How do I properly use Scriptable Objects to create Items at runtime?

794 views Asked by At

I'm relatively new when it comes to game development, but I've spent a dozen or so hours researching about how to use Scriptable Objects (SO).

I don't know how many items my game is going to have, so I would like to automate the item-making-process as much as possible to avoid human error. I've read it's good for performance to store information in one place using Scriptable Objects:

ItemData.cs

public class ItemData : ScriptableObject
{
    public int itemID;
    new public string name;
    public Sprite sprite = null;
}

Next, I have a gameObject that loads all itemData into a dictionary on Awake:

ItemDatabase.cs

private Dictionary<int, ItemData> itemDB = new Dictionary<int, ItemData>();

void Awake()
{
    LoadItems();
}

private void LoadItems()
{
    //Load all itemData
    ItemData[] itemData = Resources.LoadAll<ItemData>(itemDirectoryPath);

    for(int i = 0; i < itemData.Length; i++)
    {
        //Set sprite of itemData, to avoid doing it manually
        itemData[i] = SetSprite(itemData[i]);

        //Add itemData to dataBase
        itemDB[itemData[i].itemID] = itemData[i];
    }
}

Lastly, I have a function for creating a gameObject of a specified itemID at runtime:

//Create new gameobject at location
public void SpawnItem(int itemID, float x, float y)
{
    //Get itemData
    ItemData itemData = getItemData(itemID);
    //Create new gameObject
    GameObject gameObject = new GameObject();
    //Set name of gameObject, add Item Script, and set position
    gameObject.name = itemData.name;
    gameObject.AddComponent<Item>().itemData = itemData;
    gameObject.transform.position = new Vector3(x, y, 0);
}

Questions:

  1. Is it considered "hacky" to create an item at runtime as shown in SpawnItem above? Do I have to manually create each item as a prefab?
  2. If using "Resources" is considered bad practice, is there a better solution besides manually dragging each item onto the ItemDatabase Script?
0

There are 0 answers