[Answered](C#) Help with dealing damage to enemy from Raycast

Hello Unity Community,

I am making a top-down shooter. I want to use Raycasting for the bullets of the guns. This is my first time using Raycasting to change an amount on another script so I am having some problems.

–Edit-- : This doesn’t seem to work anymore and I did not change anything…
I got my script to change the amount of current health for one enemy, but when I duplicate that enemy and test to see if the health changed on those enemies after I shoot them, their currentHealth does not change.

–Edit–
It prints out that is has hit something so I think the problems is that the current health is not changing…

Am I doing something wrong?
Please help me with this.

Here is the raycast part of my gun script:

	void Fire()
	{
		currentBulletCount --;
		Vector3 forward = muzzle.transform.TransformDirection(Vector3.forward);
		Debug.DrawRay(muzzle.transform.position, forward * range, Color.green);

		RaycastHit raycastBullet;
		if(Physics.Raycast(muzzle.transform.position, forward, out raycastBullet, range))
		{
			if(raycastBullet.collider.tag == "Enemy")
			{
				enemyHealth = raycastBullet.collider.GetComponent<EnemyHealth>();//Gets the EnemyHealth script from the gameobject the ray hits
				enemyHealth.AddjustCurrentHealth(-damage);//subtracts damge from the current enemy health
			}
			print("I hit " + raycastBullet.collider.gameObject.name);
			//Destroy(raycastBullet.collider.gameObject);
		}
	}

And here is the Enemy Health Script:

using UnityEngine;
using System.Collections;

public class EnemyHealth : MonoBehaviour 
{
	//Public
	public float currentHealth = 100f;
	public float maxHealth = 100f;

	public bool isDead;
	
	void Update() 
	{
		AddjustCurrentHealth(0);
	}
	
	public void AddjustCurrentHealth(float adj)
	{
		currentHealth += adj;
		
		if(currentHealth <= 0)
		{
			currentHealth = 0;
			isDead = true;
		}
		
		if(currentHealth > maxHealth)
		{
			currentHealth = maxHealth;
		}
		
		if(maxHealth < 1)
		{
			maxHealth = 1;
		}
	}
}

Any help is welcome

Thanks for helping me :smiley:

The code above looks fine, assume you put a breakpoint inside AddjustCurrentHealth ti check it gets called? If not on “if(raycastBullet.collider.tag == “Enemy”)” line and step inside there.

There is a Unity tutorial doing pretty much the same code here too, jump to 35:30: https://www.youtube.com/watch?v=Va77Gq8Cm8o

There is a tutorial for that kind of game with everything you need to do it like you want

it is using raycast to hit the target obviously. you should go check it out.

Sorry for answering my own question.

I found out what I did wrong. I put two colliders on the game object because I put a collider on a empty game object then I put a sphere (and it has a collider too) inside of it. The raycast was detecting the sphere collider which was not tagged.

The above code works perfectly fine.