- Home /
Enemy wont take Damage. How could i fix this?,Enemy wont take damage with raycast
The code i currently have is
using UnityEngine;
public class Target : MonoBehaviour {
public float EHealth = 50f;
public void TakeDamage(float amount)
{
EHealth -= amount;
if (EHealth <= 0f)
{
Destroy(gameObject);
}
}
} for the enemy and using UnityEngine;
public class Shooting : MonoBehaviour { public float Damage = 10f; public float Range = 100f; public Camera fpsCam; void Update() {
if (Input.GetButtonDown("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 = GetComponent<Target>();
if (target != null)
{
target.TakeDamage(Damage);
}
}
}
}
for my gun
Comment
Answer by unity_ek98vnTRplGj8Q · Apr 20, 2020 at 03:07 PM
Using GetComponent
will try to find the Target script on the same object where your shooting script is. Try hit.gameObject.GetComponent<Target>()
instead.
Your answer
Follow this Question
Related Questions
Staged bullet damage? 1 Answer
Rapid fire does damage every frame 0 Answers
Enemies sharing health 2 Answers