Unity 右键菜单创建 Text 组件:代码实现
当在 Unity 中右键菜单中选择'UI/Text'时,实际上 Unity 会在场景中创建一个新的 Text 组件。
以下是用代码实现这个过程的示例:
using UnityEngine;
using UnityEngine.UI;
public class CreateTextComponent : MonoBehaviour
{
[MenuItem("GameObject/UI/Text")]
static void CreateText()
{
// 创建一个新的 GameObject,并将其命名为'Text'
GameObject textGO = new GameObject('Text');
// 将 GameObject 添加到场景中
GameObjectUtility.SetParentAndAlign(textGO, Selection.activeGameObject);
// 添加 Text 组件到 GameObject 上
Text textComponent = textGO.AddComponent<Text>();
// 设置 Text 组件的属性
textComponent.text = 'New Text';
textComponent.font = Resources.GetBuiltinResource<Font>('Arial.ttf');
textComponent.fontSize = 24;
textComponent.alignment = TextAnchor.MiddleCenter;
}
}
要运行这个代码,需要将其放在项目的 Editor 文件夹中,并确保项目中包含了 Unity 引擎的命名空间 'UnityEditor' 和 'UnityEngine.UI'。
原文地址: https://www.cveoy.top/t/topic/o010 著作权归作者所有。请勿转载和采集!