strangleIOC使用笔记

从asset store将strangeIOC下载下来后,运行其中的example,myfirstproject和signalsproject都没有问题,而运行第三个例子mutiplecontext时,就出现了空引用调用的问题,ShipView在Init()中添加ClickDetector时,获取ClickDetector的实例,其中的dispatcher为null;后来通过对比,改为从Resources中动态加载,让其成为ShipView的子对象,并在startcommand()中加载ShipView,具体代码如下:
1.StartGameCommand.cs
  1. public class StartGameCommand : Command
  2. {
  3. [Inject]
  4. public IGameTimer timer{get;set;}
  5. [Inject(ContextKeys.CONTEXT_VIEW)]
  6. public GameObject contextView { get; set; }
  7. public override void Execute()
  8. {
  9. timer.Start();
  10. GameObject go = new GameObject();
  11. go.name = "ShipView";
  12. go.AddComponent<ShipView>();
  13. go.transform.parent = contextView.transform;
  14. go = new GameObject();
  15. go.name = "EnemyView";
  16. go.AddComponent<EnemyView>();
  17. go.transform.parent = contextView.transform;
  18. }
  19. }
2.ShipView.cs
  1. GameObject latestGO;
  2. internal void init()
  3. {
  4. latestGO = Instantiate(Resources.Load("ship")) as GameObject;
  5. GameObject go = latestGO;
  6. go.name = "ship";
  7. go.transform.parent = gameObject.transform;
  8. go.AddComponent<ClickDetector>();
  9. ClickDetector clicker = go.GetComponent<ClickDetector>() as ClickDetector;
  10. clicker.dispatcher.AddListener(ClickDetector.CLICK, onClick);
  11. }
3.Resources文件夹:
 
 ship要去掉上面的shipView.cs脚本,这个由StartGameCommand这个方法运行时加载;

究其错误原因,应该是ClickDetector.cs脚本不应该挂在shipView.cs的同级对象上面,应挂在其子对象上面,这样才能取到dispatcher;
修改之后运行:
 

 




posted @ 2017-06-29 14:20  ycbx  阅读(478)  评论(1)    收藏  举报