我怎样在游戏对象中添加图像和文本?

我进行了以下操作:
1. 在主摄像机上添加了一个画布。
2. 在画布上添加了一个UI图片,将其命名为“BackgroundImage”,将其颜色设置为红色,并将其fill mode设置为“stretch / stretch”。
3. 在画布上添加了另一个UI图片,将其命名为“ButtonBackground”,并选择“Source Image”为“Builtin/extras/InputFieldBackground”。
4. 我向画布添加了一个名为“VirtualKeyboard”的脚本。此脚本具有一个名为“ButtonBack”的属性,我将UI图片“ButtonBackground”拖入槽中。
接下来,我运行了我的脚本:

using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class VirtualKeyboard : MonoBehaviour
{
      public Sprite ButtonBack;

    void Start()
    {
        Canvas canvas = GetComponent<Canvas>();

        string sName = "name1";

        GameObject key = new GameObject(sName);

        RectTransform keyRectTransform = key.AddComponent<RectTransform>();
        keyRectTransform.SetParent(canvas.transform);
        keyRectTransform.anchoredPosition = new Vector2(100,100);
        keyRectTransform.sizeDelta = new Vector2(200, 200);

        // Add Image component to the key
        Image image = key.GetComponent<Image>();
        if (image == null)
        {
            image = key.AddComponent<Image>();
        }
        image.sprite = ButtonBack;
        image.type = Image.Type.Sliced;

        // Add a Text component to the key and set its text to the current key string
        Text text = key.GetComponent<Text>();
        if (text == null)
        {
            text = key.AddComponent<Text>();
        }
        text.text = "test";
    }
}

为什么“Text”为null?
控制台显示:Can’t add Text to name1 because a Image is already added to the game object! A GameObject can only contain one Graphic component. UnityEngine.GameObject:AddComponent<UnityEngine.UI.Text> () VirtualKeyboard:Start () (at Assets/VirtualKeyboard.cs:37)
请教大家这个问题如何解决。

共以下 1 个回答

  • arlboro 2023年4月3日 上午10:10


    显示的错误信息会告诉你具体出了什么问题。

    每个游戏物体只能包含一个 Graphic 组件。Image 和 Text 组件都继承自 Graphic,因此单个游戏物体只能绘制其中的一个。

    在 Unity 编辑器中,使用 GameObject 菜单(GameObject -> Create -> UI -> Button)创建一个新的 UI 按钮。这样你就可以看到它们是如何解决这个问题的。按钮物体包含了 Image 组件,并且它有一个子对象来包含 Text 组件。


    0 赞同 0 条回复

# 回答此问题

您的电子邮箱地址不会被公开。 必填项已用*标注