- Home /
Accessing a Class's Variables from within a Dictionary Element
I'm just learning how to use Dictionaries and am trying to make a catalogue of Recovery Items for my game. I've created a Recovery Item Class (with variables such as name, heal value, etc.) and am populating a Recovery Items Dictionary using the item names (strings) as the Key type and the Recovery Item (class) as the Value type, as shown below...
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class itemManager : MonoBehaviour {
public class RecItem {
public string name; // Name of recovery item
private int healVal; // Value item recovers health by
private bool oneOrAll; // T=Heals one player | F=Heals all players
public RecItem (string name, int healVal, bool oneOrAll) {
this.name = name;
this.healVal = healVal;
this.oneOrAll= oneOrAll;
}
}
public Dictionary<string, RecItem> recItems;
void Start () {
recItems = new Dictionary<string, RecItem>();
recItems.Add ("Potion", new RecItem("Potion", 100, true));
recItems.Add ("Omni-Potion", new RecItem("Omni-Potion", 100, false));
recItems.Add ("Elixer", new RecItem("Elixer", 500, true));
recItems.Add ("Omni-Elixer", new RecItem("Omni-Elixer", 500, false));
}
}
What I'm trying to figure out now is how to access the variables of the RecItems Class within each of the Dictionary's elements. I know that I can access a Dictionary's Element's value using the Key, like recItems["Potion"];
But what I need is something along the lines of recItems["Potion"].healVal; // Should return 100
or recItems["Omni-Potion"].oneOrAll //Should return false
to obtain the values of the variables within the element's RecItems class. Hopefully that made sense -laugh- Thank you in advance :)
Answer by cryingwolf85 · Jul 31, 2018 at 01:00 AM
'healVal' and 'oneOrAll' are private to the class. Make them public, like you have for 'name'.
Oh my god, I'm an idiot. Such an obvious solution -laugh- Thank you :)
Not an idiot, just a little oversight. Glad I could help.
Your answer
Follow this Question
Related Questions
check if list contains item with matching string property 2 Answers
Item Database / Dictionary 1 Answer
Database error updating inventory 0 Answers
Decorator pattern for inventory item class 0 Answers
Multiple Cars not working 1 Answer