Specifically, the path is taken from an Array. I’m not an expert on C# so I can’t easily see what is wrong here;

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PrefabSetup : MonoBehaviour {

	public static List<GameObject> prefabRooms = new List<GameObject>();

	string resourcesFolder;
	string resourcesFilter = "*.prefab";

	int objectNumber = 0;
	string objectNumberAsString;

	GameObject currentObject = null;

	void Start () {
		// Sets resourcesFolder to be the correct path.
		resourcesFolder = Application.dataPath + "/Resources/Prefab_Rooms/";
	}

	void Update () {
		// Creates the prefabFiles array.
		string[] prefabFiles = System.IO.Directory.GetFiles(resourcesFolder, resourcesFilter);

		for (int i = 0; i < prefabFiles.Length; i++) {

			string path = prefabFiles*;*
  •  	currentObject = Resources.Load(path) as GameObject;*
    
  •  	Debug.Log (currentObject.ToString ());*
    
  •  	objectNumberAsString = objectNumber.ToString ();*
    
  •  	currentObject.name = objectNumberAsString;*
    
  •  	Debug.Log ("Set To: " + currentObject.ToString ());*
    
  •  	prefabRooms.Add (currentObject);*
    
  •  	objectNumber++;*
    
  •  }*
    
  • }*
    }
    What I’m trying to do is make it so there’s a “Prefab_Rooms” folder that you can simply drop .prefab files into and then when the game is run, the code will get each file and add them to a list which will be used throughout the game. I want to do this as easily as possible, whilst still loading each file individually rather than use Resources.LoadAll (So that I can make it visible to the user that each file is being loaded successfully.)
    Does anyone have any ideas what is going wrong and can you please help? I keep getting the NullReferenceException and I don’t understand why.
    (This is similar to my previous question, but since that question I’ve changed the code but still to no avail)

You have a couple of problems here. First, GetFiles() returns a full path. Resources.Load() needs a relative path to the ‘Resources’ folder. So you will need to do some processing on the strings returned by GetFiles() to have something appropriate for Resources.Load(). The second problem is that the ‘Resources’ folder does not exist in a build. So if you are tying to run this script in anything but the editor it will fail.

Assuming you need a runtime solution, you could make prefabFiles a public class variable and write an editor script that populates the list in the editor. At runtime, you would then just have to cycle through the list.