- Home /
Load ScriptableObject / asset file and save as object to list
Im totaly new and playing around with unity and stumbled upon a problem i can't seem to google my way out of. I have created a bunch of scriptable objects to hold information of different items. When the game starts im trying to load all the asset files and add them to a list of the same type as the objects.
Here is my scriptableObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Item", menuName = "Item")]
public class Item : ScriptableObject
{
public string ID;
public Sprite icon;
public void show()
{
Debug.Log(icon);
}
}
They are saved at "Assets/Resources/Items/id.asset"
When the game first loads im trying to add them to a static list for easy access like this:
public class ItemIDList : MonoBehaviour
{
public static List<Item> ItemList = new List<Item>();
public Item TempItem;
public string IDString = "id1/id2/..../idn";
void Awake()
{
string[] IDs = IDString.Split("/");
foreach (string id in IDs){
TempItem = Resources.Load<Item>("Items/" + id);
ItemList.Add (TempItem);
}
}
}
But it doesn't matter what index i call on
ItemIDList.ItemList[index];
I always get the runtime error index out of range. Im grateful for any kind of help which can lead me in right direction thanks!
Answer by l4mers · 2 days ago
So i managed to solve my problem. This is how it was done.
public class IDList : MonoBehaviour
{
public static List<Item> ItemList = new List<Item>();
public Object[] Items;
void Awake()
{
Items = Resources.LoadAll("Items", typeof(Items));
foreach (Item item in Items){
Instantiate(item);
ItemList.Add(item);
}
}
}
If anyone have a better solution please feel free to share. I can't however see the attributes in the editor for each item. I guess i need a
CreateAssetMenuAttribute
for that. However it is not needed in this case.