【问题标题】:Can't see UI elements on the scene (Unity)在场景中看不到 UI 元素(Unity)
【发布时间】:2021-05-05 01:43:07
【问题描述】:

我正在制作一个培训项目(Arkanoid)。当奖励块被破坏时,桨会暂时消耗,并且时间条会说明此效果。 问题是 TimeBar 对象在奖励时间到期后被实例化并销毁,但我看不到时间栏和场景中的文字。

所以我创建了LinearTimer 预制件,它由 UI 图像(白条)和 UI 文本(“Bonus Text”)组成:

Prefab screenshot

有一个脚本可以以适当的方式为时间栏设置动画。调试消息正确显示在控制台中:

    public class TimeBar : MonoBehaviour
    {
        public float maxTime = 15f;
        float timeLeft;
        Image timerBar;
    
        void Start()
        {
            timerBar = GetComponent<Image>();
            timeLeft = maxTime;
            Debug.Log("BONUS START");
        }
    
        void Update()
        {
            if (timeLeft > 0)
            {
                timeLeft -= Time.deltaTime;
                timerBar.fillAmount = timeLeft / maxTime;
            }
            else
            {
                Debug.Log("BONUS END");
                Destroy(gameObject);
            }
        }
    }

场景中最初没有 TimeBar 对象。 TimeBar 对象将在 Paddle 类的 Expand() 方法中实例化:

    public class Paddle : MonoBehaviour
    {
        [SerializeField] TimeBar timeBar;
        
        void Start()
        {
        }
    
        public void Expand()
        {
            Instantiate(timeBar, transform.position, Quaternion.identity, transform.Find("Game Canvas"));
    
            Vector3 newScale = new Vector3(1.5f, 1, 1);
            transform.localScale = newScale;
            
            StartCoroutine("ExpandTime");
        }
        
        private IEnumerator ExpandTime()
        {
            yield return new WaitForSeconds(15f);
            Vector3 newScale = new Vector3(1, 1, 1);
            transform.localScale = newScale;
        }
    }

即使我手动将 LinearTimer 实例添加到场景中,我也无法在场景中看到它:

LinearTimer added to the scene

资产设置可能有问题?

Prefab asset Inspector 1Prefab asset Inspector 2

P.S.:UI 是在 Layers 中打开的。

【问题讨论】:

  • 您的 UI 内容是 Canvas 的子项吗?否则它不会被渲染...在您的设置中似乎是这种情况...确保您将这些 UI 项目实例化为 Canvas 的子项 .. 或者如果需要,您还可以为每个预制件设置一个画布 ..
  • 这就是我试图通过调用Instantiate()Expand() 方法中做的事情。我的代码是Instantiate(timeBar, transform.position, Quaternion.identity, transform.Find("Game Canvas"));。如何修复它,使实例化对象成为 Game Canvas 的子对象?

标签: unity3d


【解决方案1】:

您看不到 LinearTimer 对象,因为该对象是一个 UI 元素。

UI 元素总是在画布中呈现

只需将您的 LinearTimer 对象拖到 Game Canvas 对象中即可。

编辑:您应该使用 GameObject.Find("Game Canvas").transform 而不是 transform.Find("Game Canvas")

【讨论】:

  • 这就是我试图通过调用Instantiate()Expand() 方法中做的事情。我的代码是Instantiate(timeBar, transform.position, Quaternion.identity, transform.Find("Game Canvas"));。如何修复它,使实例化对象成为 Game Canvas 的子对象?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多