Unity variable modifiers of protected, internal, const, readonly, static

Article directory

  • protected
  • internal
  • const
  • readonly
  • static


protected

When programming in C# in Unity, protected is an access modifier used to control the visibility and access rights of class members (fields, methods, properties, etc.). Members modified by protected can be accessed within the current class, derived classes (subclasses), and other classes in the same namespace, but are not visible outside the class. Here are more detailed instructions and examples:

Features and usage:

  • The protected modifier allows members to be inherited and accessed in inheritance relationships.
  • protected members can be overridden (methods) or extended (fields and properties) in subclasses.
  • protected members are not allowed to be accessed directly outside the class, but can be accessed through instances of the base class in inherited subclasses.

Example:

// base class (parent class)
public class Animal
{<!-- -->
    protected string species; // Only visible in the current class and its subclasses

    public Animal(string species)
    {<!-- -->
        this.species = species;
    }

    protected void MakeSound()
    {<!-- -->
        Debug.Log("Animal makes a sound");
    }
}

// derived class (subclass)
public class Dog : Animal
{<!-- -->
    public Dog() : base("Dog")
    {<!-- -->
        // Subclasses can access protected fields and methods of the base class
        species = "Canine";
        MakeSound(); // Call the protected method of the base class
    }

    public void Bark()
    {<!-- -->
        Debug. Log("Dog barks");
    }
}

// used in other classes
public class GameManager
{<!-- -->
    void Start()
    {<!-- -->
        // The protected members of the Animal class cannot be directly accessed here.
        // Animal animal = new Animal("Generic Animal");
        // animal.species = "Unknown"; // Error! Inaccessible

        Dog dog = new Dog();
        // Can access protected fields and methods in the base class
        dog.species = "Domestic Dog"; // Legal because it is accessed in a subclass
        dog.MakeSound(); // Legal because it is accessed in a subclass

        dog.Bark(); // Call the public method of the subclass
    }
}

In this example, the Animal class serves as the base class (parent class) and has a protected field species and a protected >Method MakeSound(). As a derived class (subclass), the Dog class inherits the Animal class and can access the protected members of the base class. The Dog class also defines its own public method Bark().

In the GameManager class, we cannot directly access the protected members of the Animal class, but we can access it through instances of the Dog class Come visit. This demonstrates the role of the protected modifier in an inheritance relationship, allowing subclasses to access protected members of the base class, but not direct access outside the class.

internal

In the C# programming language and in Unity game development, internal is an access modifier that controls the visibility and access rights of class members. internal modified members can be accessed in any class within the same assembly (assembly), but are not visible outside the assembly. Here is a more detailed introduction and examples:

Features and usage:

  • The internal modifier is used to declare members inside a class that can be accessed from other classes in the same assembly but are not visible outside the assembly.
  • The internal member is useful for implementing details and hiding data within the module without exposing it to code outside the assembly.

Example:

Suppose you are developing a Unity game that contains the following script files:

  1. Player.cs
using UnityEngine;

public class Player : MonoBehaviour
{<!-- -->
    internal int playerScore; // Visible in other classes in the same assembly

    internal void UpdateScore(int points)
    {<!-- -->
        playerScore += points;
    }
}
  1. GameManager.cs
using UnityEngine;

public class GameManager : MonoBehaviour
{<!-- -->
    void Start()
    {<!-- -->
        Player player = new Player();
        player.UpdateScore(10); // Internal methods and fields can be accessed in classes in the same assembly
        Debug.Log("Player score: " + player.playerScore);
    }
}

In this example, the Player class and the GameManager class are both in the same assembly (Unity project). The field playerScore and method UpdateScore() in the Player class are declared as internal, so they can be in the same Accessed from other classes in the assembly, such as the GameManager class.

However, if we try to access playerScore or UpdateScore() in a class outside the assembly, a compilation error will occur.

To sum up, the internal modifier is used in Unity development to control the visibility of class members to ensure that these members are only visible within the same assembly. This is useful for hiding internal details, enabling modularity, and preventing unauthorized access.

const

In the C# programming language and in Unity game development, const is a keyword used to declare constants. Constants are values that cannot be modified while the program is running. They must be initialized when declared, and once initialized, they cannot be changed. Here is a more detailed introduction and examples:

Constant properties and usage:

  • The const keyword is used to declare a constant. Once declared and initialized, its value remains unchanged throughout the life cycle of the program.
  • Constants must be initialized when declared, and can only be initialized within the declaration statement.
  • Constants can only contain basic data types (such as integers, floating point numbers, Boolean values) and string types.
  • Constants are replaced with values at compile time, which helps improve the performance of your code.

Example:

public class Constants
{<!-- -->
    public const int MaxPlayerHealth = 100;
    public const float Gravity = 9.81f;
    public const string GameTitle = "My Awesome Game";
}

public class Player : MonoBehaviour
{<!-- -->
    private int health = Constants. MaxPlayerHealth;

    void Update()
    {<!-- -->
        if (Input. GetKeyDown(KeyCode. Space))
        {<!-- -->
            health -= 10;
            Debug. Log("Player health: " + health);
        }
    }
}

In this example, the Constants class defines three constants: MaxPlayerHealth, Gravity, and GameTitle. These constants are initialized when declared, and they remain unchanged throughout the run of the program.

In the Player class, we use Constants.MaxPlayerHealth to initialize the player’s health value and decrement the player’s health value each time the space bar is pressed. Because MaxPlayerHealth is a constant, its value has been determined at compile time and will not be modified at runtime.

In short, the const keyword is used to declare constants that remain unchanged during the running of the program. Constants are suitable for situations where fixed values need to be used, such as maximum values, commonly used constants, etc. In Unity development, constants can be used to avoid magic numbers, improve code readability, and ensure that certain values are not modified incorrectly.

readonly

In the C# programming language, readonly is a keyword used to declare read-only fields. Read-only fields are initialized when declared, and their values cannot be modified later. In contrast, const is used to declare compile-time constants, and readonly is used for fields that are only allowed to be initialized once at runtime. Here is a more detailed introduction and examples:

readonlyFeatures and usage:

  • The readonly keyword is used to declare read-only fields. These fields must be initialized when declared or in the constructor, and cannot be modified later.
  • readonly fields are typically used for values that remain unchanged for the lifetime of an instance of a class, but allow initialization as needed in the constructor.
  • Unlike const, the value of a readonly field is determined at runtime and can be initialized based on the state of the object.

Example:

public class Circle
{<!-- -->
    public readonly float Radius; // read-only field

    public Circle(float radius)
    {<!-- -->
        Radius = radius; // Initialize read-only fields in the constructor
    }

    // mistake! Cannot assign to a readonly field outside the class
    // public void UpdateRadius(float newRadius)
    // {<!-- -->
    // Radius = newRadius;
    // }
}

public class Program
{<!-- -->
    static void Main(string[] args)
    {<!-- -->
        Circle circle = new Circle(5.0f);
        Console.WriteLine("Circle radius: " + circle.Radius); // Output: 5

        // mistake! The value of a read-only field cannot be modified outside the class
        // circle.Radius = 10.0f;
    }
}

In this example, the Circle class defines a read-only field Radius, which is initialized in the constructor. Once initialized, the value of Radius cannot be modified. In the Program class, we create a Circle object to store the radius of the circle through the read-only field Radius and display it in the output The value of the radius.

It should be noted that the readonly field cannot be modified elsewhere after it is declared or initialized in the constructor. This is useful for ensuring that some values remain unchanged for the lifetime of the object, while also allowing values based on specific conditions to be initialized in the constructor.

static

In the C# programming language, static is a keyword used to declare static members, methods and classes. Static members are not tied to a specific instance, they remain unchanged throughout the lifetime of the application. Static members can be accessed directly through the class name without creating an instance of the class. Here’s a more detailed introduction and examples:

staticFeatures and Usage:

  • The static keyword is used to declare static members, which are associated with the class rather than with instances (objects) of the class.
  • Static members have only one copy in memory, and their values are the same no matter how many instances of the class are created.
  • Static members remain unchanged throughout the lifetime of the application and can be accessed without creating an instance of the class.

Characteristics of static methods:

  • Static methods can be called directly through the class name without creating an instance of the class.
  • Instance members cannot be accessed inside static methods because they are not associated with a specific instance.
  • Static methods are usually used for operations that do not depend on the state of the instance, such as mathematical functions, utility methods, etc.

Characteristics of static fields:

  • Static fields are fields associated with a class, and all instances of a class share the same field.
  • Static fields are usually used to save globally shared state, such as counters, configuration values, etc.

Example:

public class MathUtils
{<!-- -->
    public static int Add(int a, int b)
    {<!-- -->
        return a + b;
    }
}

public class Counter
{<!-- -->
    private static int count; // static field

    public static void Increment()
    {<!-- -->
        count + + ;
    }

    public static int GetCount()
    {<!-- -->
        return count;
    }
}

public class Program
{<!-- -->
    static void Main(string[] args)
    {<!-- -->
        int sum = MathUtils.Add(5, 3); // Call static method
        Console.WriteLine("Sum: " + sum);

        Counter.Increment(); // Call static method
        Console.WriteLine("Count: " + Counter.GetCount()); // Output: 1
    }
}

In the above example, the MathUtils class defines a static method Add() that can be called directly through the class name. The Counter class defines a static field count and two static methods for increasing and obtaining counters. In the Program class, we call the MathUtils.Add() static method and the static method of the Counter class to demonstrate the use of static members.

In summary, the static keyword is used in C# to declare static members, which remain unchanged throughout the life cycle of the application and can be accessed without creating an instance of the class. Static members play an important role in global shared state, providing tool functions, etc.