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

Unity中无需依赖GameObject调用CommonUtils工具函数的方法咨询

Unity中无需挂载GameObject调用工具类方法的方案

完全不需要创建空GameObject挂载脚本,有两种常用方案可以直接调用工具函数:

1. 静态类+静态方法(推荐)

把CommonUtils改成静态类,内部工具函数也声明为静态方法,这样在任何C#文件里都能直接调用,完全脱离GameObject依赖。

示例代码:

// CommonUtils.cs
public static class CommonUtils
{
    // 静态工具方法:整数相加
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }

    // 静态工具方法:格式化日志
    public static string FormatLog(string content)
    {
        return $"[{DateTime.Now:HH:mm:ss}] {content}";
    }
}

调用方式(其他脚本中):

int sum = CommonUtils.Add(5, 3);
string log = CommonUtils.FormatLog("操作完成");

2. 单例模式(适用于依赖MonoBehaviour功能的场景)

如果你的工具函数需要用到Unity的MonoBehaviour特性(比如协程、Update回调、组件访问),可以用单例模式,类内部会自动创建承载的GameObject,无需手动操作。

示例代码:

// CommonUtils.cs
public class CommonUtils : MonoBehaviour
{
    public static CommonUtils Instance { get; private set; }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject); // 跨场景保留
        }
        else
        {
            Destroy(gameObject); // 避免重复实例
        }
    }

    // 非静态工具方法:计算两点距离
    public float GetDistance(Vector3 pointA, Vector3 pointB)
    {
        return Vector3.Distance(pointA, pointB);
    }

    // 协程工具方法
    public IEnumerator DelayAction(float delay, Action action)
    {
        yield return new WaitForSeconds(delay);
        action?.Invoke();
    }
}

调用方式(其他脚本中):

float distance = CommonUtils.Instance.GetDistance(transform.position, target.transform.position);
StartCoroutine(CommonUtils.Instance.DelayAction(2f, () => Debug.Log("延迟执行")));

注意

  • 优先选择静态类方案,更轻量且无额外开销;
  • 单例模式仅在工具类必须依赖MonoBehaviour特性时使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:42:45