为了使文本显示功能更加模块化和可重用,我们可以将其封装成一个独立的C#类,这样其他脚本可以方便地调用它来显示文本。下面是如何封装这个功能并使其易于从其他脚本中调用的步骤:
步骤 1: 创建一个新的C#脚本
在Unity的Project视图中,右击并选择 Create -> C# Script。
命名这个脚本为 TextDisplayer。
步骤 2: 编辑TextDisplayer脚本
打开TextDisplayer脚本,并替换其中的代码为以下内容:
using UnityEngine;
public class TextDisplayer : MonoBehaviour
{
private static TextDisplayer instance;
public static TextDisplayer Instance
{
get
{
if (instance == null)
{
// 创建一个新的GameObject来附加TextDisplayer脚本
GameObject go = new GameObject("TextDisplayer");
instance = go.AddComponent<TextDisplayer>();
}
return instance;
}
}
public string message = "Hello, Unity!";
public int fontSize = 24;
public Color fontColor = Color.white;
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject); // 使对象在加载新场景时不被自动销毁
}
else
{
Destroy(gameObject); // 确保只有一个实例存在
}
}
void OnGUI()
{
GUIStyle guiStyle = new GUIStyle();
guiStyle.fontSize = fontSize;
guiStyle.normal.textColor = fontColor;
Vector2 size = guiStyle.CalcSize(new GUIContent(message));
Rect rect = new Rect((Screen.width - size.x) / 2, (Screen.height - size.y) / 2, size.x, size.y);
GUI.Label(rect, message, guiStyle);
}
public void DisplayMessage(string msg, int size, Color color)
{
message = msg;
fontSize = size;
fontColor = color;
}
}
步骤 3: 从其他脚本调用TextDisplayer
现在你可以从任何其他脚本调用TextDisplayer来显示文本。以下是如何使用这个封装好的类的示例:
using UnityEngine;
public class ExampleUsage : MonoBehaviour
{
void Start()
{
// 显示自定义消息
TextDisplayer.Instance.DisplayMessage("Welcome to the Game!", 30, Color.green);
}
}
步骤 4: 测试功能
确保TextDisplayer脚本已经存在于一个GameObject上,或者由于它的自我实例化特性,它会自动创建所需的GameObject。
将ExampleUsage脚本附加到任何活动的GameObject上。
运行游戏并查看输出。
通过这种方式,你可以轻松地在任何地方通过调用TextDisplayer.Instance.DisplayMessage()方法来显示文本,这使得代码更加整洁和模块化。