转载至:https://blog.youkuaiyun.com/u014661152/article/details/107382291?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allsobaiduend~default-2-107382291.nonecase&utm_term=unity%20%E8%8E%B7%E5%8F%96%E6%89%80%E6%9C%89%E5%AE%9E%E7%8E%B0%E6%8E%A5%E5%8F%A3%E7%9A%84%E7%B1%BB&spm=1000.2123.3001.4430
我有一个接口:
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()
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);
}
输出结果为: