strangleIOC使用笔记
从asset store将strangeIOC下载下来后,运行其中的example,myfirstproject和signalsproject都没有问题,而运行第三个例子mutiplecontext时,就出现了空引用调用的问题,ShipView在Init()中添加ClickDetector时,获取ClickDetector的实例,其中的dispatcher为null;后来通过对比,改为从Resources中动态加载,让其成为ShipView的子对象,并在startcommand()中加载ShipView,具体代码如下:
1.StartGameCommand.cs

public class StartGameCommand : Command{[Inject]public IGameTimer timer{get;set;}[Inject(ContextKeys.CONTEXT_VIEW)]public GameObject contextView { get; set; }public override void Execute(){timer.Start();GameObject go = new GameObject();go.name = "ShipView";go.AddComponent<ShipView>();go.transform.parent = contextView.transform;go = new GameObject();go.name = "EnemyView";go.AddComponent<EnemyView>();go.transform.parent = contextView.transform;}}
2.ShipView.cs
GameObject latestGO;internal void init(){latestGO = Instantiate(Resources.Load("ship")) as GameObject;GameObject go = latestGO;go.name = "ship";go.transform.parent = gameObject.transform;go.AddComponent<ClickDetector>();ClickDetector clicker = go.GetComponent<ClickDetector>() as ClickDetector;clicker.dispatcher.AddListener(ClickDetector.CLICK, onClick);}
3.Resources文件夹:


ship要去掉上面的shipView.cs脚本,这个由StartGameCommand这个方法运行时加载;
究其错误原因,应该是ClickDetector.cs脚本不应该挂在shipView.cs的同级对象上面,应挂在其子对象上面,这样才能取到dispatcher;
修改之后运行:


浙公网安备 33010602011771号