How do I add Prefabs from Resources folder to List

It seems to be unnecessarily difficult.
I can add to an Array just fine e.g.

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

public class listResouresTest01 : MonoBehaviour
{

    public GameObject[] myArray;

    void Start()
    {
        myArray = Resources.LoadAll<GameObject>("myPrefab");
    }
}

But can’t seem to figure out the syntax for a List

Right now if I want to add Prefabs to a List I do it this way e.g.

using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class listResouresTest01 : MonoBehaviour
{
   
    public List <GameObject> myList;
    public GameObject[] myArray;
   
    void Start()
    {
        myArray = Resources.LoadAll<GameObject>("myPrefab");
        myList = myArray.ToList();
    }
}

Is there a way to add Prefabs directly to a List?

I think it’s

myList = new List<GameObject>(myArray);

did you even read my post?

I’m trying to add Prefabs to a “List” without having to add them to an Array first, then to a List

I don’t even want to use an Array

Not possible. Resources.LoadAll will return an array. However there is no reason you need to make the array a class variable, simply declare it at the method level and let it fall out of scope naturally.

2 Likes

Resources.LoadAll returns an array.

Resources.LoadAll(“myPrefab”).ToList()

if you must, but its still going to allocate that array underneath…

3 Likes

Thanks guys

BoredMormon
thanks for the explanation

JamesLeeNZ
thanks for the example code

For whoever has run into to same problem, some code for ya

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

public class listResouresTest01 : MonoBehaviour
{
  public List <GameObject> myList;

  void Start()
  {
  //List = Array of "Resources" folder to List
  myList = Resources.LoadAll<GameObject>("myPrefab").ToList();
  }
}

more details

1 Like

is ToList() depreciated?

Shouldn’t be, you’re possibly missing the “using System.Linq;” at the top ?