When to use SerializeField instead of public variable?

Hi,

Just wondering, was doing the Text101 chapter about the “Update Text Component”.
The video tells us to put [SerializeField] in front of a variable to make it available in the editor. Instead i used public in front of my variable, and the result is exactly the same;

  • [SerializeField] Text textComponent;
  • public Text textComponent;

My question: When do I use [SerializeField]? When do I use public?
And what are the different effects of using these?

thanks in advance,
Joost

1 Like

Hi Joost,

The public access modifier exposes things and makes them accessible from “outside”. Everything can use and manipulate public variables. For this reason, you want to make as few things public as possible.

With [SerializeField], we can keep our variable private while being able to expose it in the Inspector.

In lecture “Block Breaker Instructor Hangout #2” (currently #84) as of the 9:20 mark, Ben and Rick discuss why the public access modifier is “dangerous”.

Did this clear it up for you?

2 Likes

Hi,

Thanks for your reply Nina. It cleared things up!
Looking forward to do #84, might be a good side-note for #21

Regards
Joost

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms