【问题标题】:Unity image.enabled=false does not workunity image.enabled=false 不起作用
【发布时间】:2018-03-24 03:20:32
【问题描述】:

我尝试将启用设置为 true 和 SetActive(true) 来显示游戏结束图像。但是,它们都不起作用。我声明了一个公共图像 gameOverImage 并将 Start() 中的 gameOverImage.enabled 设置为 false。

private void Start()
{
     gameOverImage.enabled = false;
}

然后在我的一个函数中,我输入:

public void killAt(Vector2 loc)
{
    foreach (GameObject obj in setup.GetActive())
    {
        if (obj.GetComponent<PieceInfo>().GetLocation() == loc)
        {
            if (obj.GetComponent<PieceInfo>().GetPieceType() == 'G')
            {
                gameOver = true;
                gameOverImage.enabled = true;
                Debug.Log("?????");
            }
            setup.deactivate(obj);
            break;
        }
    }
}

控制台确实有?????已登录,但游戏视图中未显示 gameOverImage。游戏结束了,因为我不能再点击我的游戏了。有任何想法吗?我还尝试了 UI 文本。也不行。

【问题讨论】:

  • 您希望图像刚刚出现,还是您的场景中有此图像的实际 UI 图像?
  • @Eddge 是的,我只想在游戏结束时显示一个游戏结束图像。我在场景中没有 UI 图像。它在我的预制文件夹中。我已将它附加到脚本中。
  • 如果场景中不存在您无法激活它的 GameObject,它将无法正常工作。因此,如果您有一个预制件,上面有图像,您需要实例化该对象。
  • @Eddge 但是如果我把它放到场景中,它会挡住我的游戏视图。取消选中检查器下方的框可以使其消失,但当我使用启用或 setactive 时它不会显示。我该如何解决?
  • 看看我的回答。

标签: c# unity3d


【解决方案1】:

在 Unity 中,为了激活一个对象,您需要在场景中拥有它。如果场景中不存在游戏对象,或者在您的情况下包含图像的 UI 元素不在您的场景中,SetActive(true) or Enabled = true 将不会有任何效果。您将需要instantiate 对象。让它存在于你的世界中。

预制件,用于存储可以在游戏中多次使用但它们不存在于场景中的通用配置,这就是你必须实例化它们的原因。

对于您的 GameOver Image,您有几个选项,最简单的是:

using UnityEngine;
using UnityEngine.UI;
public class EnableUI : MonoBehaviour {
    public Image GameOverImage;
    // Use this for initialization
    void Start () {
        GameOverImage.gameObject.SetActive(false);
    }

    // Update is called once per frame
    void Update () {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            GameOverImage.gameObject.SetActive(true);
        }
    }
}

如果你想实例化它:

using UnityEngine;
public class EnableUI : MonoBehaviour {
    // This is a prefab that is canvas with your game over image nested as a child image UI under it
    public GameObject GameOverObject;
    // Use this for initialization
    void Start () { }

    // Update is called once per frame
    void Update () {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(GameOverObject);
        }
    }
}

【讨论】:

  • 我已将它拖到我的场景中。它仍然没有以您提供的任何一种方式显示。
  • @SeakyLone 您是否将脚本上的引用更新为您拖入场景的引用,而不是预制文件夹中的引用?
猜你喜欢
  • 2013-09-20
  • 2017-01-02
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多