Unity3D creates class singleton

Hits: 0

public class Simple{

     public static Simple sSimple;

     private Simple() {
           //set the class constructor as a private method here
     }

     public static Simple getInstance() {
           if (sSimple == null )
               sSimple = new Simple();
          return sSimple;
     }
}

The class singleton pattern created by Unity3D and java is actually the same. First, judge whether it exists or not, and create it if it does not exist. Now let’s take a look at the creation of general singletons in java:

However, in unity3D, it is not possible to simply judge whether it is null, because the public objects in it are bound by dragging and dropping. When the star is in these objects, operations such as initialization are performed, or before the next time. operation, so if we judge null and recreate it, we will lose those bound objects. How to write it? Take a screenshot:


In this method, the judgment of null is replaced by finding whether the singleton we need exists in the game

It’s actually quite simple, isn’t it?

You may also like...

Leave a Reply

Your email address will not be published.