Types of Access Modifiers
Keywords placed before variables or functions to determine where they can be used.
public (Public)
- Description: Accessible from anywhere
- Unity Inspector: Visible and editable
- Other classes: Accessible
public class Human : MonoBehaviour
{
public string myName; // Visible in Inspector, accessible from other classes
public void Eat() { // Can be called from other classes
Debug.Log("Eating");
}
}
private (Private)
- Description: Can only be used within the same class
- Unity Inspector: Not visible
- Other classes: Not accessible
- Inherited classes: Not accessible
public class Human : MonoBehaviour
{
private int myAge; // Not visible in Inspector, not accessible from other classes
private float myHeight; // Not visible in Inspector
private void Sleep() { // Cannot be called from other classes
Debug.Log("Sleeping");
}
}
When Access Modifier is Omitted
- When nothing is written before variable or function: Behaves the same as
private - C# default: Automatically becomes
privatewhen omitted
public class Human : MonoBehaviour
{
int myAge; // Same as private (when omitted)
float myHeight; // Same as private (when omitted)
void PowerPush() { // Same as private (when omitted)
Debug.Log("Pushing");
}
}
Access Modifier Comparison
| Access Modifier | Same Class | Child Class | Other Class | Unity Inspector |
|---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ Visible |
private |
✅ | ❌ | ❌ | ❌ Not visible |
| Omitted | ✅ | ❌ | ❌ | ❌ Not visible |
When to Use What?
Use public
- When you want to set values in Unity Inspector
- When other scripts need to access it
- When child classes need to use it
Use private
- Variables/functions used only within the class
- Important data that shouldn't be accessed externally
- When you want to increase code safety