Unity技术问询:如何在指定按钮激活时启用readyToRun按钮?
Hey there, to make your readyToRun button only become enabled when Button1 is active, here's a simple Unity C# implementation that does exactly that:
using UnityEngine; using System.Collections; using UnityEngine.UI; // Required when working with UI elements. public class GratzScript : MonoBehaviour { public Button Button1; public Button readyToRun; public void Update() { // Sync readyToRun's enabled state to match Button1's readyToRun.enabled = Button1.enabled; } }
Breakdown of the Code:
- We import
UnityEngine.UIto access the UI Button component (mandatory when working with Unity's UI system). - Two public Button references are declared so you can drag-and-drop the respective buttons from your scene directly into the Inspector.
- In the
Update()method, we directly sync theenabledstate ofreadyToRunto matchButton1's state. This is a cleaner, more concise alternative to wrapping it in anifstatement (both approaches work, but this cuts down on unnecessary code).
Pro Tip for Better Performance
Checking state every frame in Update() works perfectly fine for most small-scale projects, but if you want a more efficient approach (avoiding redundant frame checks), you can listen for when Button1's enabled state changes instead:
using UnityEngine; using UnityEngine.UI; public class GratzScript : MonoBehaviour { public Button Button1; public Button readyToRun; private void OnEnable() { // Subscribe to Button1's enable/disable events to trigger state changes Button1.onEnable.AddListener(() => readyToRun.enabled = true); Button1.onDisable.AddListener(() => readyToRun.enabled = false); // Set the initial state when the script first activates readyToRun.enabled = Button1.enabled; } private void OnDisable() { // Unsubscribe from events to prevent memory leaks Button1.onEnable.RemoveListener(() => readyToRun.enabled = true); Button1.onDisable.RemoveListener(() => readyToRun.enabled = false); } }
This approach only updates readyToRun's state when Button1 actually changes its enabled status, which is more efficient than checking every frame.
内容的提问来源于stack exchange,提问作者Sandro Kikvidze
相关产品推荐
相关产品推荐

