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!

How is 'tile' defined and initialized?

public Transform tile; i set it in unity and its a normal gameobject

2 Answers

2

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.

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.

My 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. Maybe 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.