Sergio
Sergio

Reputation: 88

Best way to declare class properties in Unity3D

I am new to Unity 3D development and I wanted to know what is the best way to declare attributes of a class to be assigned later from the editor. I have seen mainly two:

public class MyObject : MonoBehavour {

    public GameObject relatedObect;

}

and

public class MyObject : MonoBehavour {
    [SerializeField]
    private GameObject relatedObect;

}

I understand that it is of the second form because the encapsulation is maintained, but I am not sure.

Upvotes: 1

Views: 1420

Answers (3)

trollingchar
trollingchar

Reputation: 790

In addition to Jack Mariani's answer, I want to mention RangeAttribute and HideInInspectorAttribute.


[Range (min, max)]

If there's one, the inspector will show a slider instead of just a number. You move a slider and the value changes in specified range.

[SerializeField] [Range (0, 5)] private float _speed;

Documentation


[HideInInspector]

You should use it when you do not want a public variable to show up in the inspector (they are shown by default):

[HideInInspector] public float X;

Documentation

Upvotes: 1

Jack Mariani
Jack Mariani

Reputation: 2408

Please consider that in the example you declared class fields, and not properties. They are both members of a class, but they are quite different.

For the sake of this answer I'll focus on your example, so I'll talk about fields.

Both public and [SerializeField] private let you inject a value in the Unity Inspector, but they act differently in the scripts.

1 - public field

You declare a public field when you want it to be used or set from another class. This choice goes against encapsulation, because other script may access it. It still might be an intended behaviour if you require the field to be accessible.

2 - [SerializeField] private field

You use this when you want to set the item in the inspector, but you do not want the other classes to see it. This option is better for encapsulation, because in this way no other script may access or change this field.

Upvotes: 3

Jichael
Jichael

Reputation: 820

Second is the way to go if you want to do things "properly". But unfortunately there is a "bug" that throws warning on every private you set via the editor. I saw on github that it is finally getting fixed, but in the meantime if you want to remove the warning you can put your variables between pragma warning disable 0649 and pragma warning restore 0649

Upvotes: 1

Related Questions