How do i make my gun do damage?
Can someone help me make a new code or edit a code to make my gun do damage? Thanks using UnityEngine; using System.Collections;
public class Shooting : MonoBehaviour {
public Rigidbody projectile;
public float speed = 20;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Rigidbody instantiatedProjectile = Instantiate(projectile,
transform.position,
transform.rotation)
as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed));
}
}
}
Answer by joemane22 · Feb 23, 2020 at 08:39 AM
Ok, so you got your bullets to shoot I am guessing. So what else does a bullet need to do? It needs to hit something!
Add the tag Enemy and Bullet to your tags so you can tell them apart and make sure you use that Enemy tag for the enemies(you won't need it for this problem but you will find a need for it later I am sure!) you want to shoot and add the Bullet tag to the bullets you are shooting.
Now you need to be notified when that bullet hits something so you need an Enemy script. Make sure you add a collider to your enemy gameobject otherwise it will not detect the hit.
Inside the Enemy MonoBehaviour you need the following code
//Something else with a collider hit the enemy collider!
private void OnCollisionEnter(Collision collision)
{
if(collision.collider.gameObject.tag == "Bullet")
{
//a bullet has struck this enemy!
health -= collision.collider.gameObject.GetComponent<Bullet>().damage;
}
}
That should do it. If you have any more problems let me know and I will see if I can help! Good luck.
It says that namespace or type "bullet cannot be found? sorry I replied so late
That is code you have to write, create a new script called Bullet to represent your bullet items. This was just to show how to detect the hit, get the damage from the bullet and apply it to a "health" variable. That health variable should be a floating-point.
Your answer
![](https://koobas.hobune.stream/wayback/20220612223826im_/https://answers.unity.com/themes/thub/images/avi.jpg)