- Home /
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);
}
}
}
Answer by alwayscodeangry · Jul 11, 2014 at 05:02 PM
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);
}
}
}
Oh, and you should probably make kills private to avoid other objects bypassing your Add() function.
Thanks, I tried all the answers and this is what suits me best. Apreciate it pal :)
Hello there! Ok, maybe I'm hella thick, but is Add() a custom method or a standard Unity thing? I can't find it anywhere in the scripting API, so I assume it's custom. But in that case, when exactly is it going to get called? Sorry if this is a weird question, and thanks in advance.
Add() is a custom thing, it's just a name. It can be named ANYTHING.
Answer by SirCrazyNugget · Jul 11, 2014 at 05:02 PM
private bool heliSpawned;
void Update(){
if(kills == 15){
if(!heliSpawned){
Instantiate(heli, transform.position, transform.rotation);
heliSpawned = true;
}
}
}
Answer by Tricephalus · Jul 11, 2014 at 05:29 PM
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
Your answer
Follow this Question
Related Questions
GameObject instantiates too many objects in update 2 Answers
Collision check on Placement 1 Answer
Prefabs Transforms LookAt 0 Answers
How should i add raycast to multiple game objects??? 0 Answers
Refrencing Instantiated Object 1 Answer