Detect variables.... help

Hi community, I hope that there is someone can resolve this problem… I wanna make a console, anld I’ve thought to do an easy gui console thta include a box with input log and a textbox for inputs.
Now I want to modify variables by the console, an example:

I input on the textbox the string: health 100
So I want to modify that var “health” and set it to 100…
How can I detect that var by a string?

You dont need to detect the variable by name, you dont even need to name the commands in your console with the name of the variable in script.

You just need a switch case loop in the click event of the submit buton or the enter event for the text box in OnGUI function where you are going to treat each command like this

switch(cmd)
{
	case "health":
		HandleHealth(value);
		break;
	case "bullets":
		HandleBullets(value);
		break;
        ...
}

Ofc you must parse the content of the text box to do that.

I’ve thought about that but if I have to modify more than 1000 vars I can’t write a switch for all the vars… Can you advise me some other ways?

Something like this maybe c# - How do you get a variable's name as it was physically typed in its declaration? - Stack Overflow

Btw, 1000 variables seems a lot. Do you really need to be able to twaek all of them in console?

I did something like this recently for my boss event scripting. scarpelius is right, just use reflection.

Since I’m in a good mood and the forums don’t usually get good questions like this, I wrote you a quick demo on how to do it.

using System;
using System.Reflection;
using UnityEngine;

public class DataClass
{
    private float _health = 500;
}

public class Myfieldinfo : MonoBehaviour
{
    private FieldInfo _fieldInfo;
    private DataClass _data;

    void Start()
    {
        _data = new DataClass();

        // Get the type and FieldInfo.
        var MyType = typeof(DataClass);
        // You might want BindingFlags.Public as well if dealing with public properties.
        // Just feed in the field name from the console instead of hard coding it.
        _fieldInfo = MyType.GetField("_health", BindingFlags.Instance | BindingFlags.NonPublic);
        
        // Getting a value
        // You'll probably want to do a null check or a validation check here
        var getValue = _fieldInfo.GetValue(_data);

        // Setting the value
        _fieldInfo.SetValue(_data, 1000);
    }
}

I haven’t tested it in unity, should work though. If you have any questions give us a PM.

Thanks for the help!! It’s own what I needed :slight_smile: Is there any way to set a value to a var in that way but in other scripts???

Just get a reference to the script using GetComponent() or GameObject.Find(type) and use that instead of the DataClass.

Thanks :slight_smile: