In Unity, how does Unity magically call all “Interfaces”?

前端 未结 2 1108
无人共我
无人共我 2020-12-05 17:46

Unity has an "interface":

IPointerDownHandler (doco)

You simply implement OnPointerDown ...

public class Whoa:MonoBehavio         


        
2条回答
  •  情书的邮戳
    2020-12-05 18:10

    You can use reflection to get all types in an assembly that implements a specific interface and then instantiate those types and call the methods on those instances through the interface.

    var types = this.GetType().Assembly.GetTypes()
                                       .Where(t=>t.GetInterfaces().Contains(typeof(IGetNews)));
    foreach (var type  in types)
    {
        var instance = (IGetNews) Activator.CreateInstance(type);
        instance.SomeNews("news");
    }
    

提交回复
热议问题