- Home /
making infinite road with prefabs
Hi, I want to create infinite path and I use one prefab to make road. When camera moving on the road, I have instantiate the prefab, but when camera pass the previous prefab I cannot destroy the previous road prefab. How can I destroy prefabs clone?
function Update () { transform.position.z += speed * Time.deltaTime; //Create prefab, when camera pass previous road if(transform.position.z - startPosition >=21){ startPosition = transform.position.z; Instantiate(tilePrefab, Vector3(0,0,positionZ), Quaternion.Euler(0,270,0)); positionZ +=20; tilePrefab.transform.position.z = positionZ; } }
Answer by robertbu · Dec 01, 2013 at 11:19 PM
One way to solve your problem is to have the game object destroy itself if it is no longer visible. Put the following script on the road prefab.
#pragma strict
function OnBecameInvisible () {
Destory(gameObject);
}
But there is some things to consider about your design. Rather than Destory game objects, why not create two game objects and just swap them? Instead of instantiate above, you can just move the last road so that it becomes the current one. Instantiating and Destroying are relatively expensive.
Another thing to consider is your frame of reference. Unity uses floats for position. As you get further away from the origin, they become less precise and can become an issue for calculation and alignment. It is not an issue for many games, but if you have an endless game where you move significant distances, a better way to run the game is to keep the vehicle/player at the origin and move the road instead.