Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Advantages of using private and using getComponent?

Discussion in 'Getting Started' started by CalebLee123, Jul 25, 2020.

  1. CalebLee123

    CalebLee123

    Joined:
    Aug 2, 2017
    Posts:
    3
    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?
     
  2. TimmyTheTerrible

    TimmyTheTerrible

    Joined:
    Feb 18, 2017
    Posts:
    186
    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.
     
    Vryken and CalebLee123 like this.
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    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.
     
    CalebLee123 likes this.