Limited what classes can and cannot alter a variable

So here is my set up, I am creating a stealth game in which part of the AI functions on timers. As an example, for chase, I have one public float called ChaseTimerSet where I can specify in the inspector how long I want the AI to be in this chase state while the player is not in their view, and another variable called float _chaseTimer that does the actual countdown. What I want however is for two things;

First is I only want ChaseTimerSet to be alterable outside of runtime, so nothing else outside of the script itself can change it.

Second, I want to make it so the only other script that can access and alter _chasetimer is a set of NPC states that takes in the NPC_Guard script containing everything as an argument to understand what it needs to do every frame.

I read one person suggesting that I create some private variables that just read the inspector visible ones on awake, but I want to see if there is a more elegant solution to this problem.

I thought of using Protected, but the state scripts do not derive from NPC_Guard.

“First is I only want ChaseTimerSet to be alterable outside of runtime, so nothing else outside of the script itself can change it.” If you make the variable private and add the [SerializeField] attribute before it will only be changeable from the script itself and in the editor. You can change it in runtime by changing it in the inspector in the editor but no other script will be able to change it at any time because it is private.


“Second, I want to make it so the only other script that can access and alter _chasetimer is a set of NPC states that takes in the NPC_Guard script containing everything as an argument to understand what it needs to do every frame.” In c++ you could use something called friend class here, where classes can be friends and therefore they can access each others private parts. However, in C# there is no such thing. I have never needed to do this myself but the answers here might be of help. encapsulation - What is the C# equivalent of friend? - Stack Overflow