Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Player prefs only load when entering options menu

Discussion in '2D' started by Blejz43, Apr 11, 2021.

  1. Blejz43

    Blejz43

    Joined:
    Mar 4, 2020
    Posts:
    8
    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 ) :
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Audio;
    5. using UnityEngine.UI;
    6.  
    7.  
    8. public class audiomute : MonoBehaviour
    9. {
    10.  
    11.     public Slider slider01;
    12.     public Slider slider02;
    13.    
    14.     void Awake()
    15.     {
    16.         slider01.value = PlayerPrefs.GetFloat("save");
    17.         slider02.value = PlayerPrefs.GetFloat("save2");
    18.     }
    19.  
    20.     public void slider2(float audio2)
    21.     {
    22.         bgaudio.Instance.gameObject.GetComponent<AudioSource>().volume = audio2;
    23.  
    24.         PlayerPrefs.SetFloat("save", audio2);
    25.     }
    26.  
    27.     public void slider1(float audio)
    28.     {
    29.         AudioListener.volume = audio;
    30.  
    31.         PlayerPrefs.SetFloat("save2", audio);
    32.     }
     
  2. Magnesium

    Magnesium

    Joined:
    Sep 14, 2014
    Posts:
    178
    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.
     
  3. japhib

    japhib

    Joined:
    May 26, 2017
    Posts:
    65
    > 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.