-1
\$\begingroup\$

What is the point of such work with variables?

public GameObject Obj => _obj;
[SerializeField] private GameObject _obj;

A private variable loses its privacy when we create a public variable that defines a private one. For me it looks meaningless and only confuses.

\$\endgroup\$
1
  • \$\begingroup\$ This practice of creating a private "backing field" to support a public property is not unique to game development, so this is the kind of general programming practice question that you can find answered on StackOverflow. \$\endgroup\$
    – DMGregory
    Nov 25 at 19:44
1
\$\begingroup\$

This doesn't create a public variable that defines a private one, it creates a public property. Using a property allows you to later add code you always want to get executed when that variable is getting set and/or read. This is not happening in this example (yet), but when you create properties like this preemptively, then it gets a lot easier to add this functionality later.

Further, this particular syntax creates a property which can only be read but not written. That means that other scripts can find out what _obj this component references, but they can not change it. There are often situations where changing a variable like that at runtime can lead to unexpected behavior. For example, when you do some stuff with that gameObject in Start(). So when you write a MonoBehavior which does not support changing a variable at runtime, then it's a good idea to follow this pattern so that nobody later thinks they can do that without causing any weird bugs.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.