Hey there,
currently I am working on a “space invaders” clone. I have just implemented a LevelSystem which allows the player to distribute points in stats to make the player/ship more powerful.
Whenever I make changes to the player they are also done in the actual prefab. To clarify the problem, let me describe it with more detail:
In instance my player has the property “Shots per second”, which is actually 5. The ship is having a level up and I decide to spend 5 points in it so it is having a value of 6. Now after ending the game, the prefab’c ShotsPerSecond value is also 6. But I actually expected that the prefab’s ShotsPerSecond value is staying 5 and is not touched by changes.
How can I avoid this? I do not want to store a reference of the prefab but I want a copy of it. I was already thinking of instantiating the prefab hidden in the main scene and then keep reference to this.
If this is not clear enough, I will add some code and screenshots.
Greetings
This is just a compilation of everything that I and others already stated in the comments, but I’m posting it as an answer so the question can be marked as solved.
The Problem
Since you are keeping a reference to the original prefab and not a copy, changes that you make to it in play mode will persist. Now you might be thinking:
“But changes made in play mode shouldn’t persist after leaving play mode”
Yes, but not entirely true. The more accurate way to say it is:
“Changes made in play mode to objects in the scene hierarchy, don’t persist after leaving play mode”
Since the object being changed was the original prefab (which is not in the scene), then changes would persist. In order to solve this you must change a copy of that prefab.
Solution
As far as I know there are only two ways to do it:
Drag and drop the prefab from your project folders to the Scene Hierarchy and keep a reference to that one, instead of the original. Then proceed as normal and change its properties as before.
OR
In your Start() function (or wherever it’s appropriate, really), call Instantiate(originalPrefabReference), save that in a variable and change that one.
In this case I would use the first option. Since you only really need one copy of that prefab for the entirety of your game.
The second option is better when you need to instantiate multiple copies of the same prefab during run time.