![](/img/trans.png)
[英]Unity C# how should I call the function and values from different script files?
[英]Unity (C#): How do I call a List<int> from a different Scene?
Unity(C#):如何从其他场景调用列表? 我在当前场景中得到nullReferenceException bc,它没有设置任何变量。 但是在上一个场景中,它具有我想要的正确值和变量。 (请注意:这两个场景是不同的,但我想将分数用作场景之间的共享值)。
否则,除了检索“ frameTexts [9] .text”位置,您还有其他选择吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreDisplay : MonoBehaviour
{
public Text[] rollTexts, frameTexts;
static string output;
public void FillRolls(List<int> rolls)
{
string scoreString = FormatRolls(rolls);
for (int i = 0; i < scoreString.Length; i++)
{
rollTexts[i].text = scoreString[i].ToString();
}
}
public void Fillframes(List<int> frames)
{
for (int i = 0; i < frames.Count; i++)
{
frameTexts[i].text = frames[i].ToString();
Debug.Log(frameTexts[i].text + " frames");
}
}
public static string FormatRolls(List<int> rolls)
{
// ScoreDisplay scoreDisplay = new ScoreDisplay();
output = "";
for (int i = 0; i < rolls.Count; i++)
{
int box = output.Length + 1; // Score box 1 to 21
if (rolls[i] == 0)
{ // Always enter 0 as -
output += "-";
}
else if ((box % 2 == 0 || box == 21) && rolls[i - 1] + rolls[i] == 10)
{ // SPARE anywhere
output += "/";
}
else if (box >= 19 && rolls[i] == 10)
{ // STRIKE in frame 10
output += "X";
}
else if (rolls[i] == 10)
{ // STRIKE in frame 1-9
output += "X ";
}
else
{
output += rolls[i].ToString(); // Normal 1-9 bowl
}
}
return output;
}
public string DisplayFinalScore()
{
string FinalScore = "Congrats on scoring: " + frameTexts[9].text;
return FinalScore;
}
}
在脚本中将DontDestroyOnLoad用于包含要从一个场景保留到另一个场景的变量的对象。
我认为您的要求取决于您想在项目中做什么。 但我可以推荐一些解决方案:
如果您想在整个游戏中保持得分,我认为单身人士会很好!
您可以使用DontDestroyOnLoad(transform.gameObject);
以便游戏对象在下一个场景中处于活动状态,或使用PlayerPrefs
保存数据并在下一个场景中加载。 两者都可以工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.