- Home /
Getters issue...
in the file teste.js --->
class happy
{
private var _x : float = 0.0;
function get x () : float { return _x; }
function set x (value : float)
{
Debug.Log("hey someone set the x value using an equals sign! whoa!");
_bar = value;
}
function Start()
{
Debug.Log("getters and setters in Unityscript are easy and happy");
}
}
All no problem. But, if you do this
in the file teste.js --->
var x:int;
it makes a variable "x" in the ingenious "Inspector" (Apple-3) panel of the Unity3D Editor. Great.
You can guess what I'm going to ask ... How can I basically do this ...
functionOrWhatever setOrWhatever x
{
Debug.Log("hey, somebody changed x, perhaps in the Inspector!");
x = x whatever;
}
in other words, how to do the getters / setters for the "magic'd" variables in the "implicit" classes in Unityscript
{by "implicit" I just mean the feature where if you can just blurt out code using the magic where the filename becomes the class, etc etc -- I don't actually know what the term is, if any, for that sloppy magic in Unity javascript files}
Or, in a word - if for some reason it's not possible to get at those getters/setters, quite simply
how to know if someone has changed x in the Editor Inspector window?
Sorry for yet another ultra-lame Unityscript question.
This is a QA site. Please phrase the title as a question since it makes it far easier for newcomers to understand what you're trying to solve. If you can't phrase it as a simple question, I'd consider posting the issue on the Unity Forums ins$$anonymous$$d.
Answer by Loius · Jun 24, 2012 at 03:23 AM
You can only see public vars in the inspector.
But! There's a solution.
Build a custom editor for your class:
"ClassNameEditor.js" - goes in a folder named "Editor"
@CustomEditor(ClassName)
class ClassNameEditor extends Editor {
function OnInspectorGUI() {
super.OnInspectorGUI();
var x : int = EditorGUILayout.IntField("Ecks", target.ecks);
if ( x < 0 ) x = 0;
target.ecks = x;
}
}
"target" always refers to the currently-being-edited-in-the-Inspector ClassName object, so if ClassName is:
private var ecks : int;
You now have total control over 'ecks' but the user thinks they own it. Also that code just prevents negative numbers being entered.
That is so incredible I will have to think about it for awhile... thanks ...
TBC ... in fact, for a moment setting aside the Inspector issue ... in fact, how the hell do you get at the getters / setters, for a variable which is "magic'd" like that? (ie, is just part of the class equal to the filename.js ?)
is there a way ?!
thanks again !
You can still use get/sets -
[test.js]
class Test extends $$anonymous$$onoBehaviour {
private var _x : int;
function get x() : int { return _x; }
function set x(value:int) { _x = $$anonymous$$athf.$$anonymous$$ax(0,value); }
}
[tested.js]
@CustomEditor(Test)
class TestEd extends Editor {
function OnInspectorGUI() {
super.OnInspectorGUI();
target.x = EditorGUILayout.IntField("X",target.x);
}
}