- Home /
GameObject as a constraint for generic class
Hello! In C# I made class KnownObject, which is not derived from GameObject. Also I have a method looks like this:
public static List<GameObject> FilterBy(List<string> names, List<GameObject> objects)
{
List<GameObject> filteredObjects = new List<GameObject>();
foreach (GameObject @object in objects)
{
foreach (string name in names)
{
if (@object.name.Contains(name))
{
filteredObjects.Add(@object);
}
}
}
return filteredObjects;
}
I want to use this filter like a generic for a KnownObject. How can I do this? Defining method like:
public static List<T> FilterBy(List<string> names, List<T> objects) where T : KnownObject, GameObject {/* and so on */}
causes an error.
Answer by BastianUrbach · Sep 08, 2019 at 02:54 PM
What exactly are you trying to do? Giving two constraints for the same type parameter means that both must be fulfilled, which is not possible if both are classes. I assume the goal is to write the method just once but make it work with either GameObject or KnownObject? That's not really an easy task because you don't have control over the GameObject class (meaning you can't make it implement the interface you need). One way around this is to let the caller provide you with the methods you need:
public delegate string NameGetter<T>(T obj);
public static List<T> FilterBy<T>(List<string> names, List<T> objects, NameGetter<T> getName) {
List<T> filteredObjects = new List<T>();
foreach (T @object in objects)
{
foreach (string name in names)
{
if (getName(@object).Contains(name))
{
filteredObjects.Add(@object);
}
}
}
return filteredObjects;
}
The method could then be used like this:
FilterBy(names, objects, o => o.name);
You can then optionally provide overloads that take care of this automatically without having to rewrite the entire method for each type:
public static List<GameObject> FilterBy(List<string> names, List<GameObject> objects) {
return FilterBy(names, objects, o => o.name);
}
public static List<KnownObject> FilterBy(List<string> names, List<KnownObject> objects) {
return FilterBy(names, objects, o => o.name);
}
@coeusueoc Thank you very much! That's exactly what I need, great solution!
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Count returning 0 when called outside object~ 1 Answer
Multiple Cars not working 1 Answer
Disabling A Script on a GameObject From a Different Script 2 Answers
gameObject are not referenced 2 Answers