I am having two scripts. I am using one script to change the bool variable of another script. What I want in my first script is to have the string as the boolean variable (to reference the bool in second script). How do I achieve this?
I want to achieve this because I am adding the first script to multiple gameObjects and each of these GOs have functionality to activate/deactivate certain bool from second script. I would like to provide the names for each bool in Script 1 from my inspector window.
public Script2 script2;
public string nameOfBool;
void Start () {
script2.nameOfBool= true; //Is there a way to do this?
}
Script 2
public bool Bool_1;
public bool Bool_2;
public bool Bool_3;
Referencing a property by name is not trivial, I'd suggest you create lambdas for each at startup:
public class Script1
{
public Script2 script2;
public Action<bool> UpdateBool1;
public Action<bool> UpdateBool2;
public Action<bool> UpdateBool3;
void StartUp()
{
UpdateBool1 = (newValue) => script2.Bool_1 = newValue;
UpdateBool2 = (newValue) => script2.Bool_2 = newValue;
UpdateBool3 = (newValue) => script2.Bool_3 = newValue;
}
}
Then at runtime:
UpdateBool2(true);
If you want to associate each with a name, store them in a Dictionary<string, Action<bool>>:
public class Script1
{
public Script2 script2;
public Dictionary<string, Action<bool>> BoolUpdaters;
void StartUp()
{
BoolUpdaters = new Dictionary<string, Action<bool>>
{
{"first", (newValue) => script2.Bool_1 = newValue}
{"second", (newValue) => script2.Bool_2 = newValue}
{"third", (newValue) => script2.Bool_3 = newValue}
}
}
}
Now you can invoke them based on a string value:
string targetBool = "first";
BoolUpdaters[targetBool](true);
If you want to generate the list of updaters based on their names (known in advance), you might save yourself some typing by generating the code with a simple PowerShell script:
param([string[]]$BoolNames)
$BoolNames.ForEach({
'{{"{0}", (newValue) => script2.{0} = newValue}}' -f $_
})
Save to a .ps1 file, launch PowerShell, and run the command path\to\file.ps1 -BoolNames Bool_1,Bool_2,Bool_3,...