Resources.LoadAll to list. C# Please Help

I want to be able to grab prefabs from a folder and put them into a list. Here is what I have

GameObject[] gos = (GameObject[])Resources.LoadAll("Ground");
	   foreach(GameObject go in gos) {
		prefabList.Add(go);

It doesn’t actually add them to the list. I do not know where the problem is occuring

Your code seems fine, unless it can’t be ‘GameObject[ ]’ and needs to be ‘Object[ ]’.

For reference, here’s a part of my WorldManager class that simply loads all my levels (as TextAsset) (stored in “Assets/Resources/Levels/”)

public static class WorldManager {
    public const string LevelPath = "Levels";
    private static List<string> worldList;

    public static void LoadWorldList() {
        Object[] worlds = Resources.LoadAll(LevelPath, typeof(TextAsset));

        // Make sure results aren't empty or null
        if (worlds == null || worlds.Length == 0) {
            // "#WorldManager.LoadWorldList() :: No World files found!"
        }

        // Add each result to the worldList
        worldList = new List<string>();
        foreach (Object world in worlds) {
            TextAsset w = (TextAsset)world;
            worldList.Add(w.name);
        }

        // Unload them - no longer needed
        foreach (Object world in worlds) {
            Resources.UnloadAsset(world);
        }
    }

Try adding the check for empty / null to see if you are getting any results.

1 Like

It doesn’t seem to say that it’s empty, just not adding to the list. Any idea why?

you might have to post more code.

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

public class pertyMuch : MonoBehaviour {
	
	public List<GameObject> prefabList = new List<GameObject>();
	public int numberOfObjects;
	public Transform player;
//	public GameObject prefab1;
//	public GameObject prefab2;
//	public GameObject prefab3;
	private Vector3 nextPosition;

	// Use this for initialization
	void Start () {
		nextPosition = transform.localPosition;
		numberOfObjects = 13;
		GameObject[] gos = (GameObject[])Resources.LoadAll("Ground");
		foreach(GameObject go in gos) {
			prefabList.Add(go);
		}
		//prefabList.Add(prefab1);
		//prefabList.Add(prefab2);
		//prefabList.Add(prefab3);


			
	}
	
	// Update is called once per frame
	void Update () {
		int prefabIndex = UnityEngine.Random.Range(0, prefabList.Count);

		for(int i = 0; i < numberOfObjects; i++) {		
			if(nextPosition.x > player.transform.position.x - 500){
				GameObject o = (GameObject)Instantiate(prefabList[prefabIndex]);
				o.transform.localPosition = nextPosition;
				nextPosition.x -= o.transform.localScale.x;
			}
		}
		

		GameObject[] gobs = GameObject.FindGameObjectsWithTag("Ground");
		foreach(GameObject gob in gobs){
			if(player.transform.position.x + 60 < gob.transform.position.x)
				Destroy(gob);
			
		}
	}

}

That’s all of it. lol

Try adding a debug line to this code, to see if it is at least finding anything:

foreach(GameObject go in gos) {
    Debug.Log("Adding '" + go.name + "'");
    prefabList.Add(go);
}

code actually looks fine to me, but I havn’t dabbled in resource loading much, but since its not working, maybe try something like this…

void Start() 
{
foreach(GameObject g in Resources.LoadAll("Ground", typeof(GameObject)))
{
   Debug.Log("prefab found: " + g.name);
   prefabList.Add(g);
}
}

Ive intentionality included some debugging so you can be sure its actually finding something.

1 Like

That worked! I don’t know what is different but thank you very much kind sir!

The thing that may have affected it is the specification of the type. Easiest way to tell would be to try your old code again with the same extra param. Im thinking if this does work, the problem was the cast from Object[ ] to GameObject[ ] wasnt working

GameObject[] gos = (GameObject[])Resources.LoadAll("Ground", typeof(GameObject));

It IS very different.

One thing is to cast an array of objects to the array of GameObjects, and another thing is to loop through elements (and cast each object to GameObject).

Hello

Am trying to achieve something similar, but I have to load all images from Resources/Textures… Which they all have format such as png, jpg and other format. After I load it then I have to draw each image with it texture.
Thanks

I have to draw those images on a panel.

Am using unity 5.3, also am receiving an InvalidCastException: Cannot cast from source type to destination type. Precisely where am loading it

Error on line 3
Line1: GameObject gameParent = GameObject.FindGameObjectWithTag(“pnlHoldCard”);
Line2: GameObject gameCards = GameObject.CreatePrimitive (PrimitiveType.Cube);
Line3: Texture2D[ ] Cardtextures = (Texture2D[ ]) Resources.LoadAll (“”);
//
foreach (Texture2D ItemLst in Cardtextures) {
gameCards.GetComponent ().material.mainTexture = ItemLst;
}

The error is saying your code is returning an asset that is not a valid Texture2D file.
Try putting in only one Texture2D file into that folder and try again.
This will make sure your code is at least valid.
Try different graphic files too, in case Unity doesn’t support certain formats.

Hello I solved it, the reason was Resources.LoadAll() return an object then I declared a var variable to hold it.

Edit your code:

using System.Linq;
prefabList = Resources.LoadAll<GameObject>("Ground").ToList()
2 Likes

i have a similar question if anyone would please be willing to help over here

https://answers.unity.com/questions/1737339/why-is-my-list-not-populating.html