-1

Do keep in mind that I am not good at Unity.

I have a Game Object with a variable called hp. I have another Game Object with a trigger collider. When the trigger runs, I want it to edit the variable hp but I don't know how to edit variables from another game object.

Please may I have some help.

1 Answers1

1

In Unity, the OnTriggerEnter(Collider other) function is called when a collision is triggered.

In argument of the function, you get a collider named other, which is a reference to the collider script your object collided with. As any script in unity, you can call other.gameObject to retrieve the colliding gameObject. From then, you can use the GetComponent function to find a script on the object.

In your case, lets say you have an object on which you put this script:

public class Player : MonoBehaviour {
    public float hp;
}

You need to create another script that handles the collision. Put this on the object that collides with your player

public class Obstacle : MonoBehaviour 
{
    public float damages;

    private void OnTriggerEnter(Collider other) 
    {  
        if(!other.gameObject.HasComponent<Player>())
            return;

        var player = other.gameObject.GetComponent<Player>();
        player.hp -= damages;
    }
}
Basile Perrenoud
  • 4,039
  • 3
  • 29
  • 52