- Home /
Can I use a string to point to the Resources directory?
Is it possible to use a string to point to the location of a prefab in the Resources directory?
I'm writing a template that defines the stats and type of enemy that will show up when my game runs so I can change out the stats and enemy thumbnail when it runs.
Here is an example of how I'm hoping it can work:
public static string monsterPrefab = "Prefabs/monsters/monster_000";
void monsterImage ()
{
GameObject myMon = (GameObject)Instantiate(Resources.Load(monsterPrefab));
myMon.transform.position = new Vector3 (-2.097f, -3.53f, 50f);
}
It throws this error:
ArgumentException: The thing you want to instantiate is null. UnityEngine.Object.CheckNullArgument (System.Object arg, System.String message) UnityEngine.Object.Instantiate (UnityEngine.Object original) spawnMultiObject.monsterImage () (at /Users/glasstongue/new unity project/Assets/scripts/gameScripts/spawnMultiObject.cs:383) spawnMultiObject.Start () (at /Users/glasstongue/new unity project/Assets/scripts/gameScripts/spawnMultiObject.cs:121)
Is it possible to call Resources.Load like this?
Answer by rutter · Jun 04, 2014 at 05:24 AM
The exact thing you're trying to do won't work, but there are other options that are very similar (and will work!).
You can use a string to refer to any asset in a Resources
folder. See scripting manual.
If you prefer, you could have a public variable, set in the inspector, which refers to a prefab that you'd like to spawn.
Actually, I got it working - it was a missing Collections.Generic in my template file that finally did it.
Despite me being the reason I'm pulling all my hair out - Unity is really an awesome tool.