Trouble with Raycast shooting

When i shoot at a target it is mean to take 5 hits to make it disappear, but in stead its disappearing and all 5 notifications are appearing at once in the console and the target is destroyed immediately.

Gun code

public float damage = 10f;
public float range = 100f;

public Camera fpsCam;

// Update is called once per frame
void Update ()
{
	if (Input.GetButton ("Fire1")) 
	{
		Shoot ();
	}
	
}

void Shoot()
{
	RaycastHit hit;
	if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range)) 
	{
		Debug.Log (hit.transform.name);

		Target target = hit.transform.GetComponent<Target>();
		if (target != null)
		{
			target.TakeDamage(damage);
		}
	}
}

target code

public float health = 50f;

public void TakeDamage (float amount)
{
	health -= amount;
	if (health <= 0f) 
	{
		Die();
	}
}

void Die ()
{
	Destroy(gameObject);
	Debug.Log ("object destroyed");
}

Any suggestions as to why?

Hello there,

You are using Input.GetButton() in Update, which means it will return true each frame as long as the button is pressed.

You have two solutions here:

• Either you want to shoot as long as the button is pressed, in which case you would need to implement a cooldown

• Or you want to shoot once with every button press, in which case you can just replace that line with Input.GetButtonDown() or Input.GetButtonUp(). This only return true in the one frame when it goes from one state to the other.


I hope that helps!

Cheers,

~LegendBacon