Calling external function affects all instances of object

I’m attempting to have a bullet deal damage to an object. Right now I have the bullet call a function from the object it collides with to reduce that objects “health” by a set amount. But whenever a bullet collides with an instance of the object, all of the instances have their “health” reduced. After some debugging it looks like the function only runs one time (ie, only the single object’s script is actually called) but that single call is altering the “health” variable on all of its siblings. How can I change this so it only alters the single object the bullet collides with?

bullet script:

public class bulletStats : MonoBehaviour {
    public float damage;
    // Use this for initialization
    void Start () {
        damage = 5;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.transform.tag == "enemy")
        {
            other.GetComponent<enemyHealth>().takeDamage(damage);
            Destroy(gameObject);
        }
    }
...

health script:

public class enemyHealth : MonoBehaviour {
    public float health;
  
    //damage the enemy
    public void takeDamage(float damage)
    {
        health = health - damage;
        Debug.Log("Hit me, baby, one more time!");
    }
...

What happens if you start each object out with a unique health value, say one with 10 points, one with 11 points, then apply one point of damage?

The script is still called for each object, lowering each object’s health by the same value (100 became 90, 60 became 50. 80 became 70, etc).

Weird. Nothing in your code points to this problem. Here are some common causes you might find somewhere else.

  • A misuse of static somewhere.
  • Checking for input in Update on every instance.

I don’t see either of those in your scripts, but they might be hidden somewhere else?

Nothing in Update changes the “health” variable and I haven’t made anything static as far as I can tell.
other.GetComponent should only be retrieving information from the instance it detects, right?

Correct. How many times is the debug message being shown per collision?

Six times, the same number of instances in the scene. It scales with the number of instances, that is how I know its calling it for each instance

Something appears to be wrong with OnTriggerEnter. I add a debug log to the bullet script and it is being called for each instance whenever the bullet hits the object.

Solved: My colliders were outrageously large for some reason, the bullet was actually colliding with everything at once

2 Likes

Glad you got it solved. I’ll add that to my list for the next person.