- Home /
Dictionary with GameObject as key is updating values under other keys
I'm trying to see if an object has collisions on opposite sides, suggesting it is pinned inbetween two other objects. In order to do this, I'm maintaining a dictionary with GameObject keys and Collision values, then going through all combinations of Collisions and getting the angle between their contact normals.
private Dictionary<GameObject, Collision> collisions;
private List<GameObject> gameObjects;
void OnCollisionEnter(Collision collision){
if (collisions.ContainsKey(collision.gameObject)){
collisions[collision.gameObject] = collision;
}
else{
collisions.Add(collision.gameObject, collision);
}
gameObjects.Add(collision.gameObject);
}
void OnCollisionStay(Collision collision){
float angle = 0;
if (collisions.ContainsKey(collision.gameObject)){
collisions[collision.gameObject] = collision;
}
else{
collisions.Add(collision.gameObject, collision);
}
//Step through the list of GameObjects to get all combinations of Collisions
//Only get first contact from Collision for current iteration of code, make robust later
for (int i = 0; i < gameObjects.Count; i++){
for (int j = i + 1; j < gameObjects.Count; j++){
angle = Vector3.Angle(collisions[gameObjects[i]].GetContact(0).normal, collisions[gameObjects[j]].GetContact(0).normal);
if (angle > 170 && angle < 190){
isPinched = true;
return;
}
}
}
}
The problem I'm having is that when I check the normals that are being compared in OnCollisionStay, they are all the same. Specifically, it seems like all values in the Dictionary are being overwritten by the most recent Collision. Am I storing a reference to the Collision that is being overwritten each time OnCollisionStay occurs? Am I missing something very obvious? I've been working at this for days without any luck.
Thank you.
Answer by ceaston7 · Mar 03, 2019 at 12:37 AM
From some testing, it appears that storing the Collision as a value stores a reference to an object that is constantly being overwritten. So instead I used a Dictionary structure and store the contacts array from the collision.
Your answer
Follow this Question
Related Questions
If Check Colliding GameObject Variable 1 Answer
unity2D colliders not working properly,,Unity2D Colliders don't seem to be working HELP PLEASE! 0 Answers
How to move a Game Object from a script not attached to it. 1 Answer
collisions in character not working! 2 Answers
Issue with GameObject has been destroyed but it is not destroyed 1 Answer