I know how to check a type of a field directly. But how could I implement something like this
private bool checkJumpObstacle(Type type)
{
foreach (GameObject3D go in GameItems)
{
if (go is type) // won't accept 'type'
{
return true;
}
}
return false;
}
For type, I'd like to pass Car
, House
or Human
as a parameter (those are all classes).
But this kind of code doesn't work.
EDIT: It's actually even easier using Type.IsInstanceOfType
if you can't make it a generic method:
private bool CheckJumpObstacle(Type type)
{
return GameItems.Any(x =>type.IsInstanceOfType(x));
}
It sounds like you probably want Type.IsAssignableFrom
if (go != null && type.IsAssignableFrom(go.GetType());
Note that this is assuming you want inherited types to match.
Also, if at all possible, use generics instead. Aside from anything else, that would make the method really simple:
private bool CheckJumpObstacle<T>()
{
return GameItems.OfType<T>().Any();
}
Even without that, you can still use LINQ to make it easier:
private bool CheckJumpObstacle(Type type)
{
return GameItems.Any(x => x != null && type.IsAssignableFrom(x.GetType()));
}
Obviously if you don't expect any null values, you can get rid of the nullity check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With