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;
}
}