- Home /
How can I make this setter accessor only accept values that come from certain scripts?
So I've been trying to grasp encapsulation and I've simplified to the point its no where near as irritating as trying to do it on the project I'm currently working on so instead I made a test project where a button simply changes a variable. The problem is there's nothing to stop the value from coming from any where. If I had to describe it the situation is like a pipe that starts out very restrictive only to be accessible by everything which really just ends up being like why have the piping the first place? Here's the code I got with an example illustrating what will happen if some other script uses it.
public class GameManager : MonoBehaviour
{
//I'm sorta secure? ◔_◔
private static bool _ChangeMe = false;
public static void SetChangeMe(bool value)
{
//Lets just accept whatever I get! ◕ ◡ ◕
_ChangeMe = value;
}
// Update is called once per frame
void Update()
{
//I'm just watching. Don't mind me. ( ͡° ͜ʖ ͡°)
Debug.Log("ChangeMe is: " + _ChangeMe);
}
}
using UnityEngine;
public class ChangeVariable : MonoBehaviour
{
public void ChangeIt()
{
//I hope some code else where doesn't completely screw this up. ಠ_ಠ
GameManager.SetChangeMe(true);
}
}
using UnityEngine;
public class JoesPlan : MonoBehaviour
{
// Update is called once per frame
void Update()
{
//Don't question Joe's plan. ^_-
GameManager.SetChangeMe(false);
}
}
How would I prevent Joe's plan from messing up everything? I assume I would have to change something in the setter accessor but I have no clue how to determine where it got its value from.
Answer by toddisarockstar · Apr 01, 2019 at 04:11 AM
you cant really call it security because you are the only one writing the code changing the variables. there is no built in security from your self. normal practice would be if you don't want a particular script changing a variable you simply wouldn't put it in that script in the first place. anyways, the closest solution you are going to find is to require a second parameter in your function to include the name of the script it i's comming from.
public static bool MakeitTrue(bool b,string script){
if (script == "JoesScript") {
DevelopersAreWeird = b;
} else {
print ("you are not worthy");
}
}
public static bool DevelopersAreWeird;
void Start () {
MakeitTrue (true, this.GetType ());}
Could also do a caller/source reference in the wrapper function
public static bool doThing(bool b, ref object caller)
{
DevelopersAreWeird = false;
if (caller is SomeObjectType)
{
DevelopersAreWeird = b;
}
return DevelopersAreWeird;
}
Your answer
Follow this Question
Related Questions
Messaging system using C# 1 Answer
Getters/Setters with C# Array 1 Answer
What's the best way to hide classes when sharing C#? 2 Answers
HLAPI SyncVars property setter function 1 Answer
Modular Animation States or Encapsulating Animation States 0 Answers