The Object You want to instantiate is null?

I keep receiving this error when I try to instantiate a prefab. Yes, I have linked prefab to the GameObject inside the C# script and yet it still gives me this error. Yes I have tried Resource.Load as well and that also failed. The prefab is in my assets folder. this is my code so far.

public class Surface : MonoBehaviour
{

    public GameObject SurfacePrefab;
    public List<Entity> Players;
	void Start ()
    {
        Players = new List<Entity>();

        Instantiate(SurfacePrefab);

        Entity Player = new Entity();
        Player.CreateGameObject();
        Players.Add(Player);

    }
    void Update()
    {

    }
}

Player.CreateGameObject(); is where the exception occurs.

public void CreateGameObject()
    {
        Instantiate(EntityPrefab, Position, Quaternion.identity);
    }

And EntityPrefab is linked to the prefab which is just a sphere.
83164-link.png

It looks like your “Entity” class is actually a MonoBehaviour. MonoBehaviours can not created with “new”. So those lines doesn’t make any sense:

Entity Player = new Entity();
Player.CreateGameObject();

Even when you could create an Entity with new, it’s EntityPrefab variable would not be set to anything.

Hi @iocp,
I would try something like this instead.

public class Surface : MonoBehaviour
{

    public GameObject SurfacePrefab;
    public GameObject EntityPrefab;
    public List<Entity> Players;
    void Start()
    {
        Players = new List<Entity>();

        Instantiate(SurfacePrefab);

        CreateGameObject();

    }
    void Update()
    {

    }

    public void CreateGameObject()
    {
        GameObject player = Instantiate(EntityPrefab, Position, Quaternion.identity) as GameObject;
        Entity playerEntitiy = Player.GetComponent<Entity>();
        Players.Add(playerEntitiy);
    }
}

Ofcourse you would then have to edit your prefabs in the editor.

Hi @iocp,

If you’re instantiating a GameObject you’ll need to cast is as such by adding ‘as GameObject’ after the instantiate call. i.e:

public void CreateGameObject()
     {
         Instantiate(EntityPrefab, Position, Quaternion.identity) as GameObject;
     }

Hope you get you’re resolution.