1

I'm trying to do a kind of debug console in Unity to be able to change - for example - enable/disable boolean values at run-time.

There's a point where I have a value that I want to set in a certain variable but this value is stored as a string (input from the user) and I need to cast it to the type of that variable (stored in a Type variable) but I don't know if this is possible.

This is the part of my code where I have the problem:

private void SetValueInVariable(string variable, Type type, string toSet)
{
    //reflection - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
    Type container = typeof(StaticDataContainer);
    FieldInfo placeToSet = container.GetField(variable, BindingFlags.Static);
    placeToSet.SetValue(null, //here I need to convert "toSet"); 
}

I would like to know if this is possible and how can I do it.

6
  • 2
    Don't name your variable var Commented Jul 10, 2018 at 18:05
  • 2
    @maccettura ...or value, for that matter :-) Commented Jul 10, 2018 at 18:06
  • @dasblinkenlight missed that one! Commented Jul 10, 2018 at 18:06
  • Edited. Thank you Commented Jul 10, 2018 at 18:16
  • 1
    @StriplingWarrior Sorry, my mistake Commented Jul 10, 2018 at 18:32

1 Answer 1

1

TypeDescriptor provides a fairly robust way to convert a string to a specific type. Of course, this will only work for a handful of types that have fairly straightforward parsing.

private void SetValueInVariable(string variable, Type type, string toSet)
{
    //reflection - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
    Type container = typeof(StaticDataContainer);
    FieldInfo placeToSet = container.GetField(variable, BindingFlags.Static);
    var value = TypeDescriptor.GetConverter(type).ConvertFrom(toSet);
    placeToSet.SetValue(null, value); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

OH Thank you! I'm just trying to convert to standard types so I suppose It would work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.