2
\$\begingroup\$

Expanding upon a previous tutorial, I am adapting a follow script to support multiple variations of a Bezier spline. Each spline variation uses a custom interface called IBezierInterface, and the follow script accesses the method GetPointOnCurve() to determine the correct position. In theory, this all seems very simple. However, I appear to be running in to some trouble. While I intend to pursue the general issues a bit more, myself, I realise that I may be shooting myself in the foot with the generic implementation.

While I can find a lot of good examples demonstrating the correct use of generic types, I can not find anything that gives an example of a generic class that inherits from another class. For example, Microsoft documentation includes examples of inheritance as a restriction on the actual type, and an example of inheriting from a generic class; but there are no examples of a generic class that inherits from a standard class. Unity documentation has even less examples, but none pertaining to my query. I am not getting errors; but that is no guarantee against error. I can not conceive a good prototype model to test my theory, either, given the fact that I am fairly new to the concept of generic types.


Given that I am specifically needing my class to be a MonoBehaviour; can I make a custom generic class that inherits from MonoBehaviour, such as in my example?

public class SplineWalker<T> : MonoBehaviour where T : IBezierInterface
{
    // ...
}
\$\endgroup\$
3
\$\begingroup\$

As Theraot said: No, Unity does not support that.

But an alternative would be to use composition instead of inheritance. Instead of having a SplineWalker for IBezierInterface, create a SplineWalker with an IBezierInterface.

public class SplineWalker : MonoBehaviour
{
    public IBezierInterface spline;
}
\$\endgroup\$
1
\$\begingroup\$

The code you present is valid C#, yet as far as I know it is not supported by Unity (giving a "Generic MonoBehaviours are not supported" error warning on the console when trying to use AddComponent for it).

If you need to have multiple implementations of this class with different generic parameters, you may subclass again to make non-generic classes. You may also consider using a template solution (such as T4) to generate the code files.

\$\endgroup\$
  • \$\begingroup\$ I now realise the logical implications of a "generic MonoBehaviour" . Oddly, I am not getting any errors. That is a very good alternate, though. If no one offers a better resolution within a day, I will accept this answer. \$\endgroup\$ – Gnemlock Feb 21 '17 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.