Sorry for the vague title, it’s hard to explain in one sentence but it’s not complex either.
I have a custom class for items, with a few values like value and damage. I also have a list of some instances of these classes, acting as an inventory. Of course it’s possible that the lists contains multiple instances that have the same values (but should really be distinct items).
There could be two daggers with the same values and one sword with different values, for example.
Herein lies the problem: Wheniver I access one of the instances in the list to change, say, the damage, all other instances that share the same values get changed as well! Why?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class test : MonoBehaviour {
[System.Serializable]
public class Item {
public string name;
public int value;
public int damage;
}
public Item daggerTemplate = new Item { name = "Dagger", value = 10, damage = 20 };
public Item swordTemplate = new Item { name = "Sword", value = 100, damage = 50 };
public List inventory;
void Start() {
inventory = new List();
Item item1 = daggerTemplate;
item1.value = 2;//this causes all other daggers to change their value to 2 as well
inventory.Add(item1);
Item item2 = daggerTemplate;
inventory.Add(item2);
Item item3 = swordTemplate;
blubbListinventory.Add(item3);
}
}