Make Something Happen Just Once In Update()

Hi, my problem here is that for my game I’m making it so that if the player kills a certain amount of enemies, a helicopter appears and passes by. The problem is that when the player reaches the number (15), a bunch of helicopters appear until I kill 1 more, how can I make it so that it only spawns once?

KillCount Code:

using UnityEngine;
using System.Collections;

public class KillCount : MonoBehaviour {

	public int kills = 0;
	public GameObject heli;

	public void Add () 
	{
		kills += 1;
	}
	
	void Update () 
	{
		if (kills == 15)
		{
			Instantiate(heli, transform.position, transform.rotation);
		}
	}
}

The simplest solution would be to move your if statement into the Add() function, and completely remove the polling in Update(). This should ensure it will only trigger at the exact point the count hits 15 (assuming the count can’t go down):

using UnityEngine;
using System.Collections;

public class KillCount : MonoBehaviour
{
    public int kills = 0;
    public GameObject heli;

    public void Add()
    {
        kills += 1;

        if (kills == 15)
        {
            Instantiate(heli, transform.position, transform.rotation);
        }
    }
}

private bool heliSpawned;

void Update(){
  if(kills == 15){
    if(!heliSpawned){
      Instantiate(heli, transform.position, transform.rotation);
      heliSpawned = true;
    }
  }
}

I don’t know if it’s the correct way, but here’s how I would do it:

using UnityEngine;
using System.Collections;
 
public class KillCount : MonoBehaviour {
 
    public int kills = 0;
    public GameObject heli;
    public boolean heliActivated = false;
 
    public void Add () 
    {
        kills += 1;
    }

    void HeliCall()
    {
      Instantiate(heli, transform.position, transform.rotation);
      heliActivated = true;
    }

    void Update () 
    {
        if (kills == 15 && heliActivated == false)
        {
            HeliCall();
        }
    }
}

Hope it helps