As we begin developing with Unity, we will write code and create objects. In this process, we need to understand one of the core concepts of Object-Oriented Programming (OOP): ‘access modifiers’. Access modifiers control the access rights to the members (variables, methods) of a class or object, making data protection and code maintenance easier.
1. What are Access Modifiers?
Access modifiers are keywords that allow setting the level of access to the members of a class in object-oriented languages. Through them, we can control which members can be accessed, thereby enhancing code safety and reducing unnecessary errors.
2. Access Modifiers Used in Unity
The main access modifiers used in Unity are as follows:
- public: Accessible from any class
- private: Accessible only within the class
- protected: Accessible in the class and in derived classes
- internal: Accessible only within the same assembly
- protected internal: Accessible within classes in the same assembly and in derived classes
2.1 public
When using the public access modifier, the member can be accessed from any class. This allows for easy reference from other objects.
public class Player { public int health; public void TakeDamage(int damage) { health -= damage; } }
2.2 private
The private access modifier is used to protect data. The member can only be accessed within the declared class.
public class Player { private int health; public void TakeDamage(int damage) { health -= damage; } }
2.3 protected
The protected access modifier allows access only within the class and in classes that inherit from it.
public class Player { protected int health; } public class Warrior : Player { public void Heal() { health += 10; } }
2.4 internal
The internal access modifier refers to members that can only be accessed within the same assembly.
2.5 protected internal
Protected internal is an access modifier that combines the characteristics of protected and internal. That is, it is accessible within the same assembly and also in derived classes.
3. Reasons for Using Access Modifiers
There are several reasons for using access modifiers.
- Data Protection: Prevents direct access to data from outside, avoiding errors that could occur due to incorrect values.
- Code Maintenance: Access modifiers help clarify the structure of the code, making it easier to maintain.
- Encapsulation: Encapsulates the internal implementation of a class, preventing unintended access from outside.
4. Conclusion
In object-oriented languages like Unity, access modifiers are essential for enhancing the stability of code and providing clarity of structure. Understanding the basic concepts and using them effectively is a significant aid in becoming proficient as a developer. Continue to deepen your learning about access modifiers with various examples.