I have a 2 classes, class A and B that belong to Object Z.
A inherits Monobehavior
B inherits A
I want to GetComponent() without getting B.
The reason I have this design is that class A has variables that I need 2 versions of and used differently under class B, and B also uses functions like A.
At a certain point I need to get variables from class A. The function GetComponent() returns B first and while GetComponents() and cycling through them works, I find it encumbering.
Is there a better way?
There’s no other way as a derived class is also a “baseclass” instance. There’s no difference whatsoever as seen from the baseclass type.
You can create extension methods like this:
using UnityEngine;
using System.Linq;
public static class GOExtensions
{
public static T[] GetComponentsExact<T>(this GameObject aObj)
{
return aObj.GetComponents<T>().Where(a=>a.GetType() == typeof(T)).ToArray();
}
public static T GetComponentExact<T>(this GameObject aObj)
{
return aObj.GetComponents<T>().Where(a=>a.GetType() == typeof(T)).FirstOrDefault();
}
public static T[] GetComponentsExact<T>(this Component aObj)
{
return aObj.GetComponents<T>().Where(a=>a.GetType() == typeof(T)).ToArray();
}
public static T GetComponentExact<T>(this Component aObj)
{
return aObj.GetComponents<T>().Where(a=>a.GetType() == typeof(T)).FirstOrDefault();
}
}