0
\$\begingroup\$

I'm not sure this is possible or not but I need to create a variable and set its name to whatever the user wants. Is this doable in C#?

something like this is what I want:

public string UserInput;
void Start
{
    int "whatever UserInput is" = 0;
}
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Can you explain what you're trying to accomplish by giving the user control over your variable names? You can't do literally what you've asked, but I'm willing to bet there are ways to accomplish your actual goal - you just need to tell us what that is. \$\endgroup\$
    – DMGregory
    Mar 8, 2022 at 23:05
  • \$\begingroup\$ It is not possible to do that. But there are other structures that could resolve your problem, look into Dictionary learn.unity.com/tutorial/lists-and-dictionaries# \$\endgroup\$
    – Fabio S.
    Mar 9, 2022 at 3:20
  • \$\begingroup\$ @DMGregory The reason I'm willing to do this is because of JsonUtilities. As I have read, the variables' names in the c# file should match the ones in the JSON file. My JSON contains a few lists and users can add more to it so I would like to create a variable that has the same name as the user list's key \$\endgroup\$
    – Arian_ki
    Mar 9, 2022 at 9:21
  • \$\begingroup\$ So is your real question "How can I use JsonUtility to deserialize lists of named items?" If so, ask that specifically. Yesterday's Q&A seems to cover that use case — what behaviour do you need that would differ from this? \$\endgroup\$
    – DMGregory
    Mar 9, 2022 at 11:53
  • \$\begingroup\$ Thanks, everyone, I appreciate your answers and the links. The problem has been solved, I figured creating different JSON files instead of one file with several lists is much more efficient for what I want. Right now, I have a problem with reading a JSON file, and here's the link of my question for those who are interested: gamedev.stackexchange.com/questions/199781/… \$\endgroup\$
    – Arian_ki
    Mar 9, 2022 at 12:07

1 Answer 1

2
\$\begingroup\$

You do not need this type of functionality. User can set string to any value and you can use the string value to access the variable for example.

Dictionary<string,int> dict = new Dictionary< string,int>();
dict.add(userInput, 0);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .