【问题标题】:C# / Unity3d - pass object type as parameterC# / Unity3d - 将对象类型作为参数传递
【发布时间】:2016-06-18 09:53:47
【问题描述】:

我有一个带有几个重载的方法,因为需要不同的对象类型(列表 vs 数组和 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);
    }
}

有没有办法将这些压缩成一个方法,也许是通过传递列表或数组以及 GameObject 或 ParticleSystem 的对象类型?我猜它与泛型有关,但我无法完全理解它,所以欢迎对傻瓜进行解释:)

谢谢

【问题讨论】:

    标签: c# generics unity3d parameter-passing overloading


    【解决方案1】:

    您在那里似乎有一个有点奇怪的用例。你可能想看看你在那里尝试做什么。也就是说,这是一个应该可以工作的通用方法扩展:

    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);
            }
        }
    }
    

    用法:

        var go = new GameObject();
        go.ObjectLoop<ParticleSystem>(15, new List<ParticleSystem>(), new ParticleSystem());
    

    【讨论】:

    • 谢谢。逐字使用我得到“'GameObject'不包含'ObjectLoop'的定义”的编译错误。单独使用我得到“类型'UnityEngine.GameObject'不能用作泛型类型或方法'J_ObjectPool.ObjectLoop中的类型参数'T'”。当你说我应该看看我想做什么时,你能澄清我的问题中缺少什么吗?干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多