- Home /
spawn every frame, and i want it to spawn only once.
Hello. so, im trying to make a game where you kill an enemy and you get 1 point.
i have a cube (spawner like in minecraft), and this cube spawns an enemy every 3 secounds
(that methot i fount is easyer)
and i want to spawn a new cube/Spawner when you reach 10 points, then when you reach 20 points, then at 50 points and so on...
but i have a problem...
i run the instanciate thing in "void Update"
and when i reach 10 points it will start to spawn a cube every frame and every cube spawns an enemy every 3 secounds and in 3 secounds i'll have like 10000 enemyes
at first i was laughting at what i did, it was funny and every thing, but im stuck with this problem fro 2 days and it's not funny anymore im noob at scripting, just trying to do some game so i will learn while creating something...
here is my code
using UnityEngine;
using System.Collections;
public class Score : MonoBehaviour {
public float count = 0.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (count == 10) {
print ("lol");
GameObject spawnerInstance = Instantiate (Resources.Load ("Cube (1)")) as GameObject;
}
}
void OnGUI () {
GUI.Label (new Rect (48, 10, 100, 30),"Kills = " + count);
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "bullet") {
//Destroy(collision.gameObject);
//count += 1;
}
}
}
can anyone help me please? also, im very noob jo if you just keep it simple with the explanation, i'll be very happy :D Thanks :D
Answer by Rixterz · Apr 29, 2016 at 02:25 PM
You're checking if count has changed... but you never change it.
Change GameObject spawnerInstance = Instantiate (Resources.Load ("Cube (1)")) as GameObject;
to GameObject spawnerInstance = Instantiate (Resources.Load ("Cube (1)")) as GameObject; count ++;
That will increase the count, so it increases by 1 every time Instantiate is run. Also, you should change your declaration of count to:
int count = 0;
Because count can never be something like 2.7
Hope this helps
Thank you a lot :D it worked
so for me to understand when i reach 10, it spawns the cube then adds +1 to my score so it won't have to spawn another cube right?
Oh actually you need to change if (count == 10) {
to if(count < 10){
That means it will keep spawning cubes until 10 have spawned, and then it will stop
So the code inside update would be
if (count < 10) {
print ("lol");
GameObject spawnerInstance = Instantiate (Resources.Load ("Cube (1)")) as GameObject;
//spawn one cube
count++ ; //tell the game you've spawned another cube
}
//optional
else
{
//10 cubes have spawned, so do this code every frame afterwards
}