DirtyNative
DirtyNative

Reputation: 2834

How to load prefab properly

I want to instantiate a Prefab by it's name (and path), which comes from my server, from my Assets folder and came across some issues. I found multiple ways of doing this:

var prefab = Instantiate(Resources.Load("prefabName")) as GameObject;

This is suggested by most threads but as described here you should not use it.

var prefab = Instantiate(UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(path));

This is the second way I found but this will only work when working inside the Editor. Building the project to a WebGl for example will immidiatly throw a build error.

So what is the proper way to instantiate a prefab then?

Upvotes: 2

Views: 4181

Answers (2)

Nicolas
Nicolas

Reputation: 479

Are you importing assets into your already built game? Or are you refering to assets that are already in your project?

Because if you want to import on runtime you could use AssetBundles. Unfortunately I can't really help you with that since I have no real experience on working with them, but I have read somewhere that many mobile devs use them to distribute their asset on game launch.

Maybe the Asset Bundle Manual helps you with that.

If you want to Instantiate prefabs that are already in your project you could use a Dictionary<string,GameObject>. Like that:

public Dictionary<string, GameObject> prefabDict = new Dictionary<string, GameObject>();


public void SpawnPrefabFromDict(string name)
{
    Instantiate(prefabDict[name]);
}

The string as key then point to its value - your prefab!

Hope this helps! Good Luck!

Upvotes: 2

Nikaas
Nikaas

Reputation: 628

Why not simply add a (serializable) field in your MonoBehaviour:

[SerializeField] private GameObject myPrefab;

or

public GameObject MyPrefab;

Drag your prefab in the inspector, then below in your code:

GameObject clone = Instantiate(myPrefab);

The difference with this approach is that your prefab is preloaded in memory, i.e. when you instantiate you read from memory (as opposed to disk).

Upvotes: 2

Related Questions