[英]C# / Unity3d - pass object type as parameter
I have a method with a couple of overloads as different object types are expected (list vs array and GameObject vs ParticleSystem): 我有一个带有几个重载的方法,因为预期会有不同的对象类型(list vs array和GameObject vs ParticleSystem):
void ObjectLoop(int uBound, List<GameObject> list, GameObject item, bool projectile, int decalNo = 0, int typeNo = 0)
{
for (int x = 0; x < uBound; x++)
{
list.Add(Instantiate(item) as GameObject);
list[x].transform.SetParent(this.transform);
list[x].SetActive(false);
if (projectile)
{
projScript = list[x].GetComponent<J_Projectile>();
projScript.decalType = decalNo;
projScript.hitType = typeNo;
}
}
}
void ObjectLoop(int uBound, List<ParticleSystem> list, ParticleSystem item)
{
for (int x = 0; x < uBound; x++)
{
list.Add(Instantiate(item) as ParticleSystem);
list[x].transform.SetParent(this.transform);
list[x].gameObject.SetActive(false);
}
}
void ObjectLoop(int uBound, GameObject[] list, GameObject item)
{
for (int x = 0; x < uBound; x++)
{
list[x] = (Instantiate(fireHazard) as GameObject);
list[x].transform.SetParent(this.transform);
list[x].SetActive(false);
}
}
Is there any way to condense these into a single method, perhaps by passing the object types for list or array and GameObject or ParticleSystem? 有没有办法将这些方法压缩成一个方法,可能是通过传递列表或数组的对象类型以及GameObject或ParticleSystem? I'm guessing it has something to do with generics but I can't quite get my head around it so an explanation for dummies would be welcome :)
我猜它与仿制药有关,但我不能完全理解它,所以欢迎对假人的解释:)
Thanks 谢谢
You seem to have a somewhat strange usecase there. 你似乎有一个奇怪的用法。 You may want to look at exactly what you're trying to do there.
你可能想看看你到底想要做什么。 That said, here is a generic method extension that should work:
也就是说,这是一个应该工作的通用方法扩展:
public static class GameObjectExtensions {
public static void ObjectLoop<T>(this GameObject value, int uBound, IList<T> list, T item) where T : UnityEngine.Component {
for (int x = 0; x < uBound; x++) {
list.Add(GameObject.Instantiate(item) as T);
list[x].transform.SetParent(value.transform);
list[x].gameObject.SetActive(false);
}
}
}
Usage: 用法:
var go = new GameObject();
go.ObjectLoop<ParticleSystem>(15, new List<ParticleSystem>(), new ParticleSystem());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.