0

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?

  • GameObject.FindObjectOfType(); might be returning null. – Athul Raj Oct 13 '20 at 04:50
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Oct 13 '20 at 07:23

1 Answers1

1

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;
}
D.B
  • 588
  • 3
  • 17