![](/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.