I am trying to understand the flyweight pattern better by trying to optimize memory usage by spawning 10000 copies of an enemy GameObject that I have which has an Animator component, SpriteRenderer component, and BoxCollider2D component.
I've identified that the intrinsic states would be the sprite and the animator controllers so I reference these in a ScriptableObject for every one of my GameObjects to use for their Animator and SpriteRenderer components.
using UnityEngine; [CreateAssetMenu(fileName = "NewEnemyFlyweightData", menuName = "ScriptableObjects/EnemyFlyweightData")] public class EnemyFlyweightData : ScriptableObject { public Sprite DefaultSprite; public RuntimeAnimatorController AnimatorController; } I use this spawner in order to test spawn 10000 of these GameObjects.
using System.Collections.Generic; using Unity.VisualScripting; using UnityEngine; public class EnemySpawner : MonoBehaviour { [SerializeField] private Enemy _prefabToSpawn; [SerializeField] private EnemyFlyweightData _enemyFlyweightData; private Stack<Enemy> _objectPool; private const int StartingAmount = 10000; private SpawnPoint _spawnPoint; private void Awake() { _spawnPoint = FindObjectOfType<SpawnPoint>(); _objectPool = new Stack<Enemy>(); for (int i = 0; i < StartingAmount; i++) { Enemy enemy = Instantiate(_prefabToSpawn); enemy.AddComponent<Animator>().runtimeAnimatorController = _enemyFlyweightData.AnimatorController; enemy.AddComponent<SpriteRenderer>().sprite = _enemyFlyweightData.DefaultSprite; _objectPool.Push(enemy); } } private void Start() { while (_objectPool.Count > 0) { SpawnEnemy(); } } private void SpawnEnemy() { if (_objectPool.Count > 0) { GameObject go = _objectPool.Pop().gameObject; go.SetActive(true); _spawnPoint.SpawnGameObject(go); } } } However, it seems to use lots of memory and it doesn't seem to make a difference when compared to just putting everything in one prefab and instantiating that way. In fact, it says it consumes even more memory when trying flyweight.
Memory usage when instantiating 10000 GameObjects with my flyweight attempt according to profiler:
Memory usage when instantiating 10000 GameObjects without flyweight with everything on prefab according to profiler:
What am I doing wrong here and how should I be referencing my intrinsic states (animations, sprites) in this case so that I can conserve memory more noticeably?

