Delete/Remove Instantiated objects

Hi, I’m new to unity. I instantiated my objects

Instantiate(obstacle, new Vector3(transform.localPosition.x + 5.0f, y, 0),Quaternion.identity);

the object is created 5 points right side of my camera and this process is continuous. I want those game objects to be deleted/removed when any object is -5 from the camera… Hope you understand what I’m trying to say…

Well you should keep track of the instantiated obstacle. Maybe do something like

GameObject newObstacle = Instantiate(obstacle, new Vector3(transform.localPosition.x + 5.0f, y, 0),Quaternion.identity);

or

GameObject newObstacle = Instantiate(obstacle, new Vector3(transform.localPosition.x + 5.0f, y, 0),Quaternion.identity);
// using a generic list of obstacle objects
spawnedObstacles.Add(newObstacle);

// later in code, when its destroy time, you have selected an obstacle to be destroyed
spawnedObstacles.Remove(obstacleToDestroy);
Destroy(obstacleToDestroy);

And that way you will be able to refer to it later (maybe using a list of all instantiated obstacle objects) and remember like at the end in that example, when you are finished with it use:

Destroy(newObstacle);

to destroy the object.

That way you keep track of it, and delete (destroy) when your done with it. That may be a confusing way to explain, but read up on those methods, and keep track somehow of obstacles, perhaps with a list, or individually if you don’t have too many to handle at a given time.

And also here is stuff to read, this whole topic explains a great way to handle things:

http://forum.unity3d.com/threads/132624-Unsure-of-how-to-add-and-remove-gameobjects-from-list-as-they-spawn-die

Thanks for the reply…
Will that apply if I have huge number of clones? How would I do in case of number of clones?
What I’m trying to do is 1. Create clones on +5 x axis and remove/destroy them when they are on -5 x axis and they are number of clones created on certain time…

is “spawnedObstacles” a class in unity?

“spawnedObstacles” is the variable name for a list object. If you are destroying and creating obstacles frequently you should use object pooling. Instantiate as many of you need at startup and add them to a list of free objects. When you need a new object, grab one from the list. When you are done with it, add it back to the free list.

Creating and destroying objects constantly at runtime will trigger garbage collection which will stutter your framerate occasionally. There is lots of info and ready-made assets for object pooling if you search for it.

myproblem was there last object of list should be destroyed??how solve??