- Home /
Changing class data with a reference?
void UpdateData(CurrentLevel, ValueToChange, Value)
{
DataManager.worldData.CurrentLevel.ValueToChange = Value;
}
I would like to have a class like the one above where I can pass in the values as a reference so I can change different variables in the world data class. But I don't know how or if it's possible. I just keep getting errors that CurrentLevel isn't in the worldData class which it isn't but i just want to be able to pass in a variable to that. Is this possible? I just don't want to have to type this multiple times like bellow.
void UpdateMainOutput(bool Value)
{
DataManager.worldData.LVL_01.Main_Output = Value;
}
void UpdateInput_01(bool Value)
{
DataManager.worldData.LVL_01.Input_01 = Value;
}
...etc
Answer by Captain_Pineapple · Feb 02 at 09:28 PM
If i understand you correctly then basically what you want to achive is in general possible using something called "reflection". I am no expert in this so i cannot really tell you how to solve this with reflection.
One thing i can tell you though: Do try to not use reflection as it is bad for performance if you use it more often since it requires the running programm to stick it's fingers into the actual code to get variable names.
As an alternative solution i'd recommend to put your values into a dictionary. This way you can have
class LevelClass {
private Dictionary<string, bool> LevelValues = new Dictionary<string,bool>() {
{"someValue", true}, {"someOtherValue", false}
};
public UpdateValue(string key, bool value)
{
LevelValues[key] = value;
}
}
Note that this ofc has its downsides. The values can not be set from the inspector as Unity is not able to serialize Dictionaries.
Other then that it could be helpful if you'd post a complete description of your setup so that i or others might offer up solutions from a different angle through for example different data layout for your level classes.
Answer by Komohu · Feb 02 at 10:16 PM
I have a class with how my level data will be laid out
[System.Serializable]
public class LevelData
{
public string Name;
public bool Main_Output;
public string Connection_1;
public string Connection_2;
public bool Input_01;
public bool Input_02;
}
Then a class for a world data which has the level in that worlds data
public class World_01_Data
{
public LevelData LVL_01;
public LevelData LVL_02;
public LevelData LVL_03;
}
This class persists through the game and will have the current worlds data in which will be saved to a file
public class World_01_DataManager : MonoBehaviour
{
public World_01_Data worldData
}
Then in the level I'll have a level manager which will be able to change the level its in data in the world data in the datamanager
public class Level_Manager : MonoBehaviour
{
public World_01_DataManager DataManager;
void UpdateData(CurrentLevel, ValueToChange, Value)
{
DataManager.worldData.CurrentLevel.ValueToChange = Value;
}
Do you think I should try and just use dictionaries instead?