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

Unity中第二次调用SetActive(true)失效问题求助

问题分析与解决

你的问题核心原因是:如果这个脚本直接挂载在theBall物体上,当调用theBall.SetActive(false)时,整个物体(包括上面的脚本)都会被禁用,协程会直接中断,导致后续的SetActive(true)代码根本不会执行。

解决步骤

  • 把ScriptTwo脚本挂载到一个始终处于激活状态的物体上(比如新建一个空物体命名为GameController),确保即使theBall被隐藏,脚本所在的物体依然正常运行。
  • 在Inspector面板中把theBall拖拽赋值给脚本的theBall变量。

验证代码(逻辑不变,仅调整挂载位置)

using System.Collections;
using UnityEngine;

public class ScriptTwo : MonoBehaviour
{
    public GameObject theBall;

    void Start()
    {
        theBall.SetActive(true);
        StartCoroutine(BallCode());
    }

    IEnumerator BallCode() 
    {
        yield return new WaitForSeconds(3);
        theBall.SetActive(false);
        Debug.Log("Set Active: False");
        Debug.Log("Test Before");
        yield return new WaitForSeconds(3);
        theBall.SetActive(true);
        Debug.Log("Set Active: True"); // 新增日志,验证代码是否执行
    }
}

额外排查点

如果调整挂载位置后仍失效,检查以下内容:

  • 确认theBall变量在Inspector中已正确赋值,无空引用(空引用会在Console面板报错)。
  • 排查是否有其他脚本修改theBall的激活状态,导致逻辑冲突。
  • 确认协程未被其他代码意外终止。

内容的提问来源于stack exchange,提问作者Andrew Markarian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:36