After reading and trying many different examples, I am still stuck with this fairly simple problem on getting a score from one level to the next in Unity.
I have a C# script that handles my game logic for a level:
First, I set my level variables:
public class GameLogic : MonoBehaviour {
public GUIText countText;
public GUIText targetCity;
public GUIText gameOverText;
public GUIText endScoreText;
public GUIText timerText;
public Texture2D bgImage;
private int count;
public GameObject cityPrefab;
List<MyCity> mycities;
public float finalScore; // I Want this value to be available when my next scene loads
private float startTime;
After this, my level code executes fine, until the GameOver condition is met (time is up). Then, this code executes:
public void GameOver ()
{
gameOverText.text = "time is up!";
endScoreText.text = "You have found " + count.ToString() + " cities. Good wrok!";
Destroy (GameObject.FindWithTag("EmptyCity"));
Destroy (GameObject.FindWithTag("City"));
Destroy (GameObject.FindWithTag("TargetCity"));
finalScore = count; // SO AT THIS STAGE, MY FINAL SCORE IS SET AND READY TO BE PASSED TO THE NEXT SCENE. QUESTION IS HOW?
StartCoroutine(Wait());
}
IEnumerator Wait() {
yield return new WaitForSeconds(7);
Application.LoadLevel (3);
}
So, I end my level with an updated value in public float 'finalScore'. So far so good. Now my problem starts: Level 3 loads and all gameobjects from level 2 are destroyed. In my game, level 3 is a simple Unity scene where I congratulate the player on his performance. I want to have access to that public float finalScore from my previous scene (level2).
I know I have to use Dontdestroyonload somewhere. But I don't know how. How and where do I create a GameObject that has the public float 'finalScore' in it? How do I call that GameObject in my new level so that I can do something like this in my new level:
public GUIText ContratsOnScore;
void SetContratsText() {
CongratsOnScore = "Congratulations, you scored" + (finalScoreFloatValue from Previous level).ToString();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…