Get a game object's reference from collision?

I’m attempting to make a melee script for my player character, I have placed a trigger sphere collider in-front of the player, and was wondering if I could use this collider to get the reference of the gameobject of any enemy that enters the collider, and then use that reference to get the enemy’s health script, and call a function on it.

	void OnTriggerStay(Collider other) 
	{
		if (other.gameObject.tag.Equals("Enemy"))
			enemyGameObject = other.gameObject; // or something like this?       
	}

If this is possible, could someone please tell me the proper way to do it, or give me advice on a better way to do melee? (im a novice so the simpler the better)

thanks in advance :slight_smile:

Hi there,

First of all, if you want to detect enemy getting hit, it’s better to use OnCollisionEnter, since OnCollisionStay is called each and every frame, so it would get called probably more times than you intended.

The code you are interested in looks probably something like this

private void OnCollisionEnter( Collision collision )
    {
        GameObject other = collision.gameObject;
        if (other.CompareTag("Enemy"))
        {
            other.GetComponent<EnemyController>().CallYourFunctionHere();
        }
    }

Second of all, you can cache reference to collision.gameObject so you don’t have to reference it twice.

the code showed in the question should if you attach it to the gameObject that collides with the enemy like the main character, then the other argument in the *void OnTriggerStay(Collider other) * will be a reference to any object the main character collides with, then you can do something like rest health

void OnTriggerStay(Collider other) 
     {
           if (other.gameObject.tag.Equals("Enemy")) {
                 other. health = other. health - 2;
           }
     }