簡體   English   中英

C#/ Unity3d - 將對象類型作為參數傳遞

[英]C# / Unity3d - pass object type as parameter

我有一個帶有幾個重載的方法,因為預期會有不同的對象類型(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);
    }
}

有沒有辦法將這些方法壓縮成一個方法,可能是通過傳遞列表或數組的對象類型以及GameObject或ParticleSystem? 我猜它與仿制葯有關,但我不能完全理解它,所以歡迎對假人的解釋:)

謝謝

你似乎有一個奇怪的用法。 你可能想看看你到底想要做什么。 也就是說,這是一個應該工作的通用方法擴展:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM