Search code examples
unity-game-engine2dinstantiation

How to instantiate only one object in unity


int winer;

void Start() {
    winer = PlayerPrefs.SetInt("win", 0);
}

void Update() {
    winer = PlayerPrefs.GetInt("win");
    if(spawnPoint1.transform.position.x <= 10) {
        PlayerPrefs.SetInt("win", 1);
        chunks.enabled = false;
        if(winer == 1) {
            Instantiate(win, winPoint.transform.position, transform.rotation);
        }
    } else {
        PlayerPrefs.SetInt("win", 0);
    }
}

How can I instantiate only one object for 2d sprite?

Thanks for your response


Solution

  • You can keep track of the status in a variable so that the instantiation occurs only once.

    bool instantiated; //is false by default
    int winer;
    
    void Start() {
        winer = PlayerPrefs.SetInt("win", 0);
    }
    
    void Update() {
        winer = PlayerPrefs.GetInt("win");
        if(spawnPoint1.transform.position.x <= 10) {
            PlayerPrefs.SetInt("win", 1);
            chunks.enabled = false;
            if(winer == 1 && !intstantiated) {
                Instantiate(win, winPoint.transform.position, transform.rotation);
                intstantiated = true;
            }
        } else {
            PlayerPrefs.SetInt("win", 0);
        }
    }