Hello friends.
I need to access to all collisions applied to a game object outside of OnCollisionStay function.
I’ve created a collision array and stored all collisions in it in OnCollisionStay function.
But i think it’s not a good solution because removing them in next run is hard and maybe make lots of garbage.
Is there any other solutions to do this?
Of course I don’t know the details, but if you want to store them, add in OnCollisionEnter and remove in OnCollisionExit. No need for OnCollisionStay.
Thanks Jasper. But it doesn’t work.
When an object make a collision to my own object, it adds a collision to list.
But in debug mode when i move my own object touching that one, no new collision with new contact is added to the list.
Same old contact stays in the list.
When my object stop touching and retouch again, a new contact (collision) is added and old one doesn’t be removed.
Here is my code:
List<Collision> collisions = new List<Collision>();
void OnCollisionEnter(Collision collision)
{
if (!collisions.Contains(collision))
collisions.Add(collision);
}
void OnCollisionExit(Collision collision)
{
if (collisions.Contains(collision))
collisions.Remove(collision);
}
void Update()
{
foreach (Collision collision in collisions)
{
foreach (ContactPoint contact in collision.contacts)
{
Debug.DrawRay(contact.point, contact.normal, Color.blue);
}
}
}
I also removed “if (collisions.Contains(collision))” lines but it again doesn’t work.
If you please test this code, you do me a favor.
Thanks.
I assumed you wanted to keep track of each gameobject that’s touching (collisions are unique per event). But it seems you want to keep a record of all contact points over time (which are a lot). Is that correct?
I just want to store all contacts to my object in an array and use it in current game update or next. The array must be refreshed in every frame. I want to use this array in other methods. There won’t be too much existing game objects in one frame. Max 50.
If you want to keep track of the latest collisions, you’ll have to empty the list each physics update and then fill it again on OnColissionEnter and OnCollisionStay. Or perhaps accumulate every collision’s data, draw them all in Update, and then clear the list. Alternatively, raise a flag in Update so that only the next physics update collects collisions instead of them all. Which approach is acceptable depends on your exact needs.
Ok. Good ideas. I’ll try these. Thank you very much Jasper for helping.