我有两个脚本。我使用一个脚本来改变另一个脚本的bool变量。在我的第一个脚本中,我想要的是将字符串作为布尔变量(在第二个脚本中引用bool)。我该如何做到这一点?
我想要实现这一点,因为我正在将第一个脚本添加到多个gameObjects中,并且每个go都具有从第二个脚本激活/停用某些bool的功能。我想从我的检查器窗口为脚本1中的每个bool提供名称。
public Script2 script2;
public string nameOfBool;
void Start () {
script2.nameOfBool= true; //Is there a way to do this?
}
脚本2
public bool Bool_1;
public bool Bool_2;
public bool Bool_3;
按名称引用属性不是微不足道的,我建议您在启动时为每个属性创建lambdas:
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;
}
}
运行时:
UpdateBool2(true);
如果您想将它们与名称相关联,则将它们存储在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}
}
}
}
现在您可以根据字符串值调用它们:
string targetBool = "first";
BoolUpdaters[targetBool](true);
如果您想根据更新程序的名称(事先知道)生成更新程序列表,那么您可以使用一个简单的PowerShell脚本生成代码,从而节省一些输入:
param([string[]]$BoolNames)
$BoolNames.ForEach({
'{{"{0}", (newValue) => script2.{0} = newValue}}' -f $_
})
保存到.ps1
文件,启动PowerShell,执行命令pathtofile.ps1 -BoolNames Bool_1,Bool_2,Bool_3,...