I made a ScriptableObject Item and created a preset for it:
public class Item : ScriptableObject
{
public enum ItemType
{
Key,
Consumable
}
public new string name;
public ItemType itemType;
public string description;
public int amount = 1;
public bool isStackable = false;
}
Matches.asset:
Using script I add this item asset to inventory:
SC_FPSController.inventory.AddItem(item);
public void AddItem(Item item)
{
if (!item.isStackable || itemList.Count == 0)
{
itemList.Add(item);
}
else
{
foreach (Item invItem in itemList)
{
if (invItem.name == item.name)
{
invItem.amount = item.amount;
}
else
{
itemList.Add(item);
}
}
}
}
When I remove items amount, it changes not only itemList item, but asset as well.
public void RemoveItem(Item item)
{
Item searchedItem = itemList.Find(i => i.name == item.name);
searchedItem.amount -= 1;
if (searchedItem.amount == 0)
{
itemList.Remove(searchedItem);
}
}
So when I invoke RemoveItem function, asset becomes like this:
How to fix this and what is wrong? Maybe it takes item asset as pointer?
CodePudding user response:
In order to make the changes you want in run-time, and to make sure they do not affect the original Asset call Instantiate, and use the returned value (this will make a copy from the original one).
var itemInstance = GameObject.Instantiate(asset);
itemInstance.DoWhatever();