- Home /
c# How do I search by virtual Type variable in parent classes? (inheritance)
Hi guys, I want a way to identify if a class is a type of Enemy by searching the classes it derived, from for example : I have a class named Ship and a class named Astroid both are derived from Enemy, and I want to test if a Ship is a kind of enemy. I can use a virtual Type variable that is later overridden by the subclasses, that is a way to define types to make them easily accessable from outside, but i have no way of searching them yet.
this is my Entity class from wich i want to derive all other classes for example:
using UnityEngine;
public class Entity : MonoBehaviour {
public virtual string GetType () { return "Entity"; }
}
How do I find out if this is a type of Entity in a way that is efficient and usable for searching any class hirarchie ?:
using UnityEngine;
public class Something : Entity{
public virtual string GetType () { return "Something"; }
}
I tried using a virtual list and adding a type to it in each subclass, but virtual doesn't support lists, so I tried doing it with a string but i realised i don't know how to make the compiler calculate the string so that it wouldn't have to be generated every time I create an object in the start method.
nothing i realized my problem is somwhere else thanks
also what's the point of
public virtual string GetType () { return "Something"; }
every object has a GetType method already you could just do GetType().Name and it will give you the name of the class
Answer by TreyH · Mar 07, 2018 at 11:45 AM
The is keyword might be what you want? You also need the right syntax when passing types around.
public void CheckIfEnemy<T>()
{
return (T is Enemy);
}
You'd use this with:
bool shipIsEnemy = CheckIfEnemy<Ship>();
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Attach a non Monobehavior class to a GameObject 1 Answer
FPS weapons class structure 1 Answer