- Home /
Loading prefabs into a list
I keep getting a null reference exception on the last line. I'm fairly sure the paths are all correct (and I've tried many different variations of the path in the actual Resources.Load command), the files are actually there in the right spot, but it doesn't work. (prefabTypes[] and levelType are both strings)
DirectoryInfo dir = new DirectoryInfo("Assets\\Resources\\" + levelType);
FileInfo[] info = dir.GetFiles(prefabTypes[i] + "*.prefab");
List<GameObject> newList = new List<GameObject>();
for(int j = 0; j < info.Length; j++)
{
print(levelType + "\\" + info[j].Name);
GameObject obj = null;
obj = Resources.Load(levelType + "\\" + info[j].Name) as GameObject;
print(obj);
newList.Add(obj);
}
prefabs.Add(prefabTypes[i], newList);
"\\" is kind of like an escape character, so if the compiler tries to parse it it thinks you're telling it code. To actually have a backslash in your string, one of the ways to write it is with two "\\". Edit: even this comment box can't understand a single slash haha
Answer by proandrius · Apr 28, 2013 at 02:22 AM
Ok so the problem is that Resources.Load loads from Assets/Resources folder, you can't load from C:/...etc. For example if you want to load AssetsResourcesForestStart1.prefab, you just write Resources.Load("AssetsResourcesForestStart1"); without path and extension.
Use Resources.Load(Path.GetFileNameWithoutExtension(info[j].Name));
Oh, it stripped all \ and I thought AssetsResourcesForestStart1.prefab is a file name. But I guess you got the idea right?
Anyway, to sum-up, you need to get only a path from Resources folder (not including Resources) and file name without extension. If you have file in Assets//Resources//Level1//file.prefab, so to Resources.Load you need to give only "Level1\\file".
It's still not working. I tried "obj = Resources.Load(levelType + "\\" + Path.GetFileNameWithoutExtension(info[j].Name)) as GameObject;", and again with a slash in front of levelType, but it still comes up null. The print gives out the right folder before it, too.
Can you do print(levelType + "\\" + Path.GetFileNameWithoutExtension(info[j].Name)); and let me know what you get.
Your answer
![](https://koobas.hobune.stream/wayback/20220613101135im_/https://answers.unity.com/themes/thub/images/avi.jpg)