Im working on a combat system for my game. I plan on having any damage a player would take being done via a function inside the players health script. What I would like to know is there a way to call this function without having to reference the playerscript inside every enemy and object that would hurt the player?
You could use Unity’s SendMessage. All you have to know then is the GameObject that you’re trying to send the message to. It would look something like this:
void OnCollisionEnter(Collision collision)
{
collider.gameObject.SendMessage("DoDamage", 5, SendMessageOptions.DontRequireReceiver);
}
Additionally, you could get the component during a collision.
void OnCollisionEnter(Collision collision)
{
Player player = collision.gameObject.GetComponent<Player>();
if (player != null)
player.DoDamage(5);
}
There’s nothing wrong with either one, but I think GetComponent is slightly faster.