Skip to main content

Making Singleton

Singleton Script 

Let us make a GameManager Script which will be singleton and will not destroy between scene loading or changing.
First of all create empty Gameobject in hierarchy inside unity game engine, rename it to "GameManager".
Now click on Add Component inside the inspector panel and create a new script namely "GameManagerScript".
Open GameManagerScript in Visual Studio/ Monodevlop,

Write the following code :

using UnityEngine;

public class GameManagerScript : MonoBehaviour
{
   public static GameManagerScript instance;

   void Awake()
  {
         if(instance != null)
         {
          Destroy(gameobject);
          }
         else
         {
          instance = this;
          DontDestroyOnLoad(gameobject);
          }
   }

}

Comments

Popular posts from this blog

Restricted Bullets

In this script, fire rate of bullet is controlled i.e, only 1 bullet fire at a time. public GameObject Bullet; //Drag and drop Bullet prefab inside Bullet in the inspector panel public Transform Position; //Drag and drop Shoot position inside position in the inspector panel float Attack_Timer = 0.3f; float Current_Attack_Timer; bool CanAttack; void Update( )   {    Attack( ) ;   } void Attack( )  {    Attack_Timer += Time.deltaTime;   if(Attack_Timer > Current_Attack_Timer)    {      CanAttack = true;    }  if(Input.GetKeyDown(KeyCode.Space)   {      if(CanAttack)        {           Instantiate(Bullet,Position.position,Quaterninon.identity);           CanAttack = false;           Attack_Timer = 0f;         }    }  }