I’m currently working on a game where foes follow the player and fade themself if they reach a trigger on the map. After the fade I want to restore them with their original state (position, rotation, life, material, scripts, …).
My first way to do that was to create some Reset() functions in all script that carry my foe and manually restore what I want but since my foe have a lot of informations, it was really heavy to do that and possibly it will get heavier if I add more code to my foes.
My Second way was to save the gameobject using simply a new one by coding this in my script “GameObject go = this.gameobject;”. Then later in my script, il simply use Instanciate with my “go” and Destroy the current GameObject. But Unity saved changes that happens during my foe chase like the material alpha or the fact that I add a new component to my gameobject.
So I managed to add some logic in my Start function to fix the changes but I am under the impression that it’s some dirty tinkering rather than clean code.
So if you have advices to how to this properly, I will be really thankful
Instantiate creates a clone of the object at it’s current state. So you could use Instantiate to create a clone as you start, and then immediately set that clone inactive.
Just be sure to not put the cloning script on the object itself, as that would make the clone create a clone which would create a clone which would create a clone which would create a clone which would create a clone which would create a clone which would create a clone…
What makes doubling the game object not very optimal?
Doubling the game object, does not mean you are using double the amount of memory, if the material and texture is the same for both objects, then the memory is shared internally, and you can instantiate as many copies as you want, without affecting the memory (Except for some integers and strings, which are a few bytes here and there, not much to be not optimal)
I suggest you keep the original object from the beginning disable, and then when you need, create a copy of it and active it, while the original object is still there inactive, so that you can create from it another copy, and another and another.
Another way is to make use of “Prefabs”, you may save the object as a prefab, read about unity3D prefabs.
Well Prefabs wont works I think because when I instanciate my gameobject, I use some random to add some stuff at my foe like a weapon. But When I restore it, I doesn’t want him to randomize again the weapon for example.
This just sounds like you’re making a mountain out of a molehill. I presume the only things you need to restore are things that were changed in the first place. If the point is to make the object like new, then all you need to do is save whatever values you might change in Start() and restore the normally used values with the backups. The most complicated aspect would probably be an object pool if you want to be efficient about preserving them.