I’m basically trying to make a singleton using C# in Unity. My code are as follows:
using UnityEngine;
using System.Collections;
public class GameConfig : MonoBehaviour
{
protected static GameObject m_instance = null;
protected static GameConfig m_config = null;
// Game Settings
public int m_MaximumPlayers = 1;
public float m_MovementResolution = 0.001f;
// Game Timer
public float m_Time = 99.0f;
public bool m_IsCountdownTimer = true;
public static void Start()
{
if( m_instance )
{
// This gameobject shouldn't exist when there's already one.
if( m_instance != gameObject ) // error CS0120
{
Destroy( gameObject ); // error CS0120
}
return;
}
m_instance = gameObject;
m_config = m_instance.GetComponent< GameConfig >();
}
public static GameConfig Config
{
get
{
return m_config;
}
}
public static GameObject Instance
{
get
{
return m_instance;
}
}
}
I get error CS0120 on the lines marked. This error reads as “`UnityEngine.Component.gameObject’: An object reference is required for the nonstatic field, method or property”.
This looks like gameObject does not refer to the instance of the game object the script is attached as a component. How do I fix this?
Seriously, we should have a dedicated C# thread with syntax equivalence to JavaScript on the documentation. It’s not as simple as some people think you know. (e.g Who would thought the syntax for GetComponent(Type) would be GetComponent()? ).