Instantiate creates too many objects

Hi, I need some help.

I want my game to instantiate a heart every 1000th score (1000, 2000, 3000 etc.). I want it to instantiate only one heart. However, it generates multiple. Can someone help me with a fix?

My code (attached) is inside the update function.

Thanks!
Rosh

        if(score !=0 && score%1000==0)
        {
            Instantiate(heart, spawnPoint, Quaternion.identity);

        }

Here hopefully clearer

Update is called each frame. So while your score is a multiple of 1000, it will instantiate a heart each frame.

Do the instantiation when you increase the score.

Your root problem is that your FPS is higher than the frequency when your score is changing. So you have multiple frames where this condition results true.

  • need another boolean class member
  • set it to false by default
  • put another if inside of this, where you check for it
    – If it is false, do the instantiation and turn the boolean to true.
  • Put an else into this score % 1000 == 0 if, where you are assign false to the boolean

or check at the place where you increase the score.

Heyyy! This worked upto a certain extent. Now one heart instantiates at 1000, but somehow doesn’t work for the rest of the calculation. Am i doing something wrong here?

void Update()
    {
        if (score % 1000 == 0 && heartSpawn==false)
        {
            heartSpawn = true;
            InstantiateHeart();
        }
    }

    void InstantiateHeart()
    {

        if (score != 0 && score % 1000 == 0 && heartSpawn==true)
        {

            Instantiate(heart, spawnPoint, Quaternion.identity);

        }
        else
        {
            heartSpawn = false;
        }
    }

You have done everything on the way I haven’t described.

    void Update()
    {
        if (score != 0 && score % 1000 == 0)
        {
            if (heartSpawned == false)
            {
                Instantiate(heart, spawnPoint, Quaternion.identity);
                heartSpawned = true;
            }
        }
        else heartSpawned = false;
    }

Ahh… Thank you very much. I am very new to C#, only started learning about a month ago.

It worked, Cheers!