Advantages of using private and using getComponent?

A lot of the times when I watch scripting tutorials, they tend to write something like “private GameObject” and then in the start function use GetComponent to find it. However, I always find it easier and more clear when I just make it public and drag and drop. What are the advantages of using private?

Primarily you would use private so that other classes could not access or manipulate the class without restrictions. There are times when you dont want something being mucked (usually by accident) by other classes.

Use the SerializeField attribute to expose private properties in the inspector if you desire them to be edited in the editor but dont want them to be accessible to everything elsewhere.

2 Likes

GetComponent is useful when what you’re getting is only available at runtime, since you can’t get it via an inspector reference. But otherwise I’d agree that setting in the inspector is preferable when possible. Public vs private comes down to what you want accessible from outside the class.

The whole public vs private thing is more important when your developing in large teams, where the people using the class isn’t the same as the person who wrote it.

1 Like