- Home /
How do I make the bullet do damage
I already have a simple script but how do I make it so it does damage
using UnityEngine; using System.Collections;
public class Shoot : MonoBehaviour {
public GameObject bullet;
public GameObject bulletHole;
public float delayTime = 0.5f;
private float counter = 0;
void FixedUpdate ()
{
if(Input.GetKey(KeyCode.Mouse0) && counter > delayTime)
{
Instantiate(bullet, transform.position, transform.rotation);
GetComponent<AudioSource>().Play();
counter = 0;
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hit, 100f))
{
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}
counter += Time.deltaTime;
}
}
Answer by Lilbob · May 27, 2015 at 03:26 PM
Do you mean damage to another player, or an enemy? If so, you would attach a script to the enemy that has health. In the script you would have a function that handles damage.
if(Physics.Raycast(ray, out hit, 100f))
{
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
//Call function here to handle damage on enemy
}
//Other function
void TakeDamage(//maybe have a damage amount here)
{
health -= damage;
}
Answer by Sprawl · May 27, 2015 at 04:59 PM
If you want to damage the enemy that is hit. You will have to check if the object you hit is an ennemy and that apply the damage.
Let's say that you the enemies have an "Enemy.cs" script on them that has a public Health variable and that set the enemy's tag to "enemy".
Then you'd do something like :
if(Physics.Raycast(ray, out hit, 100f))
{
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
if(hit.gameObject.tag == "enemy") {
hit.gameObject.GetComponent<Enemy>().Health -= bulletDamage;
}
}
bulletDamage is a variable that you would have to set up in your Shoot.cs Script.
Your answer
Follow this Question
Related Questions
2 player damage script 1 Answer
How do I make my melee script do damage. 1 Answer
Identifying the attacker in multiplayer 0 Answers
Trouble setting a parameter with a collision 1 Answer
Bullet not destroying on collision 1 Answer