Questions about the singleton pattern in unity?

based on unity and C-sharp, there is a code from conception to implementation as follows. I don"t understand why this code is singleton mode.

public class BoidSpawner : MonoBehaviour{
    static public BoidSpawner S;
        .....
    public GameObject boidPrefab;    
        ....
    void start(  ){
    //SBoidSpawner
        S = this;
    }

    void LateUpate(){
        .....
    }
}
< hr >

for the above code, there is no instance of BoidSpawner created. And I didn"t see it in the follow-up code.
for Java, usually the singleton pattern is simple and can be written as (the code in the rookie tutorial):

public class SingleObject {
 
   // SingleObject 
   private static SingleObject instance = new SingleObject();
 
   // private
   private SingleObject(){}
 
   //
   public static SingleObject getInstance(){
      return instance;
   }
 
   public void showMessage(){
      System.out.println("Hello World!");
   }
}

< hr >

the above code is easy to understand. An object of this class is created within the class, and the static method SingleObject is called to get a unique instance.
but I don"t understand the C-sharp paragraph. There is no instance of this class created in the BoidSpawner class, and for the BoidSpawner class that can create such objects frequently, new BoidSpawner (), does not quite understand the direction of the this in the code, because there is no new BoidSpawner () in the whole code. If you mount the script to a node, is this node an instance of this class?
does not mean that scripts in unity are like separate OOP classes, and scripts attached to scene objects are instances of objects. In fact, I don"t quite understand why the script becomes an instance of the object, and the object is not a class.

Jul.22,2021

The characteristic of

singleton pattern is that there is only one instance, and classes that meet this condition should at least have conditions that cannot be instantiated externally, that is, constructors are private, so private constructors are generally defined, and a static object is instantiated internally (under certain conditions) and accessed through a static get accessor.

BoidSpawner Why is it called a singleton? technically, it does not guarantee that the instance is unique. But in terms of application, if the external condition can guarantee that it produces a unique instance, referenced by a static S, then it is a singleton. The most typical application scenario is to use the DI framework, where all instances are generated by the DI framework and its uniqueness is guaranteed by the DI framework.

  • How to operate multiple contional features in C-sharp

    to achieve the effect of logical and operations on symbols, you can define sequence conditional methods. For example, the second method can be executed only if both An and B are defined: [Conditional ( "A ")] static void DoIfA () { DoIfAandB(); } [...

    Sep.23,2021
Menu