- Home /
Toggle switch off causing stack overflow
I can't figure out whats wrong here so I could really use some assistance. I have a toggle switch that mutes and unmutes the game. Its setting is pulled through player prefs and when the switch setting is off it causes a stack overflow when loading the menu. It does not cause a stack overflow if the switch setting is on.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MuteManager : MonoBehaviour
{
private bool isMuted;
public Toggle soundToggle;
private bool isToggled;
// Start is called before the first frame update
void Start()
{
isMuted = PlayerPrefs.GetInt("MUTED") == 1;
isToggled = PlayerPrefs.GetInt("TOGGLED") == 1;
AudioListener.pause = isMuted;
soundToggle.isOn = isToggled;
}
public void MutePressed()
{
isMuted = !isMuted;
isToggled = !isToggled;
AudioListener.pause = isMuted;
soundToggle.isOn = isToggled;
PlayerPrefs.SetInt("MUTED", isMuted ? 1 : 0);
PlayerPrefs.SetInt("TOGGLED", isToggled ? 1 : 0);
}
}
Answer by andrew-lukasik · Jun 22, 2021 at 07:46 AM
Replace:
soundToggle.isOn = isToggled;
with:
soundToggle.SetIsOnWithoutNotify( isToggled );
Thank you very much that worked, is there a reason to use the isOn by itself or does it generally cause a stack overflow like that? SetIsOnWithoutNotify seems much better
Stack overflow
is caused by infinite loop that was created here:
soundToggle
's event callsMutePressed()
MutePressed()
callssoundToggle.isOn
soundToggle.isOn
callsMutePressed()
MutePressed()
callssoundToggle.isOn
soundToggle.isOn
callsMutePressed()
MutePressed()
callssoundToggle.isOn
... ad infinitum
Your answer
Follow this Question
Related Questions
Vector2.MoveTowards problem 0 Answers
using raycast to detect collision for 2D arkanoid/breakout game 0 Answers
Hololens won't connect to server over UNet 0 Answers
Unexpected Strange Behavior 0 Answers