this code attached to field of view slider…
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class FieldOfViewSlider1 : MonoBehaviour {
private Slider Slider;
void Start () {
Slider.value = Camera.main.fieldOfView;
}
void Update () {
}
}
and this to camera…
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MainCamera : MonoBehaviour {
private float FieldOfView;
void Start () {
FieldOfView = PlayerPrefs.GetFloat ("FieldOfView");
Camera.main.fieldOfView = FieldOfView * 10;
}
void Update () {
FieldOfView = GameObject.Find ("Field Of View Slider").GetComponent <Slider> ().value;
}
void OnApplicationQuit () {
PlayerPrefs.SetFloat ("FieldOfView", FieldOfView);
}
}
very broken, as you can see. im trying to save the fov variable.
private Slider Slider
Should be public
And assign the slider from the inspector
I see what you’re trying to do. So let’s take this one by one.
First, your slider is in fact null during the start function of FieldOfViewSlider1. When you initialize it, so far as your script is concerned, it’s null, and then you try to access it before you do.
To solve this, update as below .
private Slider fovSlider;
void Start () {
fovSlider = GetCompoent<Slider>();
fovSlider.value = Camera.main.fieldOfView;
}
Secondly, in your MainCamera at Start(), you’ve never set a player pref, so when you try to assign it, it is in fact null. To avoid this, only assign it if the key has been set. Like the following:
if (PlayerPrefs.HasKey("FieldOfView"){
FieldOfView = PlayerPrefs.GetFloat ("FieldOfView");
}
Lastly, I think your logic is just generally a little funky and overcomplicated. All of this could be handled in your FieldOfViewSlider1 Script/object, saving you the Find and Get Component Calls of your Update.
Best of luck!
Null Reference Exception means that something you are trying to reference is null.
So when it tells you which line is giving you the null reference exception, then you know that whatever object is in that line of code isn’t actually referencing anything.
In this particular case, it’s right at the beginning…
public class FieldOfViewSlider1 : MonoBehaviour {
private Slider Slider;
void Start () {
Slider.value = Camera.main.fieldOfView;
}
You have a private value Slider (which should totally not be named that… ) that you have never assigned a value to.
Then immediately afterwards you are trying to assign to the value of that uninitialized variable.
Also, you’re doing this in your other script.
void Update () {
FieldOfView = GameObject.Find ("Field Of View Slider").GetComponent <Slider> ().value;
}
This is a HUGE mistake. You should do GameObject.Find at most once, ever… on start… and store the object you get back in a local variable.