P
P
Pragma Games2021-11-29 16:42:53
C++ / C#
Pragma Games, 2021-11-29 16:42:53

How to learn from what objects the given object was inherited?

Hello. For the sake of interest, I'm trying to do something similar to the component system in unity. At the moment, I can get an object that was added earlier by its type, but what if the requested class is the base class for some object that is stored in a dictionary? For example, the dictionary stores "MovementComponent,PistolComponent,RifleComponent" and I request via GetCustomComponent"WeaponComponent" which is the base for "PistolComponent,RifleComponent"

PS It is clear that you can get the entire list of values ​​from the dictionary and loop through is to check the possibility of casting the object. But perhaps there is a more elegant way? Since in the Unity code wrapper they pass to the engine the type of the object they are looking for and an empty int reference to return the component.

private Dictionary<Type, MonoBehaviour> _componentContainer;

public void AddCustomComponent<T>(MonoBehaviour component) where T : MonoBehaviour
{
     _componentContainer.Add(typeof(T), component);
}

public void RemoveCustomComponent<T>() where T : MonoBehaviour
{
     _componentContainer.Remove(typeof(T));
}

public T GetCustomComponent<T>() where T : MonoBehaviour
{
     return _componentContainer[typeof(T)] as T;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2021-11-29
@firedragon

https://docs.microsoft.com/ru-ru/dotnet/api/system...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question