Unity 中的 GameObject 在 Unity C# 中被 SetActive(false) 设置为 false 后不会重新出现

问题描述 投票:0回答:2

我试图创建一个在按下 P 时出现和消失的画布。我使用 setActive(bool) 方法。 但是当我将对象隐藏在 void start() 中时,它不会通过 setActive() 重新出现。如果我不在 void start() 中隐藏对象,一切都会以某种方式正常运行。 如何让画布在开始时隐藏并在按下 P 时显示?`

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameOverScreen : MonoBehaviour
{
    public GameObject[] pauseObjects;
    public static bool isPaused = false;



    void Start()
    {
         Time.timeScale = 1;
        pauseObjects = GameObject.FindGameObjectsWithTag("game-over");
        hidePaused();
       
        

    }

    // Update is called once per frame
    void Update()
    {
       

        //uses the p button to pause and unpause the game
        if (Input.GetKeyDown(KeyCode.P))
            
        {
            
            if (Time.timeScale == 1)
            { 
                Time.timeScale = 0;
                showPaused();
                isPaused = !isPaused;
               
                Debug.Log("d");
               
            }
            else if (Time.timeScale == 0)
            { 
                Time.timeScale = 1;
                hidePaused();
                isPaused = !isPaused;
                
                 Debug.Log("high");
            }
        }
    }
    public void showPaused()
    {
       
        Debug.Log("Succesfull");
        foreach (GameObject g in pauseObjects)
        {
            g.SetActive(true); 
            g.name = "ray";
        }
        isPaused = true;
       
        

    }

    //hides objects with ShowOnPause tag
    public void hidePaused()
    {
        
        foreach (GameObject g in pauseObjects)
        {
            g.SetActive(false);
           
        }
       
       
       
    }

上面已经提到了

c# game-engine unityscript
2个回答
0
投票

自从我使用 unity 以来已经有一段时间了,如果停用脚本附加到的对象,则不能从脚本中调用任何代码,因为它也会停用附加到对象的每个组件。

https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html

您可以将脚本附加到父对象并将画布添加为子对象。通过这样做,您可以在画布上调用 SetActive 而不会影响父对象。 Transform.GetChild() 是将对象附加到父对象的一种方法。

https://docs.unity3d.com/ScriptReference/Transform.GetChild.html


0
投票

对于这种情况,这是一个非常简单的解决方案:您可以只创建一个游戏对象的公共列表(在检查器中将它们添加到列表中),然后手动停用对象(只需一次选择它们并在检查器中停用) .

然后当你运行游戏时:

  1. 它们都将被停用 - 如您所愿。
  2. 你有他们的参考,因为你已经在检查员中分配了,所以你可以重新激活。
  3. 您不必使用 FindGameObjects 方法(如果您经常使用它可能会非常费力)。

只需将

public GameObject[] pauseObjects;
更改为
public List<GameObject> pauseObjects = new List<GameObject>();

© www.soinside.com 2019 - 2024. All rights reserved.