- Home /
Generic Method help
Hello all , so I am trying to make a game and I need this piece of code:
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
this code is repeated more than one time , so I thought of putting it into a function (AddItem) However, in some cases , i need to use the obj variable and some others not so I need to sometimes return obj and function is as Gameobject and some other times I need is as void as it doesn't return anything. I recall learning something called templates in Advance Programming course in C++ After some search I found that It is referenced as Generic functions in C# / Unity
so far I got this :
public T fillList<T>(T param)
{
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
// return obj;
}
now my problem is that return obj is giving me an error , i am very unfamiliar with the syntax and way of writing generic functions , how can I remove the param and return the obj when it is called as Gameobject?
Can anyone please help? Thanks for all in advance!
Could you present one example for each case of use?
Anyway you definitely don't need a generic method for something like this. You could always return the object but choose not to use it or add a parameter to your method to return null. Or create 2 functions, or an overload (but parameters gotta be different for each). Can't tell you which of all is optimum for your occasion with that info but not a generic one.
Cheers.
Answer by TreyH · Dec 21, 2017 at 03:08 PM
In C#, you can call any method as though it were of type void.
public GameObject AddItem()
{
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj)
return obj;
}
You don't have to get the object returned by this, but you can if you want! Either of these will work:
// As a void
this.AddItem();
// As a GameObject
GameObject newItem = this.AddItem();
'this' is redundant. But this is indeed the most correct answer.
It's sort of a habit, I've never liked seeing a naked function without class name for static or this for instance calls. :-(
It is redundant indeed, but when posting small chunks it is nice to indicate class scope.
Your answer
