Search code examples
c#classunity-game-enginemethods

View methods of other class when accessing main class? C#


I would like to solve my problem in elegant way, rather than writing all methods of my other class into main component class (more than 100 methods)

So, in simplified version, I have unity component class:

public class MyAnimator : MonoBehaviour
{
    AnimatorHandler handler;
    public AnimatorHandler Handler => handler;
}

and the AnimatorHandler class like:

public class AnimatorHandler
{
    public void DoOperation1() { }
    public void DoOperation2() { }
    ... and a lot of more public operations
}

I would like to give user access to all DoOperation1() DoOperation2() methods of the handler class, just by accessing MyAnimator class. Like:

    void MyUpdate(MyAnimator animator)
    {
        animator.DoOperation1();
    }

rather than

    void MyUpdate( MyAnimator animator )
    {
        animator.Handler.DoOperation1();
    }

or by writing all AnimatorHandler methods into MyAnimator, so not like:

public void DoOperation1() => handler.DoOperation1();

In such case I would end up in extra .cs file with about 1000 lines of code and with need to update it each time I change something in the MyAnimator class.

Is there possible smart solution for such case?

Maybe possibility to return handler instead of MyAnimator instance when getting it's reference?

Thank you.


Solution

  • I finally ended up in interface + extensions approach.

    So I made interface which just returns reference to the AnimatorHandler and made static class with extensions methods for the interface.

    In addition, AnimatorHandler also implements the interface, so desired methods can be called from AnimatorHandler itself and MyAnimator as well.

    I just needed to create few internal variables/methods for the AnimatorHandler, to give more access for the extension methods calculations : unfortunately I can't put extension class inside partial class of AnimatorHandler to see private variables.