Sup*_*Man 2 c# arrays unity-game-engine
我正在开发Unity游戏,只是注意到有时会出现一个奇怪的错误.发生的事情是我正在实例化的字符串数组创建得太短,即使我写的日志消息确认表达式应该创建一个更大的数组.
这是相关的代码片段:
Debug.Log("hero.power = " + hero.power.ToString());
Debug.Log("allyPower = " + allyPower.ToString());
Debug.Log("opponent.power = " + opponent.power.ToString());
int max = Mathf.Max(hero.power + allyPower, opponent.power);
report.flips[hero.name] = new string[hero.power + allyPower];
report.flips[opponent.name] = new string[opponent.power];
Debug.Log("max = " + max.ToString());
Debug.Log("report.flips[hero.name].Length = " + report.flips[hero.name].Length.ToString());
Run Code Online (Sandbox Code Playgroud)
这在Unity中创建的输出:
这说明hero.power是3和allyPower是0但,而不是创建string[3]它会创建一个string[1].
有没有关于使用表达式来确定导致问题的数组的长度?我暂时改为:
int heroArrayLength = hero.power + allyPower;
report.flips[hero.name] = new string[heroArrayLength];
Run Code Online (Sandbox Code Playgroud)
它似乎有所帮助,虽然虫子之前是不稳定的,所以我不完全确定它是固定的.即使是这样,我仍然不清楚实际原因是什么.
有谁知道这里发生了什么?
如果hero.name是相同的话opponent.name,那么:
report.flips[hero.name] = new string[hero.power + allyPower];
report.flips[opponent.name] = new string[opponent.power];
Run Code Online (Sandbox Code Playgroud)
将两者设置相同的"翻转"(无论"翻转"是什么),第二次"赢".既然opponent.power是1,最终的数组将是长度1,这意味着report.flips[hero.name]将是长度1.