You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity技术问询:如何在指定按钮激活时启用readyToRun按钮?

Solution: Enable readyToRun Button Only When Button1 is Active

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.UI to 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 the enabled state of readyToRun to match Button1's state. This is a cleaner, more concise alternative to wrapping it in an if statement (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:29:24