[Unity] Single Instance in Game

Source: Internet
Author: User

In the game, some gameobjects (such as network managers) are required to exist throughout the game's lifecycle and exist in the form of a singleton.

In xgame, the singleton method is that the singleton script inherits from the monosingle class, And the monosingleton implementation method is called in awake (). Dontdestroyonload(Gameobject); To ensure the Singleton. Implementation Code of the monosingleton class:
 1 /// <summary> 2 /// Generic Mono singleton. 3 /// </summary> 4 using UnityEngine; 5  6 public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>{ 7      8     private static T mInstance = null; 9     10     public static T Instance{11         get{12             return mInstance;13         }14     }15 16     private void Awake(){17    18         if (mInstance == null)19         {20             DontDestroyOnLoad(gameObject);21             mInstance = this as T;22             mInstance.Init();23         }24         else25         {26             Destroy(gameObject);27         }28     }29  30     public virtual void Init(){}31 32     public virtual void Fini(){}33  34 35     private void OnApplicationQuit(){36         mInstance.Fini();37         mInstance = null;38     }39 }

The script that requires Singleton control only needs to inherit from the monosigleton class. Rewrite the init method to initialize the singleton class and rewrite Fini to clean up the job. For example:

[Unity] Single Instance in Game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.