- Home /
Difference between [HideInInspector] public variable and using private variable with getter/setter property
If I want to make a variable accessible to other scripts, but not view-able or editable via the inspector, is there a difference between doing:
[HideInInspector]
public bool tf;
rather than doing:
private bool tf;
....
public bool TF
{
get { return tf; }
set { tf = value; }
}
Is one way more efficient or better in any way than the other?
Thanks
Answer by MacDx · Oct 04, 2017 at 06:20 PM
I wouldn't say one is more efficient thant the other. This is a matter of code design. If your get and set will do nothing else than returning and modifying the value then I don't think a property is worthy of your time. Properties are worth using when there will be more logic to your gets and sets like, triggering an action after a value change, or some value clamping, value validation, etc. you name it. They can also be used on interfaces.
So if you won't use it the way I mentioned then I think you are better off with the public field plus the HideInInspector attribute
Another reason why to use a property might be to provide an interface to the value.
Basically something like this:
public interface ITFInterface
{
bool TF { get; set; }
}
So a class can implement an interface like this and other scripts can use the interface ins$$anonymous$$d of directly accessing the class. This helps to decouple classes in certain situations and allows to exchange the actual class used. Though this is usually only used when you have a larger system and several different implementations or if the class may be used in several different situations. As you said it's a matter of code design and concept.
Your answer
Follow this Question
Related Questions
Efficiency of static properties 2 Answers
public private and static variables in js 1 Answer
C# private/public 2 Answers
When to use private var. and public var.? 4 Answers
Animation vs Mathf.Sin() 0 Answers