Why Is this OverlapBox detecting its children
So I am trying to make an overlap box from a prefab to check if is overlapping something when it is Instantiated. But for some reason it is detecting itself even though I am checking to see if the overlap is detecting its children.
Here is the code radius = new Vector3(4, 1, 4); cols = Physics.OverlapBox(gameObject.transform.position, radius);
foreach(Collider col in cols)
{
if(col.transform.parent != gameObject.transform || col.transform != gameObject.transfom)
{
Debug.Log("destroyed");
Destroy(gameObject);
}
}
So I am checking to see if it has detected a child but the if statement just seems to ignore that and just destroy the object as soon as it is made. I I am also checking if it is detecting itself so I am not sure why it isn't working.
Your issue might be because you are using "OR" as oppose to "AND", with "OR" as soon as ANY condition in that if-statement is true, it will exit... With "AND" EVERY condition in that if-statement must be true before it will run. So it comes across the gameObject itself OR its child, and does not destroy it, but will destroy everything else. But I could be talking stupid cause both conditions dont fully make sense in my $$anonymous$$d at the moment...
You could also try a nested if-stament ins$$anonymous$$d... For some reason I found when only using 1 condition per if-statement it gets better results, I personally dont see why it works sometimes, but it does...
Another check you could do - ins$$anonymous$$d of destroying the object, print out: print(col.transform.name + " | " + col.transform.parent.transform.name);
And this may help you in knowing what its actually considering a "parent" and destroying, you may find your code is getting confused with an object at some point and the answer may be very obvious to you then.
Thanks. I turns out that for some reason the if statement was returning true even though what I did print what was being detected both objects were the same. So moving the script to a different object in the prefab worked.
Glad to hear that it worked out for you. I often find printing the best way to detect small errors like that myself.