unity3d 扩展对象-第二次注入时出现NullReferenceException

vdgimpew  于 2023-01-05  发布在  其他
关注(0)|答案(2)|浏览(157)

我是Zenject(扩展项目)的新人。
我的开发环境:Win10、Unity2020、扩展对象9.2.0
我的问题是:

    • 在安装程序中绑定类**

第一个月

    • 在A类注入**
private AccountInfo accountInfo;             

[Inject]
private void Init(GameSetup _gameSetup, AccountInfo _accountInfo)
{
    this.gameSetup = _gameSetup; 
    this.accountInfo = _accountInfo;
}

accountInfo.address = "xxx'; // works fine
    • 然后将帐户信息注入到类B**
private AccountInfo accountInfo;      
        
[Inject]
private void Init(AccountInfo _accountInfo)
{
    this.accountInfo = _accountInfo;
}

accountInfo.address = "xxx'; //NullReferenceException: Object reference not set to an instance of an object
    • 为什么accountInfo更改为null?AsCached()不起作用?还是其他问题?**
    • 请帮帮我~~谢谢!**

下面是我的代码:

    • 安装程序**
  • "ClassA"注入GameSetup并创建示例,工作正常*

  • "ClassB"注入游戏设置,错误:空对象*

  • "ClassB"创建者,我正在尝试使用container. instantiate()来创建它*

  • --更新---游戏设置仍然为空对象
gj3fmq9x

gj3fmq9x1#

在两种情况下,注入将无法在代码中正常工作。
1.使用注入对象的代码在Init之前执行。例如,如果此代码放置在构造函数中。
1.你可以在运行时创建你的游戏对象/组件而不使用IInstantiator。当你使用Znject时,你应该总是使用IInstantiator来创建对象。要做到这一点,你应该将IInstantiator注入到对象中,这会创建另一个对象。IItstantiator在默认情况下总是绑定在容器中,所以你不必手动绑定它。例如:

public class Creator : MonoBehaviour {

    [SerializeField]
    private GameObject _somePrefab;

    private IInstantiator _instantiator;

    [Inject]
    public void Initialize(IInstantiator instantiator) {
        _instantiator = instantiator;
    }

    private void Start() {

        // example of creating components
        var gameObj = new GameObject(); // new empty gameobjects can be created without IInstantiator
        _instantiator.InstantiateComponent<YourComponentClass>(gameObj);

        // example of instantiating prefab
        var prefabInstance = _instantiator.InstantiatePrefab(_somePrefab);
    }

}
svmlkihl

svmlkihl2#

我不是Maven,但我认为传递IInstantiator或容器不是一个好的做法。如果你需要在运行时创建注入示例,那么你需要一个工厂。
1.-DI的最佳实践是只引用复合根“层”中的容器
请注意,工厂是该层的一部分,可以在那里引用容器(这对于在运行时创建对象是必需的)。
2.-直接示例化对象时,可以使用DiContainer或IInstantiator,DiContainer继承自IInstantiator。但是,请注意,注入DiContainer通常是不好的做法,因为几乎总是有更好的方法来设计代码,使您不需要直接引用DiContainer。
3.-同样,依赖项注入的最佳做法是仅引用“复合根层”中的DiContainer

相关问题