A
A
Alexey2017-08-28 20:15:26
C++ / C#
Alexey, 2017-08-28 20:15:26

How to restrict access to variables?

The question of restricting access to variables is very worrying, what is the right thing to do?
Now I do this: I write [SeriasableField] over all private variables that need to be displayed in the inspector, if another script somehow uses this variable, then I write a public Get or Set method. Is it worth it to do this or just declare such variables public?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2017-08-28
@Alexeee

This is more a matter of taste, I have seen both options, I also use SerializeField myself, but more often I tend to properties, not methods, but, again, it all depends on the project. I also often saw an approach of the form:

[SerializeField]
private int _field;
public int field { get { return _field; } set { _field = value; } }

If we talk about abstract code in a vacuum, then it is better to send data outward through interfaces in general, but this is not always advisable, especially in the context of a unit. But in general, yes, with any public field there is a risk that someone will pull it from the outside and break something, therefore it is better to limit the visibility of variables to the maximum.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question