I-am-developer-9
I-am-developer-9

Reputation: 494

How to make a static class Derive by MonoBehaviour

recently I am making a game. There is a script named SizePositionForBullet.cs the code of it was as:-

using UnityEngine;
using UnityEngine.UI;
public class SizePositionForBullet : MonoBehaviour
{

    #region variables
    //public variables
    public Slider widthSetByUser;
    public Slider heightSetByUser;
    public Slider posXSetByUser;
    public Slider posYSetByUser;

    //private variables
    public float width;
    public float height;
    public float posX;
    public float posY;

    #endregion
    void Update()
    {
        #region Getting Player Prefs
        posX = PlayerPrefs.GetFloat("posX", 323);
        posY = PlayerPrefs.GetFloat("posY", 175);
        width = PlayerPrefs.GetFloat("Width", 150);
        height = PlayerPrefs.GetFloat("Height", 150);
        #endregion
    }


    public void GetSliderValue(int pos)
    {
        if (pos == 1)
        {
            PlayerPrefs.SetFloat("posX", posXSetByUser.value);
        }
        if (pos == 2)
        {
            PlayerPrefs.SetFloat("posY", posYSetByUser.value);
        }
        if (pos == 3)
        {
            PlayerPrefs.SetFloat("Width", widthSetByUser.value);
        }
        if (pos == 4)
        {
            PlayerPrefs.SetFloat("Height", heightSetByUser.value);
        }
    }
}

So I need to use it's height , width and posX, posY variable in other class. So I added this code in class

public SizePositionForBullet _instance;
public static SizePositionForBullet Instance
{
    get{
          if(_instance == null)
          {
              _instance = GameObject.FindObjectOfType<BulletSizePosition>();
          }
          return _instance;
       }
}

But when I use it in other class as it:-

float width = BulletSizePosition.Instance.width;

Unity saying: Null refrence Exception Object refrence not set to an instance of object at Assets/Scripts/BulletScript

How to solve it?

Upvotes: 0

Views: 2036

Answers (1)

D.B
D.B

Reputation: 594

Your private _instance must be static too.

You are using the Singleton pattern. If this class reflect only player save (playerprefs) you don't have to make inheriting from MonoBehaviour.

public class MyPlayerSettings
{

    public float Size;
    ...

    private MyPlayerSettings()
    {
        LoadPreferences();
    }

    public void LoadPreferences()
    {
        // Get all your pref here
        Size = PlayerPrefs.GetFloat("Size");
        ...
    }

    public static MyPlayerSettings Instance
    {
        get
        {
            if(instance == null)
            {
                instance = new MyPlayerSettings();
            }
            return instance;
        }
    }

    private static MyPlayerSettings instance;
}

Upvotes: 1

Related Questions