Added bonus RNG damage does not reset on enter/exit

I decided to add RNG boost to my towers on instantiation. It was a very simple approach where i just added “prefab.attack = prefab.attack + Random.Range(0,5);” It works but not as intended. The prefab.attack rating keeps growing as I instantiate new towers and it does not reset when i enter/exit playmode. What am i forgetting or this approach is fundamentally bad? Please let me know if you want to see the code. I try to keep it short.

Hi Slav,

You are on the right track but there is a big problem with Unity that you probably do not know yet. When you change a prefab, the changes persist. For this reason, do not override the values of a prefab at runtime.

First of all, edit the prefab while the game is not running. Set the attack variable back to your initial value.

Then save the attack data for the tower(s) in your tower spawner. A new variable helps. Initialise that variable with the initial value of your prefab. Use that value for the spawned towers. If you implemented more ideas, a new class for the tower configuration at runtime might be a solution. However, if you have just one tower, a simple variable in the tower spawner is sufficient.

Did this help? :slight_smile:


See also:

Hi Nina, thank you for your swift reply!
“When you change a prefab, the changes persist.” This is indeed news to me. Does this mean that modifying a prefab (or its clone) is never a good option (except spawning and destroying it)? What is a good practice for creating a “unit”, which can be modified during and after initialization?

If you instantiate a prefab at runtime, you could safely modify that instantiated game object because it is independent from the prefab.

If you prefer to work with a ‘blueprint’, you could instantiate the prefab in Start(), cache that instantiated game object in an instance variable, disable the instantiated game object and modify the variables of it. Instead of the prefab, you could pass on this game object to the Instantiate method.

If you apply your solution to this ‘blueprint’ game object, the rest should probably work as expected.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms