- Home /
Store a Copy then Destroy Scene Objects
Hi, is there a way to take a gameobject from the scene and store it into the list of a script? Then after that, destroy the scene gameobject without destroying the one in the list? Here is some code to illustrate my problem.
public List<GameObject> items; // A list of GameObjects
GameObject obj; // Let this be the GameObject from the scene
public void Example(){
items.Add(obj); // Store it in the list
Destroy(obj.gameObject); // Now destroy the object in the scene
}
The problem I'm having is that the object stored in the list is destroyed when I call the Destroy() object. Its like the scene gameobject and the object stored in the list are the same. Is there a way to make a separate copy of the scene gameobject, store it in my list, then destroy the scene gameobject without affecting the one in my list?
Answer by Paps O · Dec 27, 2014 at 07:00 PM
No it is not possible. Because when you add an object to a list (or any container) it store only the reference of the object (basically the same object). So when you modify one, you modify all the other one.
One thing you can do, is instead of destroying your object is to disable the gameobject
myGameObject.SetActive(false)
and when you need it again to re-enable it
myGameObject.SetActive(true)
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
What happens to GameObjects in a List when Destroy()'d elsewhere? 1 Answer
Add and destroy instantiated gameobject in linkedlist C# 1 Answer
Destroy and rebuild game objects from lists 1 Answer
Storing complex GameObject structure 1 Answer