Unity设置界面切换闪烁问题求助(附代码)
问题解决:UI界面切换闪烁
问题描述
制作切换设置界面与主UI界面的按钮时,严格按教程操作,但点击设置按钮后界面出现快速闪烁现象。已确认游戏对象添加正确,OnClick事件绑定的函数无误,相关代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShowSettings : MonoBehaviour { //Menu States public enum MenuStates {Reg, Settings}; public MenuStates currentState; public GameObject regScreen; public GameObject settingsScreen; //When script first starts void Awake() { currentState = MenuStates.Reg; } void Update() { //Checks Current State switch(currentState) { case MenuStates.Reg: //Set Active Game Objects for regular Screen regScreen.SetActive(true); settingsScreen.SetActive(false); break; case MenuStates.Settings: //Set Active game objects for Settings Screen regScreen.SetActive(false); settingsScreen.SetActive(true); break; } } public void OnSettings() { currentState = MenuStates.Settings; } public void OnReg() { currentState = MenuStates.Reg; } }
问题原因
- 多脚本实例冲突:大概率是将
ShowSettings脚本同时挂载在了regScreen和settingsScreen两个游戏对象上,导致两个脚本实例在Update方法中互相覆盖状态设置,引发界面快速切换闪烁。 - 冗余的帧更新操作:原代码在
Update中每帧重复执行界面激活/禁用操作,虽然本身不会直接导致闪烁,但可能与其他UI逻辑产生冲突,且属于不必要的性能浪费。
修复方案
步骤1:检查脚本挂载对象
确保ShowSettings脚本仅挂载在一个独立的空游戏对象上(比如命名为"MenuManager"),不要挂载在regScreen或settingsScreen这两个界面对象上——当界面被禁用时,挂载在其上的脚本逻辑会被中断,进而引发状态异常。
步骤2:优化状态切换逻辑
将界面更新逻辑从Update中移出,仅在状态变更时执行一次,避免冗余操作:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShowSettings : MonoBehaviour { //Menu States public enum MenuStates {Reg, Settings}; public MenuStates currentState; public GameObject regScreen; public GameObject settingsScreen; void Awake() { currentState = MenuStates.Reg; UpdateMenuUI(); //初始化界面状态 } // 仅在状态变更时调用,更新UI显示 void UpdateMenuUI() { switch(currentState) { case MenuStates.Reg: regScreen.SetActive(true); settingsScreen.SetActive(false); break; case MenuStates.Settings: regScreen.SetActive(false); settingsScreen.SetActive(true); break; } } public void OnSettings() { currentState = MenuStates.Settings; UpdateMenuUI(); } public void OnReg() { currentState = MenuStates.Reg; UpdateMenuUI(); } }
步骤3:验证按钮绑定
再次确认设置按钮的OnClick事件仅绑定了MenuManager对象上ShowSettings脚本的OnSettings方法;返回按钮仅绑定OnReg方法,无重复绑定或错误绑定。
内容的提问来源于stack exchange,提问作者Will P
相关产品推荐
相关产品推荐

