0
votes

I am try to find the children of the transform that I insantiate. This is my code:

public Transform GetLevel(int _currentLevel)
{
    string levelName = "Level" + _currentLevel;
    Transform level2Load = MonoBehaviour.Instantiate(Resources.Load("Prefabs/Levels/" + levelName)) as Transform;
    Debug.Log(level2Load.childCount);
    return level2Load;
}

The problem is that I am getting the following error:

NullReferenceException: Object reference not set to an instance of an object LevelLoading.GetLevel (Int32 _currentLevel) (at Assets/Resources/Scripts/LevelScripts/LevelLoading.cs:10)

Does anybody know why?

edit*

The wierd thing is that it does find the transform and instantiates it. But it can't find the chrildren.

The children do appear in the scene, and if I attatch an script to the transform that looks for the children it finds them.

1
which line is it referring to? - maksymiuk
this line Debug.Log(level2Load.childCount); - anonymous-dev
does this work? Transform level2Load = (Instantiate(Resources.Load("Prefabs/Levels/" + levelName))as GameObject).transform; - maksymiuk
Transform level2Load = (MonoBehaviour.Instantiate(Resources.Load("Prefabs/Levels/" + levelName)) as GameObject).transform; works! Could you explain why? - anonymous-dev

1 Answers

2
votes

The exception is from:

Debug.Log(level2Load.childCount);

level2Load is null. Therefore trying to access its childCount results in a null reference exception. This is probably due to the as in:

MonoBehaviour.Instantiate(Resources.Load("Prefabs/Levels/" + levelName)) as Transform;

Because as tries to typecast and returns null if the typecast is invalid, I think your issue is that the instantiated object is a GameObject, not a Transform.

Try casting to GameObject and using .transform instead:

GameObject level2Load = MonoBehaviour.Instantiate(Resources.Load("Prefabs/Levels/" + levelName)) as GameObject;
return level2load.transform;