Micard
Micard

Reputation: 389

How to instantiate GameObject from prefab using Resources.Load?

I get a NullReferenceException error when I try to instantiate a GameObject the following way:

Side1_Slots.sGameObject[i] = Instantiate(Resources.Load<GameObject>(Side1_Slots.SlotAlliedPrefab), 
            Side1_Slots.SlotPosition[i], Quaternion.identity, UIContainer.transform);

Using this overloaded method for Instantiate:

Instantiate(GameObject Original, Vector3 position, Quaternion rotation, Transform parent);

Where:

Side1_Slots.SlotAlliedPrefab = "Prefabs/Battle/SlotAlliedPrefab";

I've tried the following project folder structures:

// Leads to NullReferenceException error
Resources/Prefabs/Battle/SlotAlliedPrefab

and:

//Leads to "Object you want to instantiate is null"
Prefabs/Battle/SlotAlliedPrefab

Which one is correct by the way? Google shows both ways, so I'm not sure...

Upvotes: 1

Views: 11965

Answers (1)

Arshia001
Arshia001

Reputation: 1872

You do not need Resources in resource paths. Prefabs/Battle/SlotAlliedPrefab should do the job, provided it's the correct path to the asset. First, double-check your paths. Then, use the non-generic Resources.Load() to load the resource, then check its type (preferably with a debugger, use VSTS if you don't already). You may not have the correct asset type at that path. If Resources.Load() returns null, you probably have the wrong path, maybe a typo.


EDIT: You must store you asset in a Resources folder. But the path you pass to Resources.Load will be relative to the root of the closest Resources folder. For example, if you have an asset at:

Assets\MyGame\Models\Resources\Category1\SomeModel

You will load it like this:

Resources.Load("Category1\SomeModel")

This means that you may get undefined behavior if you have different resources with the same name inside different Resources folders. This only works for assets inside Resources folders, as they are treated differently during build and packaging.

About the non-generic Load, I mean you should do it like this:

var myResource = Resources.Load("SomePath");
var myGameObject = myResource as GameObject;

This way, you can step through your code and see what's inside myResource. This is to make sure that you're passing the correct path. If myResource is not null, you can see what type of asset it is. Maybe you're loading an audio clip instead of the prefab you're looking for.

Upvotes: 2

Related Questions