OnTriggerStay2D() for 2 colliders simultaneously
I'm using an OnTriggerStay2D()
function that does something while an object in inside the collider (doesn't matter what). However, sometimes I have another, so a total of 2 colliders that may stay inside that collider. The two colliders are not on the same Game Object
. I'm trying like this:
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.CompareTag("Obj1"))
{
//do something
}
if (other.gameObject.CompareTag("Obj2"))
{
//do something else
}
}
but do something else just never happens when Obj1
is already inside. How to make a collider sense two colliders at once for OnTriggerStay2D()
?
Answer by UnityCoach · Jan 23, 2017 at 11:05 PM
You can't. At least, not using OnTriggerStay2D
which is called once for every collider2D that stays in the trigger for that frame.
You may initialise a List<Collider2D>
, add the colliders in OnTriggerStay2D
, then in LateUpdate or FixedUpdate (see which ones comes after the calls), do your stuff and reset the List.
List<Collider2D> colliders;
void OnTriggerStay2D(Collider2D other)
{
if (!colliders.Contains(other))
colliders.Add (other);
}
void LateUpdate ()
{
Debug.Log (colliders.Count); // make sure the list contains the colliders in LateUpdate, I'm not sure.
// do your magic here
colliders = new List<Collider2D>();
}
Your answer
Follow this Question
Related Questions
Collision With Text 0 Answers
OnCollisionEnter2D not calling, but objects are colliding. 1 Answer
Collision detection 1 Answer
How to kill enemy when the bullet hits the BoxColllider2D? 1 Answer