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

为何UI文本始终不为空?Unity触摸交互文本显示异常排查

问题根源

你的CreateText方法每次调用都会新建一个Canvas和Text对象。当双指触摸时,你创建了带文本的UI元素;切换到单指时,虽然新创建的Text是空的,但之前双指时生成的带文本的Canvas/Text并没有被销毁,它们会一直叠加显示在屏幕上,所以你看到文本始终不为空。而且Update方法每帧都会执行这个逻辑,短时间内会生成大量冗余的UI对象,还会造成内存泄漏。

解决方案:复用已有UI对象

不要每次调用都新建Canvas和Text,而是初始化一次,之后只修改文本内容。

修改步骤

  1. 在类中添加成员变量,保存Canvas和Text的引用:
private Text _uiText;
private Canvas _canvas;
  1. 重构CreateText方法,只在首次调用时创建UI对象,后续直接修改文本:
private void CreateText(bool create)
{
    // 首次调用时创建Canvas和Text并初始化固定属性
    if (_canvas == null)
    {
        // 创建Canvas
        GameObject canvasGO = new GameObject("Canvas");
        _canvas = canvasGO.AddComponent<Canvas>();
        canvasGO.AddComponent<CanvasScaler>();
        canvasGO.AddComponent<GraphicRaycaster>();
        _canvas.renderMode = RenderMode.ScreenSpaceOverlay;

        // 创建Text对象
        GameObject textGO = new GameObject("UIText");
        textGO.transform.parent = canvasGO.transform;
        _uiText = textGO.AddComponent<Text>();

        // 设置Text的固定样式(无需重复修改)
        Font arial = (Font)Resources.GetBuiltinResource(typeof(Font), "LegacyRuntime.ttf");
        _uiText.font = arial;
        _uiText.fontSize = 48;
        _uiText.alignment = TextAnchor.MiddleCenter;

        RectTransform rectTransform = _uiText.GetComponent<RectTransform>();
        rectTransform.localPosition = Vector3.zero;
        rectTransform.sizeDelta = new Vector2(600, 200);
    }

    // 根据参数修改文本内容
    _uiText.text = create ? "Press space key" : "";
}

额外优化

原代码中Update每帧都会调用CreateText,即使触摸状态没有变化也会执行。可以添加状态判断,只在触摸状态改变时才调用方法,减少不必要的执行:

private int _lastTouchCount = -1;

private void Update()
{
    // 其他触摸逻辑...

    // 仅当触摸数量变化时才更新文本
    if (Input.touchCount != _lastTouchCount)
    {
        CreateText(Input.touchCount == 2);
        _lastTouchCount = Input.touchCount;
    }

    // 移动逻辑...
}

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:15:30