- Home /
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 :)
Yeah, there's nothing "wrong" with this. I've certainly heard of folks using this approach for melee detection; getting fancier, you might have an animation of the arms, legs, or weapon props which have triggers attached; this would offer more specific detection (where the hit occurs; what body part or weapon did the hitting).
Checking for a tag is not essential; putting your objects on specific layers that allow collision detection is cheaper where possible; checking for a script is a more direct approach than checking for a tag or name.
AgentScript agent = other.GetComponent<AgentScript>() as AgentScript;
if (agent) agent.TakeDamage(someDamage);
Answer by Defetysta · Nov 21, 2018 at 02:21 PM
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.
Answer by unity_cE1vOYgSOQANyg · Nov 21, 2018 at 12:22 PM
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;
}
}