✅ 一、核心定位与核心优势

1. 核心定位

Unity.Mathematics 是 Unity 官方出品的高性能、SIMD 优化、值类型优先的数学库,专为 DOTS 生态(ECS、Job System、Burst 编译器)深度定制,也可以无缝用于常规 MonoBehaviour 开发中。

2. 核心优势(对比Unity内置Vector3/Quaternion

极致性能:底层基于 SIMD (单指令多数据) 指令集优化,支持CPU并行计算,相同运算速度远超原生结构体
Burst 编译器完美兼容:Burst 编译能对其做极致IL优化/机器码优化,性能再提升数倍(原生Vector3在Burst中无法最优编译)
值类型纯净设计:无任何GC分配、无虚函数、无堆内存依赖,内存占用更小,缓存命中率更高
功能更完整:包含原生库没有的数学功能(复数、随机数、完整的矩阵运算、几何工具等)
语法统一:所有数学类型API设计风格一致,学习成本低,跨平台兼容性拉满


✅ 二、核心命名空间 & 基础引用

1. 核心命名空间

使用该库必须引入2个核心命名空间(缺一不可),所有核心类型都在这两个命名空间下:

using Unity.Mathematics; // 核心数学类型:float3、quaternion、float4x4 等
using Unity.Collections;  // 配套的高性能容器(可选,DOTS开发必用)

2. 安装说明

Unity 2019.3+ 版本 内置自带 Unity.Mathematics 库,无需手动安装Package,直接引用命名空间即可使用;
低版本Unity需在 Package Manager 中搜索 Mathematics 安装对应包。


✅ 三、核心结构体(原生类型的完美替代,重点必学)

Unity.Mathematics 的核心设计:用统一的命名规范 + 更高效的实现,替代所有Unity原生数学类型,所有类型都是值类型 struct,核心对应关系如下(工作中99%的场景只需要用这些):

Unity.Mathematics 类型 对应 Unity 原生类型 用途说明 核心优势
float2 Vector2 2维向量/坐标 运算快、无GC、支持SIMD
float3 Vector3 3维向量/坐标/方向(最常用) 性能提升最明显,Burst下碾压原生Vector3
float4 Vector4 4维向量/颜色(RGBA) 可直接与矩阵做乘法运算
quaternion Quaternion 四元数(旋转表示) 运算效率更高,插值更稳定
float4x4 Matrix4x4 4x4矩阵(坐标变换/投影) 内置完整的矩阵运算API,无冗余逻辑
int2/int3/int4 Vector2Int/3Int 2/3/4维整数坐标 纯整型运算,无浮点精度损耗

✅ 核心注意:命名规范

Unity.Mathematics 遵循 「类型+维度」 的命名规则,一眼看懂含义:

  • 浮点型:float2(2维)、float3(3维)、float4(4维)
  • 整型:int2int3int4
  • 布尔型:bool2bool3bool4(批量布尔判断)

✅ 四、基础语法 & 常用API(与原生类型无缝切换)

✔ 1. 变量声明(与原生一致,写法几乎无差别)

// 声明赋值
float3 pos = new float3(1, 2, 3);    // 等价 Vector3(1,2,3)
float2 uv = new float2(0.5f, 0.5f);  // 等价 Vector2(0.5f,0.5f)
quaternion rot = quaternion.identity;// 等价 Quaternion.identity(无旋转)
float4x4 matrix = float4x4.identity; // 等价 Matrix4x4.identity(单位矩阵)

// 快捷赋值:分量访问和原生一致,x/y/z/w 通用
pos.x = 5;
pos.y += 2;
float height = pos.y;

✔ 2. 核心常量(和原生一致,直接调用)

float3 up = math.up;        // 等价 Vector3.up → (0,1,0)
float3 right = math.right;  // 等价 Vector3.right → (1,0,0)
float3 forward = math.forward;//等价 Vector3.forward → (0,0,1)
float PI = math.PI;         // 高精度圆周率 π
float infinity = math.INFINITY; // 无穷大

✔ 3. 关键:类型互转(原生 ↔ Mathematics,零成本转换)

最常用的需求:原生Vector3float3互相转换,提供2种无缝转换方式,无性能损耗,完全兼容旧代码:

// 方式1:强制类型转换(推荐,简洁高效)
Vector3 unityVec = new Vector3(1,2,3);
float3 mathVec = (float3)unityVec; // 原生 → Mathematics

Vector3 newUnityVec = (Vector3)mathVec; // Mathematics → 原生

// 方式2:显式构造(兼容所有场景)
float3 mathVec2 = new float3(unityVec.x, unityVec.y, unityVec.z);

✅ 补充:quaternionQuaternionfloat4Vector4 均支持上述强制转换方式


✅ 五、核心核心:math 静态工具类(重中之重)

✔ 核心规则

Unity.Mathematics所有的数学运算、向量/四元数/矩阵的操作,都通过 math 静态类调用
✅ 这是和原生最大的区别:原生是 Vector3.Distance(a,b),数学库是 math.distance(a,b)
✅ 所有API都是静态方法,无GC、无虚调用,Burst编译后速度极快

✔ 高频必用 math 工具函数(按使用频率排序,全覆盖90%开发场景)

所有方法均支持 float2/float3/float4 等维度,参数传对应维度即可,API通用!

float3 a = new float3(1,0,0);
float3 b = new float3(0,1,0);

// 1. 向量基础运算
float length = math.length(a);        // 向量长度 → 等价 Vector3.magnitude
float lenSq = math.lengthsq(a);       // 向量长度平方(无开方,性能更高,推荐比较距离用)
float3 normalized = math.normalize(a); // 单位向量 → 等价 Vector3.normalized

// 2. 向量点积/叉积(向量运算核心)
float dot = math.dot(a, b);           // 点积 → 等价 Vector3.Dot(a,b)
float3 cross = math.cross(a, b);      // 叉积 → 等价 Vector3.Cross(a,b)

// 3. 距离计算
float dist = math.distance(a, b);     // 两点距离 → 等价 Vector3.Distance(a,b)
float distSq = math.distancesq(a, b); // 距离平方(性能优先,推荐)

// 4. 插值运算(平滑过渡核心)
float3 lerpVec = math.lerp(a, b, 0.5f); // 线性插值 → 等价 Vector3.Lerp(a,b,t)
quaternion lerpRot = math.lerp(rotA, rotB, 0.5f); // 四元数插值
quaternion slerpRot = math.slerp(rotA, rotB, 0.5f); // 球面插值(旋转平滑,无万向节死锁)

// 5. 旋转相关(四元数核心操作)
quaternion rotX = math.mul(rot, quaternion.EulerX(math.radians(30))); // 绕X轴转30度
quaternion rotY = quaternion.RotateY(math.radians(45)); // 绕Y轴旋转(更简洁)
float3 euler = math.eulerangles(rot); // 四元数转欧拉角(弧度值)

// 6. 数值处理(通用)
float clampVal = math.clamp(5.2f, 0, 5); // 数值限制在[0,5] → 等价 Mathf.Clamp
float roundVal = math.round(2.3f);       // 四舍五入
float floorVal = math.floor(2.9f);       // 向下取整
float ceilVal = math.ceil(2.1f);         // 向上取整
float absVal = math.abs(-3.5f);          // 绝对值

// 7. 弧度/角度转换(必记!math库中所有旋转都是【弧度制】)
float rad = math.radians(90);  // 角度 → 弧度 (90度 = π/2 弧度)
float deg = math.degrees(math.PI); // 弧度 → 角度 (π 弧度 = 180度)

⚠️ 重要提醒:Unity.Mathematics所有旋转相关的参数都是「弧度制」,Unity原生是「角度制」,这是最容易踩坑的点!必须用 math.radians(角度值) 转换后再使用。


✅ 六、为什么在 DOTS(ECS/Job/Burst) 中必须使用它?

这是重中之重,也是该库被设计的核心原因,3个强制理由,没有例外

❌ 原生 Vector3/Quaternion 在 DOTS 中的致命问题

  1. Burst 编译器不友好:Unity原生的 Vector3 内部有冗余的属性、方法和隐式转换,Burst 编译器无法对其做深度优化,甚至部分场景会直接禁用Burst优化,导致Job任务性能暴跌。
  2. 不支持 IJobParallelFor 等并行Job:原生结构体内部有托管堆引用(非纯值类型),在并行Job中使用会触发内存安全检查报错,直接无法运行。
  3. GC与内存损耗:原生类型的部分API会产生临时堆分配,在高频调用的Job中会累积GC,造成卡顿。

Unity.Mathematics 的完美适配

  1. 纯 blittable 值类型:所有结构体都是「 blittable 类型」(内存布局连续、无托管引用),完全兼容Unity的安全内存访问规则,可在任意Job(串行/并行)中无限制使用。
  2. Burst 深度优化:Burst编译器对 Unity.Mathematics 做了专属编译优化,能将数学运算直接编译为CPU的SIMD指令,运算速度是原生类型的 2~10倍
  3. 零GC:所有API都是静态方法+值类型,全程无堆内存分配,完美适配高性能的ECS/Job体系。

✅ 结论:只要写 DOTS 相关代码(ECS/Job/Burst),必须使用 Unity.Mathematics,禁止使用原生Vector3/Quaternion


✅ 七、完整实用代码示例(MonoBehaviour + DOTS 双场景)

示例1:常规 MonoBehaviour 开发(无缝替换原生类型,无学习成本)

using UnityEngine;
using Unity.Mathematics;

public class MathDemo : MonoBehaviour
{
    public Transform target;
    private float3 selfPos;
    private quaternion selfRot;

    void Update()
    {
        // 原生Vector3转float3
        selfPos = (float3)transform.position;
        float3 targetPos = (float3)target.position;

        // 计算方向向量并归一化
        float3 dir = math.normalize(targetPos - selfPos);
        // 计算目标旋转:看向目标
        selfRot = quaternion.LookRotation(dir, math.up);
        // 平滑旋转插值
        transform.rotation = (Quaternion)math.slerp((quaternion)transform.rotation, selfRot, Time.deltaTime * 5);

        // 计算距离(用平方距离,性能更高)
        if(math.distancesq(selfPos, targetPos) < 100)
        {
            Debug.Log("目标在10米范围内");
        }
    }
}

示例2:Burst Job 中使用(高性能,DOTS核心场景)

using UnityEngine;
using Unity.Mathematics;
using Unity.Jobs;
using Unity.Burst;
using Unity.Collections;

public class JobMathDemo : MonoBehaviour
{
    void Start()
    {
        // 创建高性能原生容器
        NativeArray<float3> positions = new NativeArray<float3>(1000, Allocator.TempJob);
        // 赋值初始坐标
        for (int i = 0; i < positions.Length; i++)
        {
            positions[i] = new float3(i, math.sin(i * 0.1f), 0);
        }

        // 创建Burst Job
        RotateJob rotateJob = new RotateJob()
        {
            positions = positions,
            angle = math.radians(10), // 必须转弧度!
            deltaTime = Time.deltaTime
        };

        // 调度并执行Job
        JobHandle handle = rotateJob.Schedule(positions.Length, 64);
        handle.Complete();

        // 释放内存
        positions.Dispose();
    }

    // Burst编译标记:开启极致优化
    [BurstCompile]
    public struct RotateJob : IJobParallelFor
    {
        [NativeDisableParallelForRestriction]
        public NativeArray<float3> positions;
        public float angle;
        public float deltaTime;

        public void Execute(int index)
        {
            // 高性能旋转计算(math库+Burst优化)
            quaternion rot = quaternion.RotateY(angle * deltaTime);
            positions[index] = math.mul(rot, positions[index]);
        }
    }
}

✅ 八、总结(核心知识点速记,必背)

  1. Unity.Mathematics 是 Unity 官方高性能数学库,DOTS开发必用,常规开发推荐用,性能碾压原生数学类型。
  2. 核心命名空间:using Unity.Mathematics;,核心类型:float3quaternionfloat4x4
  3. 核心规则:所有运算通过 math 静态类调用,所有旋转参数都是「弧度制」。
  4. 无缝兼容:原生Vector3float3可强制互转,旧代码改造成本极低。
  5. 性能核心:纯值类型、无GC、SIMD优化、Burst专属适配,是Unity高性能计算的基石。
  6. 避坑点:忘记将「角度」转「弧度」导致旋转异常,这是使用该库最常见的错误。