- Home /
The question is answered, right answer was accepted
Why OnTriggerStay applies this action on all colliders
Hello,
I have a collider.tag set on multiple AIs of the same type in the scene. When one of the AI enters a damage OnTriggerStay area, all the AIs in the scene take the damage, not only the triggering AI.
The code:
void OnTriggerStay(Collider col)
{
if(col.tag == "SpiritForm" && counter > 0)
{
theTarget = col.gameObject;
RateCount += Time.deltaTime;
if (RateCount >= Rate)
{
if(theTarget != null)
{
theTarget.SendMessageUpwards("GotHit", Damage, SendMessageOptions.DontRequireReceiver);
GameObject newGameObject = (GameObject)Instantiate(prefabToInstantiate, theTarget.transform.position, Quaternion.identity);
RateCount = 0.0f;
counter -= 1;
}
}
}
Where am I screwing things up?
Answer by ThePunisher · Nov 21, 2013 at 10:44 PM
I'm not sure what the hierarchy of the objects looks like but in order to avoid the problem all together you could just do the following to ensure only the GameObject that is inside the collider will get damaged.
void OnTriggerStay(Collider col)
{
if (col.tag == "SpiritForm" && counter > 0)
{
theTarget = col.gameObject;
RateCount += Time.deltaTime;
if (RateCount >= Rate)
{
if (theTarget != null)
{
TheComponentWithGoHit comp = theTarget.GetComponent<TheComponentWithGoHit>();
comp.GoHit(Damage);
GameObject newGameObject = (GameObject)Instantiate(prefabToInstantiate, theTarget.transform.position, Quaternion.identity);
RateCount = 0.0f;
counter -= 1;
}
}
}
}
Thanks man, that indeed solved the issue. Will mark you answer now.
Answer by aldonaletto · Nov 21, 2013 at 11:13 PM
This smells like a "static variable curse": if the AI health variable is declared as static, all AIs will suffer whenever one of them gets hurt. A static variable pertains to the class, not to the instance, thus all scripts where it's declared share the same variable. If this is the case, remove the static keyword.
That's because I've sensed that smell many times before in my own scripts...
:D Unfortunately he didn't post the script that has the GoHit method on it :(
Hi guys,
Your idea is good aldonaletto and that was the first thing I double checked(had this issue many times before myself) but it's not the case here. The health variable is not defined as static.
When I send the damage message by other methods, it works just fine. So the problem is really in this method, in the way I define the 'target'.
I will check and get back to you guys. Thank you!