Instantiating prefab game objects not workin

Hey. So, I have script that instantiates objects from an array randomly, but the Resources.LoadAll function is not finding the game objects for some reason. Debug.Log prints null. The folder name is correct (checked a bunch of times) and it is located at the root of resources. Here’s the code:

using UnityEngine;
using System.Collections;

public class PersonSpawner : MonoBehaviour {

    public GameObject[] personArray;
    public Boundary boundary;

    void Awake () {

        personArray = Resources.LoadAll("Persons") as GameObject[];

    }

    void Start () {
   
        InvokeRepeating ("SpawnPerson", 0.0f, 1.5f);
        Debug.Log(personArray);
    }

    void SpawnPerson () {

        Vector3 randomPosition = new Vector3
            (
                Random.Range (boundary.xMin, boundary.xMax),
                Random.Range (boundary.yMin, boundary.yMax),
                -1.25f
            );

        if(CubeMover.keepClosed == false)
        {
            GameObject person = Instantiate
                (
                    personArray[Random.Range(0,personArray.Length)],
                    randomPosition,
                    Quaternion.identity
                )
                    as GameObject;   
        }

Can you try this instead and see if that changes anything? I vaguely remember having a similar issue but cannot for the life of me remember the fix, this may or may not be it as this will only load assets that are GameObjects, where as yours is returning ALL assets in the folder and if they are not a GameObject the “as” may be the cause of the null.

personArray = Resources.LoadAll<GameObject>("Persons");

Hmm, the game objects are still not added to the array, but it changed the Debug.Log’s output to “UnityEngine.GameObject[ ]”. What could that indicate?

It would hopefully mean it has loaded something, so in that case we can check how many it has loaded.

Debug.Log(personArray.Length);

If it’s 0, then there isn’t any GameObjects it can see in the folder given, which would be strange if you are definitely sure that there are.

Yup, it’s printing 0. There are three game objects in the Persons folder, here’s a screencap: Imgur: The magic of the Internet

The PersonSpawner script is linked to the GameController game object that only has that one script on it.

Ooooooh I see the problem now, your folder is not in the correct place, that’s showing as “Assets/Persons”, to work with Resources it needs to be “Assets/Resources/Persons”.

Ah! Thanks man, I’ll try that out. :slight_smile:

Might I suggest this code as well:

GameObject ObjVariable = (GameObject)Instantiate(Resources.Load(FolderInResources/Resource))