So I’ve got a number of objects in my scene tagged, and to simplify work in the editor I’ve written this code snippet (javascript) in function Awake().
for (var collisionObj : GameObject in GameObject.FindGameObjectsWithTag("Collider"))
{
collisionObj.AddComponent("ShowContact"); // adds a script
if (!collisionObj.BoxCollider) // check if it has a collider
{
collisionObj.AddComponent(BoxCollider); // if not, add one
}
}
Objects without colliders have them added without issue. Problem is, I keep getting the warning:
“Can’t add component’BoxCollider’ to abunchofstuff because such a component is already added to the game object!”
It doesn’t seem to be affecting performance, but I get anxious when my console fills up like this. I’ve tried checking with both !BoxCollider as well as BoxCollider == null, and get the same result.
Am I misunderstanding how to check for an existing BoxCollider?
I’m coding in C#, so I might be completely wrong, but I don’t think you could access the box collider of an object with .BoxCollider. Anytime, if you’re referencing a component, the first is lower case, so even if this variable exists (according to the documentation, it doesn’t), it should be boxCollider. One way to solve this, is if it’s not important that it’s a BoxCollider, to use:
if (!collisionObj.BoxCollider)
If it’s important that it’s a BoxCollider, then:
if (!collisionObj.collider || collisionObj.collider.GetType() != typeof(BoxCollider) // !collisionObj.collider comes first, so that there's no null reference error
collisionObj.collider = NULL if there is no collider attached.
Do these gameObjects tagged “Collider” have other colliders that you are concerned with? If not, just check if there is a collider, not necessarily a BoxCollider.
EDIT: I think this should work.
for (var collisionObj : GameObject in GameObject.FindGameObjectsWithTag("Collider"))
{
collisionObj.AddComponent("ShowContact"); // adds a script
if (collisionObj.collider) // check if it has a collider, null if no collider
{
Debug.Log("Collider attached to this GameObject");
}
else
{
collisionObj.AddComponent(BoxCollider); // if not, add one
}
}