So i have this problem. When i launch the game player prefs will not start working until i enter my options scene. I have sliders that change the game volume and player prefs script attached to them. When i already were on the options menu scene the player prefs work without any problem. I want the player prefs to work immediately when the game launches.
I have tried putting the player prefs script on the first scene but then i need to attach sliders onto the script (which i cant because they are on a different scene)
Here is my code ( i have the sliders and the player prefs in the same script ) :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class audiomute : MonoBehaviour
{
public Slider slider01;
public Slider slider02;
void Awake()
{
slider01.value = PlayerPrefs.GetFloat("save");
slider02.value = PlayerPrefs.GetFloat("save2");
}
public void slider2(float audio2)
{
bgaudio.Instance.gameObject.GetComponent<AudioSource>().volume = audio2;
PlayerPrefs.SetFloat("save", audio2);
}
public void slider1(float audio)
{
AudioListener.volume = audio;
PlayerPrefs.SetFloat("save2", audio);
}
You should probably separate your script into two, one generic that handles data and that you don’t destroy on load and one for the sliders that will at start get a reference to this script on your options scene.
When i launch the game player prefs will not start working until i enter my options scene
What do you mean by “not working”? PlayerPrefs are stateless so I doubt that they are the problem.
Assuming that what you mean is that the volume isn’t getting set unless you go into your options scene, that’s understandable given your setup.
What you need is a script that will read the PlayerPrefs and set the volume on the AudioListener independent of the sliders. Sliders are just for setting the PlayerPrefs values, so you need to separate out the logic that reads the PlayerPrefs values and sets the volume, no matter what scene you’re in.
I don’t know if this’ll help the op. But I hope someone might find this useful.
I was facing the same issue with Player Prefs. I had added Player Prefs code to my Audio Mixer and my Slider, everything was perfectly organized and ready to be executed. However, when I started my game the Player Prefs wouldn’t be set, it would just be the default options. But the moment I went to my Menu and opened up Settings it immediately set the Player Prefs, which meant my code was working but only when Settings was opened. I finally realized that the code did not start executing until I activated my Settings Menu (I had it off in the hierarchy).
TL;DR
Maybe your Scriptable Game Object in the Hierarchy is turned off. That might be the reason why your Player Prefs aren’t being set by the script. So, try to call/set the Player Prefs through another active Game Object.