我有一个统一项目,想使用预定义的列表一个接一个地调用方法。
在这个测试场景中,我想执行 startTrialWithFixedValue1() 两次,startTrialWithFixedValue2() 两次,最后 startTrialWithRandomValue() 一次。每次用户进行输入时,我都想执行列表中的下一个方法。我的代码有两个主要问题:
(1) 每当我使用带有返回值的 if 语句时,变量 countTrial 就变得无法访问。调试日志始终显示为 0:1,并且始终执行第一种方法。
(2) 如果我排除了 return 语句,所有方法都会立即启动。
[编辑] 指定我的问题:如何按照给定列表的顺序执行方法。
脚本A:
public int countTrial;
public int maxTrials = 16;
public Spawner spawner;
List<int> trialMarkers = new List<int>() {1, 1, 2, 2, 3};
public void chooseNextTrial()
{
for (int countTrial = 0; countTrial < maxTrials; countTrial++)
{
Debug.Log(countTrial + ": " + trialMarkers[countTrial]);
if (trialMarkers[countTrial] == 1)
{
spawner.startTrialWithFixedValue1();
return;
}
if (trialMarkers[countTrial] == 2)
{
spawner.startTrialWithFixedValue2();
return;
}
else
{
spawner.startTrialWithRandomValue();
return;
}
}
脚本B:
public void handleUserInput()
{
if (Input.GetButtonDown("Fire3"))
{
deleteAllChildren();
chooseTrial.chooseNextTrial();
}
}
}
希望大家帮帮我!
[EDIT2] 根据程序员的建议:删除该函数中的 return 语句,然后再次运行它。复制并粘贴 Debug.Log(countTrial + ": " + trialMarkers[countTrial]); 结果总是:
5:3
5:3
5:3
...
您需要删除 For 循环并更手动地处理 Method 的执行
public int countTrial = 0;
public int maxTrials = 16;
public Spawner spawner;
List<int> trialMarkers = new List<int>() {1, 1, 2, 2, 3};
public void chooseNextTrial()
{
Debug.Log(countTrial + ": " + trialMarkers[countTrial]);
if (trialMarkers[countTrial] == 1)
{
spawner.startTrialWithFixedValue1();
}
if (trialMarkers[countTrial] == 2)
{
spawner.startTrialWithFixedValue2();
}
else
{
spawner.startTrialWithRandomValue();
}
}
然后在处理用户输入的第二个脚本(脚本 B)中
public void handleUserInput()
{
if (Input.GetButtonDown("Fire3"))
{
deleteAllChildren();
chooseTrial.chooseNextTrial();
chooseTrial.countTrial++;
}
}
结束行:您不应该使用 Fop 循环,因为您希望使用玩家输入操作启动序列并像这样处理它。还添加了这样的方法:
public void NextCounter()
{
if(countTrial<trialMarkers.Count)
countTrial++
}
在您的脚本 A 中,然后在脚本 B 中像这样调用它,以避免您的计数器超过列表计数。
chooseTrial.NextCounter();
代替在脚本 B 中使用 countTrial++
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句