- Home /
Is there a way to make certain functions accessible by only certain classes?
I have an InputManager that has public functions that can be called from any script, but also functions that must only be called from certain scripts with "permission." The script that has permission is the InputReader, but other classes shouldn't have access to those particular functions.
Answer by Bunny83 · Oct 01, 2020 at 08:53 AM
Not really possible unless you compile those scripts to a seperate assembly and use the internal access modifier. Things defined internal are like public for the current assembly / module but are private from the outside. There are no "friend" declarations like in C++ as this generally leads to a maintenance hell since it's hard to tell who has access to what parts. That's most likely the main reason why they didn't include such a keyword in C# ;) See this SO question for some reasons.
C# has another feature called partial classes which can lead to similar issues when abused. Partial classes have been implemented mainly to seperate auto generated code (like from the visual studio form designer) and user code.
There are other ways to achieve some sort of contract between classes. One way is something like this:
public interface IInputHandler
{
void OnKeyDown(KeyCode aKey);
}
public interface IInputReader
{
void SetHandler(IInputHandler aHandler);
}
public class InputManager : MonoBehaviour
{
private InputHandler handler = new InputHandler();
private class InputHandler : IInputHandler
{
public void OnKeyDown(KeyCode aKey)
{
// handle
}
}
public void RegisterReader(IInputReader aReader)
{
aReader.SetHandler(handler);
}
}
public class InputReader : IInputReader
{
IInputHandler inputHandler;
public void SetHandler(IInputHandler aHandler)
{
inputHandler = aHandler;
}
void SomeMethod()
{
inputHandler.OnKeyDown(key);
}
}
In this case you can only get access to the "handler" if you are implementing the IInputReader interface. So only a certain type of classes are able to get access to the methods provided by the InputHandler class.
Keep in mind that access modifiers are by no means security measures. They are languages constructs to convey an idea and to restrict yourself from misusing this idea. With the help of reflection it's possible to circumvent all of those measures and there's no way to prevent that. After all code is just code and data is just data on the CPU level.