3

I have a method with a couple of overloads as different object types are expected (list vs array and 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? 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

Absinthe
  • 3,258
  • 6
  • 31
  • 70

1 Answers1

0

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());
S.Richmond
  • 11,412
  • 6
  • 39
  • 57
  • Thanks for that. Used verbatim I get a compile error of "'GameObject' does not contain a definition for 'ObjectLoop'". Used on it's own I get "The type 'UnityEngine.GameObject' cannot be used as type parameter 'T' in the generic type or method 'J_ObjectPool.ObjectLoop". When you say I should look at what I want to do can you clarify what's missing from my question? Cheers. – Absinthe Jun 18 '16 at 19:11