- Home /
empty GameObject is equal to null on comparison?
Transform selectedObject = SCScript.GetCurrentGameObject().transform.Find("Container/ContainerBox/ElementBox");
//Transform selectedObject = SCScript.GetCurrentGameObject().transform; //<--This works fine!!
Debug.Log("Got SelectionBox:"+selectedObject);
if (selectedObject==null) return;
MeshRenderer[] meshes = selectedObject.GetComponentsInChildren<MeshRenderer>();
The Debug.Log shows: GotSelectionBox:UnityEngine.Transform
the GetCurrentGameObject returns a selected GameObject. If I just use the commented line it works, but then I am getting to many Materials, I just want the materials in SelectedGameObject/Container/ContainerBox/ElementBox. ElementBox is an Empty GameObject, which can contain a further GameObject with Materials, that I am trying to get and change. I am checking if there is an ElementBox there, so no errors occur, but it is returning as if it were null even though there is an object there. Is this because it is an empty GameObject?. I get all materials if I just use the currentObject, which is not exactly what I want, but it works. The current GameObject is a loaded prefab and also an empty GameObject, containing multiple other GameObjects.
UPDATE: I tried this and it works ok:
Transform selectedObject = SCScript.GetCurrentGameObject().transform;
Transform[] allChildren = selectedObject.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren) {
if (child.name=="ElementBox"){
MeshRenderer[] meshes = child.GetComponentsInChildren<MeshRenderer>();
...
}
}
Answer by Tetrad · Jul 13, 2010 at 08:09 AM
I highly recommend against using Find()
by name in any and all of its forms. http://answers.unity3d.com/questions/13827/my-script-isnt-working-what-are-some-ways-i-can-start-debugging/13857#13857
Instead try putting a script on your game object returned by GetCurrentGameObject()
that contains a transform public member variable, and setting up the connection to your desired parent object on the prefab in the inspector. That way you're not trying to find it by name.
k, thats another way to do it aswell :) Guess that would be a lot quicker than my current solution
Your answer
Follow this Question
Related Questions
I wanna use Gameobject.Find(string name, bool active) 3 Answers
Why is this null? Finding a script on an object 3 Answers
Gameobject becomes null without a reason 2 Answers
Finding the root GameObjects in the scene ? 8 Answers
How to find Inactive GameObject 16 Answers