美文网首页Unity技术分享征服Unity3dunity3D技术分享
Zenject-动态实例化预制体 prefab上的多个脚本怎样自

Zenject-动态实例化预制体 prefab上的多个脚本怎样自

作者: 杰罗xr | 来源:发表于2018-08-08 16:02 被阅读15次

如果一个预制体上的脚本使用了zenject 中的 [Inject] 给变量自动绑定赋值 那么当它使用unity自带函数Instantiate(prefab) 实例化出预制体后 脚本中使用[Inject] 的变量是不会自动绑定赋值的

那么如何让新实例化的预制体上的脚本自动赋值绑定呢

1.使用工厂

  1. 创建工厂
其中 ChildIcon 就是已经在预制体上的脚本组件 如果本预制体还有别的脚本 用这一个 其他的脚本就全部自动绑定赋值了

using UnityEngine;
using Zenject;

public class ChildIcon : MonoBehaviour {


    public class Factory : PlaceholderFactory<ChildIcon>
    {
    }
}

  1. 注册绑定
更多资料多看GitHub  https://github.com/svermeulen/Zenject#game-object-bind-methods

using Zenject;

public class SteamInstall : MonoInstaller<SteamInstall>
{
    public GameObject childPrefab;
    public override void InstallBindings()
    {
        Container.BindFactory<ChildIcon, ChildIcon.Factory>().FromComponentInNewPrefab(childPrefab);
    }
}
  1. 使用工厂生成预制体

using UnityEngine;
using UnityEngine.UI;
using Zenject;

public class ScrollLayout : MonoBehaviour {

    private ChildIcon.Factory _childFactory;

    [Inject]
    private void Init(ChildIcon.Factory childFactory)
    {
        _childFactory = childFactory;
    }

    
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            Transform ct = _childFactory.Create().transform;
            ct.SetParent(transform);
            ct.localScale = Vector3.one;
            ct.localPosition = Vector3.one;
        }
    }
}

2.

相关文章

网友评论

    本文标题:Zenject-动态实例化预制体 prefab上的多个脚本怎样自

    本文链接:https://www.haomeiwen.com/subject/kpkxbftx.html