- Home /
Detecting if object in array collides with another object in same array
Hey guys,
I'm trying to figure out how to detect if an object in an array collides with another object in the same array. Here's some pseudo-code:
public GameObject[] goArray;
void Update(){
goArray = GameObject.FindGameObjectsWithTag("quads");
if(goArray[goArray.Length - 1]
(collides with)
goArray[goArray.Length - 2]){
print("GameObject02 collided with GameObject01");
}
}
Thanks guys!
And what's your question? You want to test collision between all two objects in goArray?
Not exactly, just between 2 certain objects that are in the array.
Answer by KevinGelking · Jul 18, 2014 at 09:04 AM
Use Lists!
C# using System.Collections.Generic; List varName = new List();
You could do this by adding colliders to the objects and attaching a script to them which checks whether "OnCollisionEnter" or "OnTriggerEnter" is called, then send the result (itself + other object) upwards to wherever you want to handle the event from. There you can check whether the sender and other object are within the same array by doing
if(goArray.Contains(sender) && goArray.Contains(otherObject))
{
print(sender+" collided with "+otherObject)
}
What this does (works this easy only for Lists)
Another way to do it would be to iterate through the array yourself checking each object with eachother, though I don't have an example ready as how to check whether they are colliding from "outside" the object.
I can't use a List because I'm sorting the array based on the GameObjects position, and for what I understand you can't use "OrderBy(quadSort => quadSort.transform.position.y).ToArray();" with a List.