Skip to content

Flyweight pattern & Scriptable Objects

Jiufen edited this page Apr 1, 2021 · 1 revision

Flyweight pattern

This pattern focuses on separting the dynamic data from the static data in order to avoid reusing this last type of data in RAM over an over.

For example, you have an enemy, specifically an orc. The orc has a currentLife, a maxLife and an attackSpeed. The currentLife is a dynamic atrribute because it changes trough time. However, the maxLife and the attackSpeed are STATIC attributes because they don't change in the entire gameplay.

In the case of unity, we are going to store that static data on Scriptable Objects.

Why Scriptable Objects you may ask? Well there are 3 solutions static data separation problem.

  1. Const attributes

    This attributes will save memory compared to a simple attribute. Nonetheless, they are hard coded and not "easy" to change. Also they can't be referenced by other GameObjects.

  2. Static attributes

    This attributes are better than the const attributes. They save memory but they also can be referenced by GO and also can be changed in the unity inspector. Nonetheless they are hard to deal on the change of scenes.

  3. Scriptable Objects

    The best solution to save memory with static attributes is the Scriptable Objects. They are stored in the project and not in the scene so they will not have problems with the change of scenes. Scriptable Objects should only be used to stored data

Example of Scriptable Object:

Clone this wiki locally