- Home /
Public variables vs {get{return variable;}}
So, for my Unity project I've been setting any variable in a script that needs to be accessed by another script as public. I don't need to edit these in the inspector but because they're public they show up in the inspector anyways. This was fine at the beginning, but as the project grew there were more and more and they started cluttering the inspector. My friend showed me how to add this to make the the variables that are only accessed for their information stay private and not clutter the inspector.
public int FunctionVariableReturn
{get{return variable;}}
But as I started going through my scripts I was wondering if it was really worth it. I have to add this for any variable I need to share, but only if it doesn't need to be changed by the other script.
P.S. I was also wondering what the difference would be between something set as private int var and just int var
P.S.S. I was also wondering if there was any place where people show others their code and they help make it better. I doubt my code is very optimized, but I've doing my best to look things up.
Thanks.
Answer by Bunny83 · Aug 27, 2012 at 08:29 PM
I guess HideInInspector would be enough in your case ;) Properties are nice and they can provide 2 read-only access to variables, but i use them only in some cases, mostly when i need to do more calculations there ;).
Btw, it's also possible to have private variables which can't be accessed by other classes, but are shown in the inspector and are serialized (saved) by using SerializeField
Is it possible to add more than one variable to the [HideInInspector] or do I have to add that line for every variable I want to hide?
No, this is an attribute which is attached to the element that follows it. Some prefer to write it in front of the variable, but most the time you will place it above for better readability.
Depending on the attribute type, some can only be "attached" to variable, some to functions and some to classes. Here are Unity's runtime attributes and those are the editor attributes which can only be used in editor classes.
$$anonymous$$eeo in $$anonymous$$d that there are also other attributes which comes with $$anonymous$$ono / .NET, but what a certain attribut does is not specified. It completely depends on the interpreting system which is in our case Unity or the Unity compiler. Attributes are just meta data attached to a certain element.
Your answer
Follow this Question
Related Questions
How faster is private variables over public variables? 1 Answer
Is this the right way to make a variable available to other scripts? 1 Answer
How to change public variable by another script 0 Answers
Variable Not Changing In Method 1 Answer
what public variables can be shown and changed in the inspector 1 Answer