-2

So i have my game scene and i want to have my score be displayed in game over scene and my high score. This is my score code:

public class Score : MonoBehaviour
{

    public Text scoreText;
    public float scoreAmount;
    public float pointIncreasedPerSecond;
    // Start is called before the first frame update
    void Start()
    {
        scoreAmount = 0f;
        pointIncreasedPerSecond = 1f;
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = (int)scoreAmount + "";
        scoreAmount +=pointIncreasedPerSecond * Time.deltaTime;
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115

1 Answers1

0

Unity has a DontDestroyOnLoad method that will keep any objects alive across scene loads. You can add a call to that in your Score script.

void Awake() {
    DontDestroyOnLoad(gameObject);
}

Note that the GameObject must be a "root" GameObject (meaning it doesn't have parents in the scene). Also, be careful to not keep anything extra that you don't want alive around with it (child GameObjects will be left intact). The linked documentation states:

If the target Object is a component or GameObject, Unity also preserves all of the Transform’s children. Object.DontDestroyOnLoad only works for root GameObjects or components on root GameObjects.

Foggzie
  • 9,691
  • 1
  • 31
  • 48
  • Its working but now my score is keep going up and i dont know how to display it now on the screen im beginner. – GameDevEG Sep 01 '22 at 09:32
  • @GameDevEG That's because it still has an `Update()`. You need to decide how to tell it its done counting and then make sure once it's told it's done, it stops adding. That's a different question with a different answer though. – Foggzie Sep 01 '22 at 15:39