Reputation: 1271
I'm in the process of creating a Loot system. I'm nearly at the end all I have left is to fill in the DropTable
in the Inspector on my Enemy
script. For some reason my DropTable
script is serializing but, my LootDrop
class is not. My classes are essentially set up like so:
DropTable
class:
[System.Serializable]
public class DropTable
{
public List<LootDrop> loot = new List<LootDrop>();
public Item GetDrop()
{
int roll = Random.Range(0, 101);
int chanceSum = 0;
foreach (LootDrop drop in loot)
{
chanceSum += drop.Chance;
if (roll < chanceSum)
{
return ItemDatabase.Instance.GetItem(drop.itemSlug); //return the item here
}
}
return null; //Didn't get anything from the roll
}
}
LootDrop
class:
[System.Serializable]
public class LootDrop
{
public string itemSlug { get; set; }
public int Chance { get; set; }
}
Essentially, my DropTable
just contains a list of LootDrop
. However, I cannot access the individual LootDrop
instances inside of the List<LootDrop>
from the inspector. All I am doing is creating a public DropTable
variable on my Enemy
script. I feel like I have done things similar to this before and had no problem. Am I doing something wrong here? I really wanted DropTable
to be a separate class from my Enemy since the Enemy should not really care about the GetDrop()
method. However, if that is the only way then I guess it'll have to do. Any help on this matter would be appreciated.
Upvotes: 4
Views: 14556
Reputation: 2377
Unity will serialize fields, not properties. Either switch to fields:
[Serializable]
public class LootDrop
{
public int Chance;
}
Or use a serialized backing field:
[Serializable]
public class LootDrop
{
public int Chance
{
get { return _chance; }
set { _chance = value; }
}
[SerializeField]
private int _chance;
}
Upvotes: 7
Reputation: 13146
You should initialize the loot
variable before trying to add items.
[System.Serializable]
public class DropTable
{
public List<LootDrop> Loot;
public DropTable()
{
Loot = new List<LootDrop>();
}
}
Also, be careful with name conventions.
Upvotes: 0