C# Conception - Hide inherited members and functions

Hey everyone,

I have a C# conception question. I have a class that inherit from MonoBehaviour but when you get the object I don’t want that the other classes access MonoBehaviour properties.

I don’t want to expose the features of the inherited MonoBehaviour class but I want to be able to use them (Update, Start, GetComponent, etc.) inside my inherited class but not from outside.

Is it possible ?

Thanks a lot.

Have your class implement an interface with the stuff you want to expose, then access instances of your class through that interface only.

i think that’s not his point, because he could still implement Start - it wouldn’t make it impossible.

and personally i cannot think of a way that does exactly what you are looking for. (doesn’t mean much if i have no clue :p)

a little workaround could be if you have

ClassA : Monobehaviour
{
  protected virtual void Start() { }
}
ClassB :ClassA
{
  sealed protected override void Start() { }
}
ClassC :ClassB
{
  void Start()
  {
  //do stuff
  /* This would acutally cause a compiler warning - NOT an error though - and code written here would still be executed */
  }
}

sorry i couldn’t help more

Yes, it wouldn’t make it impossible, and as you point out, it can’t be made impossible. But at least you can guide the user of your class to use only the methods intended to use.

Well, one general way to gain access to the functionality of class X without exposing its interface is to create a class that has an X (as a private field) rather than one that is an X (via inheritance). You can then call any functions you want on your private field, but outside code can’t, because it’s private.

However, I don’t think that’s what you actually want to do here. You mentioned wanting “access” to Start and Update, but those aren’t functions that you access in a MonoBehavior, they’re functions you implement so that the Unity engine can call them at appropriate times. So you actually do want some of the outside world (specifically, the Unity engine) to be able to see that your class is a MonoBehavior and treat it like one. I’m guessing you also want to attach your class to a game object as a component (otherwise, I’m not sure why you’d need GetComponent–except to call on other objects, which you can do without being a MonoBehavior).

Which means any solution that does exactly what you asked for is probably going to be useless to you.

You might be able to make use of blizzy’s suggestion to implement an interface, and pass around a handle typed as that interface rather than as you class. That will stop anyone from accidentally accessing members that aren’t in that interface.

Otherwise, you probably need to rethink what precisely you’re trying to accomplish.

1 Like