Question is off-topic or not relevant
How to deal damage to only enemy hit?
I have a prefab enemy that naturaly has a float healthPoints, when HP gets to 0, the enemy dies. Now for my project I have to use projectiles instead of raycasting on my guns, the damage script is laying on my bullets. The problem is when i hit one enemy, all enemys get damaged. I know whats wrong here, but i dont know the right solutions, can anybody provide some insight? Here is the damage script. My question is how to get the enemy script that has been shot.
public class DealDamage : MonoBehaviour { public Transform explode; public float dmg;
private EnemyScript enemyScript;
private Shooting shooting;
void Awake()
{
shooting = FindObjectOfType<Shooting>();
enemyScript = FindObjectOfType<EnemyScript>();
dmg = shooting.gun_dmg;
}
void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag == "Enemy")
{
enemyScript.TakeDmg(dmg);
}
Debug.LogWarning("Enemy HIT!");
}
}
THIS IS FROM THE ENEMY SCRIPT public void TakeDmg(float dmgAmount) { healthPoints = healthPoints - dmgAmount; if (healthPoints < 0f) { Die(); } }
Answer by Mokomaki · Oct 05, 2019 at 09:26 AM
Ok so you are you are using
FindObjectOfType<EnemyScript>();
To get the enemy and this will just find the first object in the scene not the one you shot. You can actually use OnTriggerEnter Collider to get the reference like this:
collision.gameObject.GetComponent<EnemyScript>().TakeDmg(dmg);
Hope this helps :)
Answer by smarjanovicng · Oct 05, 2019 at 11:28 AM
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
{
other.gameObject.GetComponent<EnemyScript>().TakeDmg(dmg);
}
}
Now i get the msg: NullReferenceException: Object reference not set to an instance of an object DealDamage.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Player/DealDamage.cs:23)
This script is attached to the projectile. Thank you!
$$anonymous$$an, go look for this error in google. spend your time trying reading trying trying and trying. And learn from experience.
$$anonymous$$an, what are you talking about, dont you think I've already read trough different types of problems? I'm doing something wrong and i asked for help, no need to be a dick about it.
I think the problem is with the EnemyScript i made a simple copy of what you have here and it worked fine.