- Home /
my object keeps cloning is self i want it to clone once
hello there i am making a video game that require a obstacle generator similar to the one in flappy birds when the character goes though the trigger located in the center of the obstacles it is suppose to spawn another obstacle a few units up one at a time but it spawns a whole bunch in the air which slows down my computer can you guys help me make it spawn one at a time thx here is my script
pragma strict var max : float = 5; var min : float = 0; var obstacle : GameObject; var regenerate : boolean = false; var far : float = 0; var yes : boolean = true;
function Start () {
}
function Update () {
var x = Random.Range ( min, max);
var y = far + transform.position.y;
if(regenerate){
Instantiate( obstacle, Vector3(x,y,0),Quaternion.identity); regenerate = (false);
}
}
function OnTriggerEnter2D (other: Collider2D) { { regenerate = (true);}
}
Answer by akauper · Apr 13, 2014 at 08:10 PM
13yearoldceo... please use the code formatter button (the 010101 button up there) when submitting code. Your code is very hard to read as is.
Why are you instantiating the object within Update at all? If you only want ONE object to be instantiated per OnTriggerEnter2D, just put the code for the instantiation within that function. No need to bother with the regenerate boolean etc.
If for some reason that doesn't work for you, then you will need to track (within an array or list) the colliders which have entered your trigger. You will then need to check each entering collider against your list of colliders to make sure it does not already exist within the list.
Answer by sumeetkhobare · Apr 13, 2014 at 07:42 PM
I don't know why this happens, but i am currently making an endless runner too, and the same thing happened to me. The collider somehow produced multiple detections.
So i put a limit on the number of obstacles the scene can have at a time,including the ones not visible to the camera. Like:
if(regenerate && numberOfObstacles < obstacleLimit){
Instantiate( obstacle, Vector3(x,y,0),Quaternion.identity); regenerate = (false);
numberOfObstacles ++;
}
PS: you could either maintain the list of obstacles in an array and get the array count for the numberOfObstacles variable or you could go with this.but this has an overload of maintaining synchronization and also you have decrease it everytime you destroy an obstacle once it passes thru your scene.
Your answer
Follow this Question
Related Questions
Updating a variable on a script in an instanced object 1 Answer
Instantiate object 1 Answer
Prefab instantiated wrong scale on mobile 0 Answers
autolink to prefab? 0 Answers