Unity Zenject的一些小Tips(学习备忘)
1、原生的Instantiate游戏对象不会注入其定义的[Inject]属性,需要使用Container.InstantiatePrefab来实例化,才能受容器管控。
2、类似的在SceneManager.LoadScene时,如果Scene没有放置Zenject的SceneContext也无法呗容器管控,其下的对象所定义的[Inject]属性也无法注入。
3、继承MonoBehavior的单例和普通Csharp单例可以分别如下定义
Container.Bind<GameManager>().FromNewComponentOnNewGameObject().AsSingle(); //自动放置新对象中
Container.Bind<FruitManager>().AsSingle();
4、一些比较贴近Spring的使用
4.1、正常的[Inject]、IInitializable、 IDisposable接口
4.1、MonoBehavior脚本的全局单例
Container.Bind<GameManager>().FromNewComponentOnNewGameObject().AsSingle(); //自动放置新对象中
4.2、ScriptObject数据作为全局配置参数
Container.Bind<BackGroundColorConfigSO>().FromInstance(backGroundColorConfigSO);
Container.Bind<GameManager>().FromNewComponentOnNewGameObject().AsSingle().WithArguments(backGroundColorConfigSO).NonLazy();
4.3、Prefab预制体作为全局配置参数
Container.Bind<GameObject>().WithId("PlayerPrefab").FromInstance(playerPrefab);
Container.Bind<PlayerAttribute>().FromInstance(playerAttribute);
Container.Bind<RespawnPlayerManager>().FromNewComponentOnNewGameObject().AsSingle().WithArguments(playerPrefab, playerAttribute).NonLazy();
2025/10/27
4.4、发现了还有一个ScriptObjectInstaller为可视化配置量身打造
using NativeSerializableDictionary; using UnityEngine; using Zenject; public enum BackGroundColor { Blue, Brown, Gray, Green, Pink, Purple, Yellow, None } [CreateAssetMenu(fileName = "BackGroundColorConfig", menuName = "Installers/BackGroundColorConfig")] public class BackGroundColorConfig : ScriptableObjectInstaller<BackGroundColorConfig> { [SerializeField] public SerializableDictionary<BackGroundColor, Texture> backGroundColorMaterial; public override void InstallBindings() { Container.BindInstance(backGroundColorMaterial); } }
如果是纯只读配置使用4.4 ,如果是可修改 需更新维护的使用4.2

浙公网安备 33010602011771号