- Home /
A common way for counting instances of gameobjects that implement subclasses derived from a single base class
I am creating several gameobjects from prefabs. All of these gameobjects are assigned scripts which implement subclasses that all derive from a single base class.
I would like to be able to count how many types of certain gameobjects there are, as defined by which subclasses they have assigned to them. I want to be able to process all the gameobjects that derive from the base class in the same way.
Ideally would like to create a variable in the base class that is static in the subclasses, so I can process all the gameobjects in the same way, but have the variable different for each of the subclasses. However I can't seem to use abstract variables which are then later declared as static.
Anyone have any suggestions for this?
Answer by Nischo · Jul 09, 2015 at 09:40 AM
Something like this comes to my mind. But be careful with serialization and Dictionaries.
class BaseClass : MonoBehaviour
{
void Start()
{
}
protected static void Register(BaseClass aThis)
{
List<BaseClass> list;
if(sInstances.TryGetValue(aThis.GetType(), out list)
{
if(!list.Contains(aThis) list.Add(aThis);
}
else
{
list = new List<BaseClass>();
list.Add(aThis);
sInstances[aThis.GetType()] = list;
}
}
private static Dictionary<Type, List<BaseClass>> sInstances = new Dictionary<Type, List<BaseClass>>();
}
If your classes now derive from BaseClass
you just need to call Register(this)
in the scripts Awake()
method. In Instances
you now have, sorted by type, a collection of your scripts, using the gameObject
property on these scripts you can access the objects in your scene.
Your answer
![](https://koobas.hobune.stream/wayback/20220611230331im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Static Facing an Object 2 Answers
Strange increment counter 1 Answer
Why my capsule collider sometimes stucks in other colliders? 0 Answers
Should non-rendered (code only) GameObjects be marked as static 2 Answers
When is a static game object static? 1 Answer