is it possible to store Class values into a dictionary?
Let me clarify the question a bit. For the sake of simplicity I'm reducing the amount of variables that I would like to store (otherwise I should have used a Struct if I've understood correctly); I'm using Unity and in my project I have:
1 Inputfield to let the user add a profile name; 1 Dropdown that stores the profiles created by the user; 2 more Inputfields that the user fills out with infos such as Age and Car's Color;
I thought I could store every profile's variable associated with a person inside a dictionary so, after googling a bit, I've come out with something like this:
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
[System.Serializable]
public class TestClass
{
public string age;
public string carColor;
public TestClass()
{
this.age = "";
this.carColor = "";
}
}
public class TestScript : MonoBehaviour
{
public TMP_InputField profileName;
public TMP_InputField age;
public TMP_InputField carColor;
public TMP_Dropdown drop;
public Button saveProfile;
public TestClass myTestClass;
public Dictionary<string, TestClass> dictionary = new();
void Start()
{
dictionary = new Dictionary<string, TestClass>();
myTestClass = new TestClass();
saveProfile.onClick.AddListener(AddProfile);
drop.onValueChanged.AddListener(delegate{ DropdownUpdateValuesShown();});
}
void AddProfile()
{
if (!dictionary.ContainsKey(profileName.text))
{
SetClasseValues();
dictionary.Add(profileName.text, myTestClass);
drop.options.Add(new TMP_Dropdown.OptionData() { text = profileName.text });
}
}
void SetClasseValues()
{
dictionary[drop.options[drop.value].text] = myTestClass;
myTestClass.age = age.text;
myTestClass.carColor = carColor.text;
}
void DropdownUpdateValuesShown()
{
myTestClass = dictionary[drop.options[drop.value].text];
age.text = myTestClass.age;
carColor.text = myTestClass.carColor;
}
}
My goal is to store the values of each profile in the dropdown menu and let the user be able to save them via button and recall them selecting the desired dropdown option. The problem is that, even though I'm able to save them, when I select a different profile in the dropdown, the values shown are the last saved. I'm not able (since I'm quite a noob) to understand if it saves them correctly but it doesn't show the corrent ones of it only save and consequentially updates the last inserted in the input fiels.
I'm able to do so with two values by using a Dictionary and a single string output from the Inputfield but with multiple values I struggle. Maybe I've misunderstood the Class concept.
Thanks in advance for your patience and help.