当前位置: 移动技术网 > IT编程>开发语言>Java > Unity 获取所有实现接口的实例化对象

Unity 获取所有实现接口的实例化对象

2020年07月17日  | 移动技术网IT编程  | 我要评论

我有一个接口:

interface IMyInterface
{
    void IFunction_1();

    string IFunction_2(string str);

}

现在有两个类BehaviourScripts 和 BehaviourScripts1 都继承了该接口:

class BehaviourScripts : MonoBehaviour, IMyInterface
{
    
    public void IFunction_1()
    {
        print("我是BehaviourScripts,TODO....");
    }

    public string IFunction_2(string str)
    {
        return $"我是BehaviourScripts,你传入的内容是---> {str}";
    }
}


----------------------------------------------------------------------------


public class BehaviourScripts1 : MonoBehaviour, IMyInterface
{
    public void IFunction_1()
    {
        print("我是BehaviourScripts1,TODO....");
    }

    public string IFunction_2(string str)
    {
         return $"我是BehaviourScripts1,你传入的内容是---> {str}";
    }
}

如果场景中分别有100个挂载了BehaviourScripts 和 BehaviourScripts1 的物体,

查找所有由 IMyInterface 派生的实例化,使用FindObjectsOfType<T>()

 public static List<T> FindAllTypes<T> () 
	{
		List<T> interfaces = new List<T>();
		
		var types = UnityEngine.MonoBehaviour.FindObjectsOfType<MonoBehaviour>().OfType<T>();

		foreach (T t in types)
		{
			interfaces.Add(t);
		}

		return interfaces;
	}

获取所有接口实例并实现接口的方法:

public void GetTypeBtn()
    {

      List<IMyInterface> myInterfaces = ResourcesManager.FindAllTypes<IMyInterface>();

	  foreach (IMyInterface item in myInterfaces)
	  {
		  item.IFunction_1();
		  Debug.Log(item.IFunction_2("你是...."));
	  }
    }

结果:

想要源码的同学

链接:https://pan.baidu.com/s/17JlmZOETX186VfCJmrF0qA 
提取码:7w86

 

-----------------------------------------------------------------------------------------------------------------------------

另外,通过C#反射获取所有实现接口的类时

获取到的并不是场景中所有实例化的物体对象,而是实现接口的类型

我的代码是这样的:

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => type.IsAssignableFrom(p));

foreach (var item in types)
{
	Debug.Log(item);
}

输出结果为:

哪位大佬给指点一下,通过反射获取场景中所有接口派生的实例

本文地址:https://blog.csdn.net/u014661152/article/details/107382291

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网