Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Update not being called

Discussion in 'Scripting' started by supervelly, Mar 23, 2019.

  1. supervelly

    supervelly

    Joined:
    Dec 6, 2017
    Posts:
    16
    Hi all,
    I can't seem to figure out what I have done wrong.

    I made a generic Singleton Object like so:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Singleton<T> : MonoBehaviour where T : Component
    4. {
    5.     private static T instance;
    6.     public static T Instance
    7.     {
    8.         get
    9.         {
    10.             if (instance == null)
    11.             {
    12.                 instance = FindObjectOfType<T>();
    13.                 if (instance == null)
    14.                 {
    15.                     GameObject obj = new GameObject();
    16.                     obj.name = typeof(T).Name;
    17.                     instance = obj.AddComponent<T>();
    18.                 }
    19.             }
    20.             return instance;
    21.         }
    22.     }
    23.  
    24.     protected virtual void Awake()
    25.     {
    26.         if (instance == null)
    27.         {
    28.             instance = this as T;
    29.         }
    30.         else
    31.         {
    32.             Destroy(gameObject);
    33.         }
    34.     }
    35. }
    36.  
    Afterward I created a GameManager class:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class GameManager : Singleton<GameManager>
    4. {
    5.     [SerializeField]
    6.     private float gameTimer;
    7.     public float GameTimer => gameTimer;
    8.  
    9.     protected override void Awake()
    10.     {
    11.         base.Awake();
    12.         Debug.Log("Started Game manager");
    13.     }
    14.  
    15.     private void Update()
    16.     {
    17.         gameTimer -= Time.deltaTime;
    18.     }
    19.  
    20. }
    21.  
    My problem is that the update method on the GameManager is never being called.
    and it is attached to a game object in the active scene

    any ideas?

    Thanks in advance
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Is the object active? Is the script itself active?
     
  3. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    Did you debug log the update function?
     
  4. supervelly

    supervelly

    Joined:
    Dec 6, 2017
    Posts:
    16
    My problem was that another script was calling the instance of the singleton in it's awake before.
    so it did the destory method and the object was destoryed.
    Took me a while to figure out what happens