- Home /
Why are the objects (they are cows) randomly disappearing?
I added this code to some cows in my game so that they would be destroyed when they collide with the outer boundaries in the game, but now they are randomly disappearing at the start. Anybody know why? Heres the code:
{
public GameObject edges1, edges2, edges3, edges4, edges5, edges6, edges7;
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject == edges1 || edges2 || edges3 || edges4 || edges5 || edges6 || edges7)
{
Debug.Log("I am inevitable");
Destroy(gameObject);
//add a puff of smoke?
}
}
}
Answer by Eno-Khaon · Dec 14, 2021 at 03:26 AM
Your if() statement is incomplete. Each portion is a discrete condition, not a "this or this or this" as you're trying to use it. In short, yours functions approximately like this:
if(collision.gameObject == edges1 || edges2 exists || edges3 exists || ...)
That said, it should be easier to look at (and effectively the same to process) if you turn the 7 GameObjects into an array:
public GameObject[] edges; // Assign them here or set size/GameObjects in script/etc.
// ...
for(int i = 0; i < edges.Length; i++)
{
if(collision.gameObject == edges[i])
{
Destroy(gameObject);
break; // Break out of loop early, since you found a match
}
}
Thank you for the quick response, I tried the code you wrote and it worked very well. The array was very useful and something I had not thought of. Like I said, the problem is solved, but I am still curious, do you have any idea why only some of the cows were disappearing and others weren't?
Honestly, it's hard to say why there would be any specific (in-)consistency about this. The key element is that it would only be applicable when OnCollisionEnter() is triggered, so maybe there are circumstances where it doesn't immediately/arbitrarily trigger in the first place?
Anyway, a thought:
If these "edges" happen to all be part of the same overall GameObject, you could also simplify this further to not need "edges" at all. If they're all child GameObjects to a shared parent, you could use something like this instead:
public Transform edgeParent;
// ...
if(collision.transform.parent = edgeParent)
{
// etc.
}
Answer by Zaeran · Dec 14, 2021 at 03:28 AM
You need to specify the == for every object.
i.e.
if (collision.gameObject == edges1 || collision.gameObject == edges2 || collision.gameObject == edges3, etc.
Your current code only tests for the first edge object on collision, and the rest of the || queries are just querying whether the assigned gameobjects exist.