- Home /
How do I create public read-only properties?
I want my script to publish some variables at runtime that could be read by other scripts, but they cannot modify them. Also I don't want these variables to appear at Unity's editor.
Thank you!
@Edy, I was about to suggest you also upvote the answer you checkmarked - but then I remembered it takes 15 points to upvote, at least according to the FAQ. Wups.
Thank you for the suggestion. I'm new to this great system, and I'm still getting used to it. Time to read the FAQ I guess :)
Answer by Mike 3 · May 29, 2010 at 08:10 PM
best way is to either use functions or properties
functions will work in js and c#:
(js)
var test : float = 1;
function getTest() : float { return test; }
(c#)
float test = 1;
public float getTest() { return test; }
the alternative is properties in c#:
float test = 1;
public float Test { get { return test; } }
Thanks to both of you! I've marked this one just because it's most complete, and also I'm currently using javascript (sorry, I forgot to specify that in the question)
Answer by Edy · May 30, 2010 at 10:27 PM
I've just discovered that you can actually access the private variables in one script from other script! You can use them exactly as if they were public variables (at least in Javascript, didn't tested in C#).
I guessed that the 'private' keyword would keep the variable isolated from other scripts, but it's more like a "non-publish-in-editor" tag.
Edit: You can access the private variables only when accessing the script this way:
var myScript = Vehicle.GetComponent(myScriptName);
var value = myScript.privateValue;
It depends how you access the script - if you reference it with dynamic typing (e.g. GetComponent(moo).variable), it'll get the member data with reflection (which is slow). In c# you can't really do that without doing the reflection yourself, which is a lot more work
Ok, thanks! I think I'll go the straight way and use the getter functions :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613034859im_/https://answers.unity.com/themes/thub/images/avi.jpg)