Hi all. So in Unity you can attach different collider components to objects - box collider, capsule collider, mesh collider, etc.
But say for instance you wanted to reference the collider on a number of objects all with different collider types, you can just say GetComponent() and it will automatically return a collider on that object regardless of what type of collider it is.
Is there a way to set this up for custom classes? For example, I have a number of different door locks - tumbler, combination, electronic - that I have on different objects. Is there a way for me to say GetComponent() and have it return any of those lock types?
Well I just had a thought that maybe it had to do with inheritance. All my door locks derive from the base class Lock(). Sure enough I just did GetComponent() and it worked like a charm for every lock type.
That was easy! I’ll leave this here in case anyone searches it in the future.
What you are described is known as inheritance in object-oriented programming. When you create a Component in Unity, it inherits from MonoBehaviour by default.
You would need to create a base class “Lock”. Other lock types, such as “ElectronicLock” can inherit from this type. If you add the ElectronicLock Component to a GameObject, this is the instance which will be returned when you call GetComponent on that GameObject.
Edit: well, looks like you figured it out on your own.
public class Lock : MonoBehaviour
{
public LockTypes _locktype;
public enum LockTypes
{
tumbler,
combination,
electronic
}
public LockTypes getCurrentType
{
get { return _locktype; }
private set { _locktype = value; }
}
}
So you should be able to do
GetComponent().getCurrentType