- Home /
Instantiate Object and set its parent throws Null Reference Error
Hey guys, i have read some answeres about that but no one works for me. I tried to create several objects and set their parent. But it seems like the objects are not created when i try to set the transform.parent value This is my code:
void OnWizardCreate()
{
GameObject parentObj = new GameObject();
parentObj.name = roomName;
if (!parentObj)
{
Debug.Log("parentObj is not existing yet");
}
else
{
for (x = 0; x < roomWidthX; x++)
{
for (z = 0; z < roomWidthZ; z++)
{
GameObject temp = GameObject.Instantiate(tile, new Vector3(x + startPosition.x, startPosition.y, z + startPosition.z), Quaternion.identity) as GameObject;
if (temp == null)
{
Debug.Log("temp is not existing yet");
}
else
{
temp.transform.parent = parentObj.transform;
}
}
}
}
when i start this function the console throws that the temp Object is not yet existing. If i do that without the if(temp == null) part then i get a Null Reference exception. Any ideas on what could solve my problems are very welcome!
public Transform tile; i set it in unity and its a normal gameobject
Answer by whydoidoit · Apr 28, 2013 at 06:14 PM
So your problem is that a Transform is not a GameObject. When you instantiate a Transform, you get a Transform - doing As GameObject returns null because it isn't a GameObject.
and you can retrieve its GameObject using itsTransform.gameObject
I assumed it was a GameObject, given the original limited question.
Answer by EliteMossy · Apr 26, 2013 at 03:55 PM
Firstly you should be checking for null BEFORE setting the name
parentObj.name = roomName;
if (!parentObj)
{
Debug.Log("parentObj is not existing yet");
}
is wrong, parentObj.name = roomName; should be in the else. Otherwise would be kind of pointless.
Also i am assuming tile is null, so do this test after void OnWizardCreate() {
Debug.Log(tile == null ? "Tile is null" : "Tile is ok!");
Only reason i can think off.
$$anonymous$$y problem is not the parent object, it says that the temp object is null, so after instantiate this object i cannot set its parent because it does not exist in this moment, maybe it would work if i wait for some time. But i saw so much others who do it like that and no one gets errors
The parentObj is not theh problem, it says that the temp object does not exist in this moment. $$anonymous$$aybe it works if i wait for some time but i saw so many others who do it like me in the code above and they do not get errors.
Your answer
Follow this Question
Related Questions
Simultaneous Null Reference Exception and expected value 1 Answer
[Solved] How to Dynamicaly assemble an Object in your Resource Folder 1 Answer
updateMassFromShapes error 2 Answers
Prefab changing dimensions when parent changed 1 Answer
Keep Instantiated GameObject while exit gamemode in unity 0 Answers