- Home /
Variables not visible in editor but accessible from other scripts
I have a script that creates targets every few seconds. The Script keeps track of the amount of targets that are created and destroyed. The number of targets are stored in a private variable called TargetNum. I made it Private so that it is not visible and cannot be modified through the editor. I also have another script which needs to modify TargerNum but cannot because it is a private variable. How can i make the variable TargetNum not visible in the editor but is accessible and can be modified by other scripts? Whenever i try to access TargetNum throgh another script it gives and error : 'Creation.TargetNum' is inaccessible due to its protection level.'
Answer by Bunny83 · May 11, 2012 at 12:05 PM
It's even much easier ;)
Unity provides a special attribute to hide public members from the inspector: HideInInspector
// C#
[HideInInspector]
public int TargetNum;
// UnityScript
@HideInInspector
var TargetNum : int;
This variable is accessible from other classes since it's public, but Unity won't show it in the inspector.
On the other hand, using direct variable references is still bad coding practice in general.
Answer by syclamoth · May 11, 2012 at 11:12 AM
This is why we have getters and setters:
private int TargetNum = whatever;
public int GetTargetNum()
{
return TargetNum;
}
Then, whenever you would use 'TargetNum', use 'GetTargetNum' instead.
If you want to set the value, you can use
public void SetTargetNum(int value)
{
TargetNum = value;
}
Alternatively, you can do this:
private int _targetNum;
public int targetNum {
get {
return _targetNum;
}
set {
_targetNum = value;
}
}
Which neatly manages all that internally (just treat 'targetNum' like a normal public variable).