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