- Home /
Spawn issue - Duplication of Object
I'm making a shooter game based on Space Invader and similiars.. Everything run great except the spawn of the Asteroids. The game consists of controlling a ship that has to avoid asteroids in the space to earning points. If it collides with an asteroid its life decreases. Now... the asteroids spawn bad because the function Instantiate() makes duplicates of the main Rigidbody, infact if there are 3 asteroids in the scene it makes spawn another 3 and then 6 etc... I hope you understand my question ! For anything the code is here : Thanks for helping !
using UnityEngine;
using System.Collections;
public class Ast : MonoBehaviour {
float timer =0;
int pos_x= 0;
float velAst = 300f;
public Rigidbody player ;
void Awake ()
{
timer = Time.time +1.1f;
}
// Use this for initialization
void Start () {
//player= player1.GetComponent<Player>();
}
// Update is called once per frame
void Update () {
pos_x = Random.Range(-100,100);
//Funzione per lo spawn a tempo degli asteroidi.
if (timer < Time.time)
{
Instantiate(player, new Vector3(pos_x,68,480), transform.rotation) ;
timer = Time.time + 1.1f;
rigidbody.name = "Asteroid";
}
transform.position = new Vector3 (transform.position.x,transform.position.y, transform.position.z -velAst *Time.deltaTime);
transform.Rotate (0,0,50*Time.deltaTime);
//Distruggiamo il meteorite quando oltrepassa il giocatore
if(transform.position.z < -170)
{
Destroy(player.gameObject);
GameObject.Find("Main Camera").GetComponent<Score>().punteggio();
}
}
//Definiamo le collisioni
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == "Giocatore")
{
Destroy(player.gameObject);
GameObject.Find("Main Camera").GetComponent<Score>().vita();
}
}
}
There is good tutorial, where similar game is created. http://unity3d.com/learn/tutorials/projects/space-shooter
Answer by mediumal · Aug 11, 2014 at 05:34 PM
Since you are spawning an asteroid in every asteroid's Update() method, the more asteroids you have the more asteroids will spawn. And since each asteroid can spawn multiple other asteroids until it dies, there is geometric growth! Your asteroids are breeding.
All you need to do is make sure each asteroid can only spawn one other asteroid. A sort of one child policy, if you will.
Try changing this:
Instantiate(player, new Vector3(pos_x,68,480), transform.rotation) ;
timer = Time.time + 1.1f;
to this:
Instantiate(player, new Vector3(pos_x,68,480), transform.rotation) ;
timer = float.MaxValue;
Alternatively, have a single persistent object in charge of spawning asteroids, instead of the asteroids themselves.
Your answer
Follow this Question
Related Questions
Unity Engine issue... 1 Answer
Spawn Script Issue 0 Answers
Problem with spawning script 1 Answer
Huge performance hit when spawning prefab with AI 1 Answer
Spawn object 1 Answer