简体   繁体   中英

Unity c# convert string to param name

i need to convert a string to a param name to take his value, but i don't need to use the dictionary or ref , something like this

bool boolean;

void Start()
{
    boolean = false;
    Debug.Log("After = " + boolean);
    changeBool("boolean");
    Debug.Log("BeFore = " + boolean); // It will be true
}

void changeBool(string variableName)
{
    
}

Please, help me

Thanks in advance

As vernou already said, you can use reflection

void changeBool(string variableName)
{
    // Check for field existance, you can also log it
    var fieldInfo = GetType().GetField(variableName);
    if (fieldInfo == null) return;

    // Check if variable is a bool type and get the current value
    var oldValue = fieldInfo.GetValue(this);
    if (oldValue is not bool oldBoolean) return;
    
    fieldInfo.SetValue(this, !oldBoolean);
}

But be careful if the variable name comes from a dangerous source, it can become a vulnerability in your code
Someone can enter a deliberately false variable name
I recommend redesigning your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM