Restrict access to components on same object

I’ve caught myself several times now defining Properties/Methods as protected when they actually should be public. I made this mistake be cause I wanted to achieve the following: Define Properties/Methods to which only other Components on the same Object have access.

A use case for example would be: I have an enemy with an EnemyController-Component and multiple EnemyState-Components, where the Controller should be able to acceess the State’s properties (e.g. there could be a Patrol-State and the Controller should be able to set patrol-waypoints) but no other gameObjects should be able to do so.

But is there a way (probably not via access modifiers, but some other) do achieve what I described?

I know of course, that (staying in my controller and patrol state example from above)

  1. there would be other ways to go, for example keeping the patrol-waypoints in the controller and make them publicly gettable, so the patrol-state could access them without “owning” them
  2. I (or the developer who uses my objects) would still have to ensure that only “authorized” components of the same object alter the patrol-state.

But by restricting access to components of the same object I prevent some possible mistakes (altering an enemy state from “outside”, which should in my example never happen), which is imho always good.

So is there a reasonable way to achieve this access restriction? Or would it be, for some reason I don’t see at the moment, useless anyway?

Thanks for any input! I hope, this is not an irrelevent/to generic question.

There’s no “component visibility” in unity, so no, you can’t prevent the GetComponent commands family from getting whatever component is attached to a gameobject.

Of course, unless you create your own MyGetComponent command which explicitly filter out those components (return null) and eventually call the original GetComponent command, like this:

public static T MyGetComponent <T> ( this GameObject go )
    where T : Component
	if (typeof (T) == typeof (ComponentWhichMustNotBeAccessed))
		return null;
		return go.GetComponent<T>();

You can use the internal keyword and keep the related components in the same assembly. Calling GetComponent<SomeClassInthatAssembly>(); from outside of that assembly will then yield a compiler error because SomeClassInthatAssembly is not reachable.