M
M
marsep2015-07-29 03:52:50
C++ / C#
marsep, 2015-07-29 03:52:50

How can you define multiple classes with the same parent within the same type?

Hello! There was a question about classes in Unity3d... It is necessary to implement such a system: there is a parent class that contains methods and variables, and there are child classes that inherit this class. Some child classes can override methods, etc., this is already clear. It is necessary that it is possible to group game objects that are similar in their type into one whole, i.e. the parent class forms the standard behavior of an object of this type, and the child ones represent an already defined object and supplement its behavior if necessary. There is a task, for example, when a player collides with such an object, it is correct to use its class. You can get a component by name, there is no problem with this, but the problem arises when you need to cache components, because in fact the classes can be different and only the parent is the same.
d783c088a40d4e3db892d2a5e8199831.png
Those. when colliding with an object or at startup, I need to cache the class components into an array, but I cannot set the desired type for the array, i.e. the class is unknown. I've tried using the object type instead of a direct type definition, but this causes errors if I try to access methods that are unknown to it, for example, the execute method will be unknown because the type object does not define this. This is understandable, but how can this be done as simply as possible? After all the task I think is actual not only in my example. I searched for a long time on the Internet, found clues within MethodInfo, but they also said that this affects performance a lot, and it seemed to me that this was too costly a solution, can I ask you for advice?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Makarov, 2015-07-29
@marsep

Um.....why can't it be cached into an "array" of type ParentClass?
For each cache object, all its methods will be known, and the implementation (or refinement of the implementation) of them will be taken over by descendants.
As far as I understand OOP, inheritance and polymorphism are invented for that ....

V
Vitaly Pukhov, 2015-07-29
@Neuroware

store in the type objects, and use it to look at what type it is .GetType().ToString() and cast to this type var A= (YatiPtIpa)object; then do whatever you want with it. But such a solution is not ideal, it scales badly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question