Author Topic: UIToggle = null???? (Solved)  (Read 2867 times)

Mr_Love_Gloves

  • Newbie
  • *
  • Thank You
  • -Given: 1
  • -Receive: 0
  • Posts: 6
    • View Profile
UIToggle = null???? (Solved)
« on: July 10, 2014, 07:01:17 AM »
With my code I am trying to have a toggle button that mutes and plays sound, it works when it first loads up, but when I carry on through the game and end back at this start screen Toggle is = Null and the toggle does not mute the audio or work. I have no idea why its = null the second time round. Any help would be great  :D

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SoundButtionGUI : MonoBehaviour {
  5.        
  6.  
  7.         public UIToggle toggle;
  8.        
  9.  
  10.         void Awake () {
  11.                 if (PlayerPrefs.GetInt ("SoundMute") == 1) {
  12.                         toggle.value = true;
  13.                 } else {
  14.                         toggle.value = false;
  15.                 }      
  16.  
  17.         }
  18.  
  19.         void Update () {       
  20.                 if (Application.loadedLevel == 0) {
  21.                         if(toggle == null){
  22.                                 Debug.Log ("Toggle = Null");
  23.                         }
  24.  
  25.                                 if(toggle.value == true && toggle != null){
  26.                                 PlayerPrefs.SetInt("SoundMute", 1);
  27.                                 Invoke("audioOff", 0.01f);
  28.                         } else{
  29.                                 Invoke("audioOn", 0.01f);
  30.                                 PlayerPrefs.SetInt("SoundMute", 0);
  31.                         }
  32.                 }
  33.         }
  34.  
  35.         void audioOn(){
  36.                 audio.volume = 1;
  37.         }
  38.        
  39.         void audioOff(){
  40.                 audio.volume = 0;
  41.         }
  42. }
  43.  
« Last Edit: July 11, 2014, 05:46:43 AM by Mr_Love_Gloves »

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UIToggle = null???? (Aren Mook please help)
« Reply #1 on: July 10, 2014, 09:08:07 PM »
Never do anything in Awake() that involves other components.

Awake() is only for local value initialization. Rename it to Start().

Mr_Love_Gloves

  • Newbie
  • *
  • Thank You
  • -Given: 1
  • -Receive: 0
  • Posts: 6
    • View Profile
Re: UIToggle = null???? (Aren Mook please help)
« Reply #2 on: July 11, 2014, 05:45:41 AM »
Thank you that advice will help me, turns out the problem was every time the scene reloaded the toggle component disapeared from the variable so i just moved the script to the actual toggle and now everything works :D