It's possible to pass a reference to a variable (rather than just its value) into another function with the keyword ref
. It's also possible to get a variable name with nameof(variableName)
. However, I'm not sure how to solve my current problem.
With Unity saving/loading, it's not uncommon to have a line like:
level = PlayerPrefs.GetInt("level", level);
I feel that rather than typing level
three times in a line, I should have a short little function like:
LoadPref(ref level);
void LoadPref(ref int pref)
{
pref = PlayerPrefs.GetInt(nameof(pref), pref);
}
Then every new pref
can be added with another simple LoadPref
call, writing it once and removing any potential issues with magic strings. However, the problem is that nameof(pref)
returns pref
, even though I really want it to return the name of the referenced variable.
Is there a way to get the name of the referenced variable as a string?
This is not a duplicate of Finding the variable name passed to a function, as for that nameof(pref)
would be the solution - though I can see why their title causes confusion. The question here is if there is a way to get the name of the original reference from ref
.