cannot return private string variable through a public get function?
public class MapTile : MonoBehaviour { private string mapName;
public void SetMapName(string t_mapName){
mapName = t_mapName;
}
public string GetMapName(){
return mapName;
} }
Basically, i have a class like this. I had the string set somewhere else, and expected to be able to get it through the get function, but i couldn't.
However, when i changed the string from private to public it turned out working. Why is that? I just want to keep this string variable private. Please help!
I don't see a problem in this code, maybe it's somewhere else.
cannot return private string variable through a public get function
What exactly doesn't work here? Do you get a compile error? A runtime error? No error but an empty or null string? Does the game crash? Does your cat walk backwards up the wall?
Since this question is a general program$$anonymous$$g question and not really related to Unity i'll move it into the HelpRoom. Please improve your question by editing your question and adding more details.
Answer by melsy · Apr 18, 2018 at 02:15 AM
You already have mapName so why are you running another method to get it. That is kind of redundant.
string mapName = "";
public void SetMapName(string _name)
{
mapName = _name;
}
Debug.Log(mapName);
Because he wants to keep it private and still access it from other scripts.
Why down vote.. This accomplishes the goal and keeps the mapName private.
That's the exact same code that he posted in his question, except you didn't address why the get function isn't working.
I did not downvote and sean didn't downvote as well, but i think i understand why. First and foremost having the actual fields private and providing accessor methods is a fundamental part of OOP (Encapsulation). Though even we usually use properties in C# for that purpose it's totally fine to use normal methods. Properties are just syntactic sugar for such get and set methods.
The second issue with your answer is that you keep the mapName variable private so the second class that was mentioned can't access it and since you removed the accessor method it can't be accessed at all outside the class.