Hi, i want to use a dictionary as an item database for my game. I could use a monobehaviour and put the script on every objects that needs to use the itemData but i dont really want to do it so:
I use a custom class called ItemData with a dictionary of string as key and Item as type.
I want to add keys at startup and i dont really know how to do it. Well, you’ll see in my script.
Unity doesnt react really bad, i get no error.
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Item
{
public enum ItemType{Sword,Shield,Consumable,Misc};
public int ID;
public string Name;
public Texture2D Icon;
public ItemType Type;
public GameObject StaticMesh;
public AudioClip DropSound;
}
public class ItemData{
public static Dictionary<string, Item> items;
public static Dictionary<string, Item> Items {
get {
if (items == null)
{
LoadItemsData();
}
return items;
}
}
public static void LoadItemsData(){
items = new Dictionary<string, Item>();
Item newItem = new Item(){
ID=0,
Name="Money",
Icon=null,
Type=Item.ItemType.Misc,
StaticMesh=Resources.Load("Data/Items/Money",typeof(GameObject)) as GameObject,
DropSound=Resources.Load("Data/Items/MoneySound",typeof(AudioClip)) as AudioClip
};
items.Add (newItem.Name,newItem);
newItem = new Item(){
ID=1,
Name="Coin",
Icon=null,
Type=Item.ItemType.Misc,
StaticMesh=Resources.Load("Data/Items/Coin",typeof(GameObject)) as GameObject,
DropSound=Resources.Load("Data/Items/MoneySound",typeof(AudioClip)) as AudioClip
};
items.Add (newItem.Name,newItem);
}
public static Item GetItem(string name){
Item temp = null;
if(items.TryGetValue(name,out temp)){
return temp;
}else return null;
}
}
I get a NullReferenceException: Object reference not set to an instance of an object on my line if(items.TryGetValue(name,out temp)){ when i call the method “GetItem”. So my dictionary doesnt seem to be created.
If you have any idea, thanks ![]()