简体   繁体   中英

Correctly reset Scene and keep score in Unity

So I am making a game in Unity in order to learn how to code, and I have kind of hit a wall again. The game is a "dodge the falling objects game", and the way I am creating the objects is as follows:

public class Salt : MonoBehaviour {
    public float delay;
    public GameObject salt;

    // Use this for initialization
    void Start () {
        InvokeRepeating("Spawn", delay, delay);
    }
    // Update is called once per frame
    void Spawn () {
        Instantiate(salt, new Vector3(Random.Range(-2.5f, 2.5f), 10, 0), Quaternion.identity);
    }
}

This part of the code seems to be working fine. The problem occurs when the salt (falling objects) make contact with the player. The game resets like it should, however the salt that was on the screen already is still there and I can't figure out how to delete all of the clones that have already been made. Basically I can't figure out how to clear the objects that have already been created when the player loses.

The way I reset the game after collision:

public class TapToStart : MonoBehaviour {

    public Text highScore;
    public Button startButton;
    public ScoreManager sMan;

    // Use this for initialization
    void Start () {
        Init();
    }

    public void Init() {
        Time.timeScale = 0;
        sMan.SetScore(0);
        highScore.text = "High Score: " + Mathf.Round(sMan.GetHighScore()).ToString();
        startButton.gameObject.SetActive(true);
    }



    public void Pressed() {
        startButton.gameObject.SetActive(false);
        Time.timeScale = 1;
    }
}

I thought maybe making a SaltManager object would work, and then just have the Instantiated salt objects be children of it would work so that I could just delete the SaltManager after and all the children would disappear as well, however I can't figure out how to do that and it doesn't seem too efficient anyways. Any help would be greatly appreciated! Thanks! -Brandon

I would recommend that you reset the game by reloading the scene so like that you get it exactly how it was at the beginning. You can load your scene like that :

SceneManager.LoadScene("SceneName");

Or with the scene index :

SceneManager.LoadScene(sceneIndex); 

I can see that you're keeping a highscore and its probably why you didn't do it that way. You should save your high score with PlayerPrefs like this :

PlayerPrefs.SetInt("High Score", 10);

Then you can easily get it back with :

PlayerPrefs.GetInt("High Score");

This actually saves your score so that even if they quit the game and come back you can still retrieve it. More info on PlayerPrefs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM