- Home /
How to distinguish between different collisions?
Trying to get collisionInfo for two simultaneous collisions. I'm new to this so bear with me.
I want to eventually be able to compile the GetContact.normal
so that I may take the mean of the normals for each contact point for all the collisions.
The code below is as close as I've managed to get but when adding the collision 'other' to the list, every time another OnCollisionEnter
occurs the value of 'other' in the list is also overwritten.
The result is the gameObject.name of the last collision is called again for however many objects are currently being collded with.
Here's where I'm at so far:
private List<Collision> collisionsInfo = new();
public void OnCollisionEnter ( Collision other )
{
collisionsInfo.Add(other);
foreach (Collision col in collisionsInfo)
{
Debug.Log(col.gameObject.name);
}
}
My goal is to somehow compile all the collision normals (of at least two concurrent collisions) at any one time (when key is pressedDown
) and use them.
If there is a way to make this code work, or to use a different method that solves my issue, that would be fantastic! Thank you.
Answer by Captain_Pineapple · Apr 19 at 08:52 AM
The problem you face here is that Unity reuses the Collision objects for performance reasons.
The result of this is that since you save a reference to the object it gets overwritten with new values.
You could do a deep copy of the object on Collision to fight this but i'd suggest to not do this as you'd copy a lot of useless values as well.
A better way imo would be to introduce your own struct:
public readonly struct collisionData {
public readonly string name;
public readonly Vector3 collisionNormal;
public collisionData(string name, Vector3 collisionNormal)
{
this.name = name;
this.collisionNormal = collisionNormal;
}
}
Then when a collision occures simply save the data into a new object of this:
private List<collisionData> collisionsInfo = new ....();
public void OnCollisionEnter ( Collision other )
{
collisionsInfo.Add(new collisionData(other.gameObject.name, other.GetContacts(0).normal);
foreach (var col in collisionsInfo)
{
Debug.Log(col.name);
}
}
Answer by DoodleDragoness · Apr 28 at 12:20 PM
Thank you! I need to take a deeper look into structs in order to better utilise them but this looks like a great way to do it!
Your answer
![](https://koobas.hobune.stream/wayback/20220613055529im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Average the hit info from a list of GameObject's RaycastHits. 2 Answers
Obstacle avoidance 1 Answer
Why does this script check for raycast collision? Is it necessary? 1 Answer
Help Understanding Raycast 2 Answers