我希望更改以下代码,以便可以在此函数中传递类型 T 或 Component 的参数,以便可以在类型参数中使用它。这将用于代替以下代码中的 ButtonManager
,这可能吗?我可以使用泛型
来完成此任务吗?我希望这样做,这样我就可以为各种组件类型重用此方法,而不必为每个组件类型创建一个方法。
private GameObject[] FindInActiveObjectsByType()
{
List<GameObject> validTransforms = new List<GameObject>();
ButtonManager[] objs = Resources.FindObjectsOfTypeAll<ButtonManager>() as ButtonManager[];
for (int i = 0; i < objs.Length; i++)
{
if (objs[i].hideFlags == HideFlags.None)
{
objs[i].gameObject.GetComponent<ButtonManager>().ConfigureInteractives();
validTransforms.Add(objs[i].gameObject);
}
}
return validTransforms.ToArray();
}
最佳答案
您已经在使用通用重载 Resources.FindObjectsOfTypeAll<T>()
它总是返回 T[]
为了使其余部分(例如 GetComponent
)正常工作,您只需确保 T
类型始终为 Component
所以你会这样做
public GameObject[] YourMethod<T>() where T : Component
{
List<GameObject> validTransforms = new List<GameObject>();
T[] objs = Resources.FindObjectsOfTypeAll<T>();
for (int i = 0; i < objs.Length; i++)
{
if (objs[i].hideFlags == HideFlags.None)
{
//objs[i].gameObject.GetComponent<T>().ConfigureInteractives();
validTransforms.Add(objs[i].gameObject);
}
}
return validTransforms.ToArray();
}
请注意但是 ConfigureInteractives()
似乎与您的 ButtonManager
特别相关并会抛出异常,因为它不是 Component
的一部分.
所以,如果您需要这个来继承 ButtonManager
的其他内容然后只需交换 Component
与 ButtonManager
在
public void YourMethod<T>() where T : ButtonManager
How could I check the passed in Type
有多种方法。你可以例如使用检查确切的传递类型
if(typeof(T) == typeof(ButtonManager)) (objs[i].gameObject.GetComponent<T>() as ButtonManager).ConfigureInteractives();
但是你也可以简单地返回使用
if(typeof(T) == typeof(ButtonManager)) objs[i].gameObject.GetComponent<ButtonManager>().ConfigureInteractives();
或者你可以使用 typeof(T).IsSubclassOf(typeof(ButtonManager))
还可以匹配继承的类型。
关于c# - 在 Unity 中使用泛型作为变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56832338/