NullReferenceException: Object reference not set to an instance of an object OptionsController.Update () (at Assets/Scripts/OptionsController.cs:26)
I am making this script and im very confused why it isn't working, i have checked it thoroughly and i cant see why is is giving me this error, somebody please help!
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class OptionsController : MonoBehaviour {
private Slider slider;
[SerializeField]
private string sliderType;
private float volume;
void Start()
{
if (PlayerPrefs.GetFloat(sliderType) == null)
{
PlayerPrefs.SetFloat(sliderType, 0.5f);
}
slider = GetComponent<Slider>();
slider.value = PlayerPrefs.GetFloat(sliderType);
}
private void Update()
{
volume = slider.value;
}
public void Apply()
{
PlayerPrefs.SetFloat(sliderType, volume);
}
}
Answer by Bunny83 · Oct 18, 2017 at 06:53 PM
Well, there simply is no Slider component attached to the gameobject where this script is attached to. GetComponent will look for the desired component on the same gameobject where this script is attached to. So there might be one on a child object or a completely different gameobject but not on this one.
there is i made sure that there was when i was debigging
That's not possible. The only line inside your Update method is this:
volume = slider.value;
volume is getting assigned and is a value type. So the only thing that can actually produce a null reference exception is the "slider" variable. Trying do access something on the slider object fails if this reference is null (if it doesn't reference anything).
If you do this in Start:
slider = GetComponent<Slider>();
if(slider == null)
Debug.LogError("There is no slider component on this gameobject");
Do you see this error message in the console? If so then there is no Slider component on this gameobject. You may want to post a screenshot of your inspector while the object with this script attached is selected. It would also help to see the hierarchy to know where this gameobject is located.
Your answer

Follow this Question
Related Questions
My Turrent Trigger does not work 1 Answer
[noob] I have a script that theoretically should manage movement of a 2D GameObject... 1 Answer
Reference problem 1 Answer
IENumerator does not work 0 Answers