ScriptableObject 资产随其实例变化
ScriptableObject asset changes with its instance
我制作了一个 ScriptableObject Item 并为其创建了一个预设:
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:
我使用脚本将此项目资产添加到库存:
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);
}
}
}
}
当我删除项目数量时,它不仅会更改 itemList 项目,还会更改资产。
public void RemoveItem(Item item)
{
Item searchedItem = itemList.Find(i => i.name == item.name);
searchedItem.amount -= 1;
if (searchedItem.amount == 0)
{
itemList.Remove(searchedItem);
}
}
所以当我调用 RemoveItem 函数时,资产变成这样:
如何解决这个问题,出了什么问题?也许它以项目资产为指针?
为了在run-time中进行您想要的更改,并确保它们不影响原始资产调用实例化,并使用返回值(这将复制原始值) .
var itemInstance = GameObject.Instantiate(asset);
itemInstance.DoWhatever();
我制作了一个 ScriptableObject Item 并为其创建了一个预设:
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:
我使用脚本将此项目资产添加到库存:
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);
}
}
}
}
当我删除项目数量时,它不仅会更改 itemList 项目,还会更改资产。
public void RemoveItem(Item item)
{
Item searchedItem = itemList.Find(i => i.name == item.name);
searchedItem.amount -= 1;
if (searchedItem.amount == 0)
{
itemList.Remove(searchedItem);
}
}
所以当我调用 RemoveItem 函数时,资产变成这样:
如何解决这个问题,出了什么问题?也许它以项目资产为指针?
为了在run-time中进行您想要的更改,并确保它们不影响原始资产调用实例化,并使用返回值(这将复制原始值) .
var itemInstance = GameObject.Instantiate(asset);
itemInstance.DoWhatever();