- Home /
Save a copy of a gameObject
I'm trying to create a simple save/reload system, where objects of many different types need to be saved. There are many objects with different scripts, and I need copies of those instances with all their variables in whatever state they had at the time of copying.
Setting a GameObject variable with a gameObject in the scene only makes a reference to that object, not a state copy. (i.e if it gets destroyed or altered, the variable is affected).
pseudocode to show my problem:
GameObject objectReference = find("a gameobject");
GameObject objectCopy = objectReference;
destroy (objectReference);
print(objectCopy); > console prints "null"
How can I store a copy of a gameObject? Am I going to have to write a custom class to store all the possible data in an instance of a gameObject? If I have to do this, would it be possible to use typecasting? This method would be quite a pain :(
Thanks!
PS: using C#
Answer by flamy · May 20, 2013 at 01:14 PM
Gameobject is reference type. once u destroy the object source, the copy of reference is also deleted.
hence the value in objectCopy becomes null when destroy is called.
something once destroyed cannot be recreated as the exact same. what you want to store? positions? scripts? or some other component?
Why not disable the object instead of destroying it. So that you can re-enable it later?
or you can serialize the object and save it to local and get that back later on to create similar object (have a look at Unity Serializer for that purpose)
How can I make a copy ins$$anonymous$$d of a reference? Any tips?
I want to store a copy of objects that can be moved by the player, and have states (stored in different scripts) that can also be changed by the player. I need to be able to move them, destroy them, and re-create them when the player decides to reload the level from when they saved. Simply disabling the object won't do as I still need the object so that the player can use it until they reload, or save again (and i'd overwrite the stored state).
Actually, disabling the object gives me a good idea. What if I create a clone and disable it immediately, and destroy the original object when the player "reloads" then enable the clone. Although, this doesn't allow me to save states in between games (i.e the player closing the game and then loading it back up) I guess I need to write a custom serializer to extend the Unity Serializer.
I'm going with using Unity Serializer with my own serialisation class for each custom monobehaviour I have that needs to be stored, and store it as a supported type in the Unity Serializer (a string). Thanks for the help :)
Your answer
Follow this Question
Related Questions
Save gameobject 1 Answer
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
The name "Destory" Does not exist in the current context 2 Answers
Moving object to specific location 1 Answer
Place gameobject on ROI 0 Answers