I'm a quite confused about Scriptable Objects. For example, can I use 'new' when I create a Scriptable Object? If I can't use 'new', how can I use it, and how do the code examples I provided below work?
This is my Player script that detects when the player touches the Item.
public class Player : MonoBehaviour
{
public Inventory inventory;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Item"))
{
int itemId = collision.GetComponent<ItemWorld>().item.id;
string itemName = collision.GetComponent<ItemWorld>().item.name;
int itemAmount = collision.GetComponent<ItemWorld>().item.amount;
inventory.AddItem(itemId,itemName,itemAmount);
Destroy(collision.gameObject);
}
}
}
This is the ScriptableObject script that hold Items attributes.
[CreateAssetMenu(fileName = "Item", menuName ="ItemSystem/BasicItem")]
public class Item : ScriptableObject
{
public int id;
public string name;
public int amount;
public Item(int _id,string _name,int _amount) {
this.id = _id;
this.name = _name;
this.amount = _amount;
}
}
Here is an inventory script that adds items to a list based on incoming values.
public class Inventory : MonoBehaviour
{
public List<Item> InventoryList = new List<Item>();
public void AddItem(int _itemId,string _itemName, int _itemAmount)
{
Item newItem = new Item(_itemId,_itemName,_itemAmount);
InventoryList.Add(newItem);
}
}
I learned on Internet that I can create Scriptable Objects using CreateInstance, but I didn't fully understand how to do it.