问题
Unity (C#): How do I call a List from a different Scene? I get nullReferenceException bc in the current scene, it has no variables set to it. But in the previous Scene it had the correct values and variables that I wanted. (note: the 2 scenes are different but I want to use the score as a shared value between Scenes).
Otherwise, do you have an alternative to retrieving the "frameTexts[9].text" position?
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;
}
}
回答1:
I think your request depend on what you wanna do in your project. But i can recommend some few solutions:
- Singleton (unitygeek - gist)
- Save your scores in external file
- PlayerPref
If you wanna keep the scores entire the whole game, i think singleton will be nice !!
回答2:
Use DontDestroyOnLoad in the script for the object that contains the variables you want to retain from one scene to another.
回答3:
You can use DontDestroyOnLoad(transform.gameObject);
so that the gameobject will be active in your next scene or use PlayerPrefs
to save the data and load in the next scene. Both shall work!
来源:https://stackoverflow.com/questions/44320987/unity-c-how-do-i-call-a-listint-from-a-different-scene