I just fishined Obstacle Course.
Before I learned a little bit of Unity on youtube.
Many people use public instead of [serializefield] .
I would like to like the difference between it.
Can some one help me.
Hi,
[SerializeField] allows us to expose private
fields in the Inspector. We try to avoid making our variables public
because everything with a reference to out object could change the value of said variables. As you can probably imagine, this might result in bugs in more complex projects, especially when working in teams. Figuring out who or what changed the value unexpectedly can be time-consuming. With private
, we only have to check one class because only objects of that class are able to access the private
members.
In OOP, using private
is considered good practice.
Did this clear it up for you?
See also:
- Forum User Guides : How to mark a topic as solved
Thank you very much!
For me a little difficult
But I will save your words. Maybe I will get it later
Public fields can be accessed outside the class. If you have a Health
class with a public Value
field, any other class have access to this Value
field. Because these values are public, the inspector has access to it and can display the values for us to configure.
Private fields can not be accessed from outside the class. If our Health
class’s Value
field was private, no other class would have access to it. To display a private field in the inspector, we need to add the [SerializeField]
attribute to it. Now it is still private, but the inspector has access to it and can display it for us to configure.
Here’s a little example (these are just standard classes)
public class Health
{
public int MaxValue;
private int Value;
public Health(int maxValue)
{
MaxValue = maxValue;
Value = maxValue;
}
}
public class Player
{
public void Test()
{
Health health = new Health(100);
// this is fine because MaxValue is public and we all have access to it
int max = health.MaxValue;
// this will not compile because Value is private and we do not have access to it
int value = health.Value;
}
}
As Nina has mentioned, we want to avoid making fields public. It is not wrong, but it can come back to haunt you in the future. It’s just good practice.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.