C#元组和Unity Vector3详解
一、C# 元组(Tuple)
1. 基本概念
- 元组是一种轻量级的数据结构
- 可以存储多个不同类型的值
- C# 7.0及以后版本支持更简洁的语法
- 支持命名和解构
2. 创建方式
Tuple<int, string> tuple1 = new Tuple<int, string>(1, "Hello");
(int id, string name) tuple2 = (1, "Hello");
var tuple3 = (id: 1, name: "Hello");
3. 元组特性
- 值类型(存储在栈上)
- 成员不可变(但可以整体重新赋值)
- 支持相等比较
- 可作为方法返回值
4. 常用操作
(int x, string y) tuple = (123, "test");
Console.WriteLine(tuple.x);
Console.WriteLine(tuple.Item1);
var (id, name) = GetPerson();
5. 实际应用场景
(int min, int max) FindMinMax(int[] numbers)
{
return (numbers.Min(), numbers.Max());
}
Dictionary<(int, int), float> gridValues;
var playerInfo = (health: 100, position: new Vector3(0,0,0));
二、Unity Vector3
1. 基本概念
- 表示3D空间中的点或方向
- 包含X、Y、Z三个浮点数分量
- 结构体类型(值类型)
- Unity中最常用的数据类型之一
2. 常用属性
Vector3.zero
Vector3.one
Vector3.up
Vector3.down
Vector3.left
Vector3.right
Vector3.forward
Vector3.back
vector.magnitude
vector.sqrMagnitude
vector.normalized
3. 常用方法
Vector3.Distance(a, b)
Vector3.Angle(a, b)
Vector3.Dot(a, b)
Vector3.Cross(a, b)
Vector3.Lerp(a, b, t)
Vector3.Slerp(a, b, t)
Vector3.Project(a, b)
Vector3.Reflect(a, normal)
vector.Normalize()
vector.Set(x, y, z)
vector.ToString()
4. 运算符重载
Vector3 c = a + b;
Vector3 d = a - b;
Vector3 e = a * 2f;
Vector3 f = a / 2f;
Vector3 g = -a;
5. 常见使用场景
位置操作
transform.position += Vector3.forward * speed * Time.deltaTime;
Vector3 direction = target.position - transform.position;
旋转操作
transform.rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(
transform.rotation,
targetRotation,
Time.deltaTime * rotateSpeed
);
物理计算
rigidbody.AddForce(Vector3.up * jumpForce);
rigidbody.velocity = new Vector3(x, y, z);
6. 性能优化建议
- 计算优化
if (Vector3.Distance(a, b) < range)
if ((a - b).sqrMagnitude < range * range)
- 内存优化
private Vector3 moveDirection;
void Update() {
moveDirection.Set(x, y, z);
transform.position += moveDirection * speed * Time.deltaTime;
}
7. 最佳实践
- 向量运算
Vector3 direction = (target.position - transform.position).normalized;
float dot = Vector3.Dot(transform.forward, direction);
bool isInFront = dot > 0;
- 插值应用
transform.position = Vector3.Lerp(
transform.position,
targetPosition,
smoothSpeed * Time.deltaTime
);
Vector3 desiredPosition = target.position + offset;
transform.position = Vector3.SmoothDamp(
transform.position,
desiredPosition,
ref velocity,
smoothTime
);
总结
- 元组(Tuple)
- 适合临时组合多个值
- 方法返回多个值时很有用
- 注意性能开销,不适合频繁创建
- Vector3
- Unity 3D开发中最基础的数据类型
- 掌握常用属性和方法
- 注意性能优化
- 合理使用插值实现平滑效果