//获取或增加组件
public static Component GetOrAddComponent(this GameObject gameObject, Type type)
{
Component component = gameObject.GetComponent(type);
if (component == null)
{
component = gameObject.AddComponent(type);
}
return component;
}
//获取GameObject是否在场景中
public static bool InScene(this GameObject gameObject)
{
return gameObject.scene.name != null;
}
// 设置绝对位置的 x 坐标。
public static void SetPositionX(this Transform transform, float newValue)
{
Vector3 v = transform.position;
v.x = newValue;
transform.position = v;
}
// 设置绝对位置的 y 坐标。
public static void SetPositionY(this Transform transform, float newValue)
{
Vector3 v = transform.position;
v.y = newValue;
transform.position = v;
}
// 设置绝对位置的 z 坐标。
public static void SetPositionZ(this Transform transform, float newValue)
{
Vector3 v = transform.position;
v.z = newValue;
transform.position = v;
}
// 增加绝对位置的 x 坐标。
public static void AddPositionX(this Transform transform, float deltaValue)
{
Vector3 v = transform.position;
v.x += deltaValue;
transform.position = v;
}
// 增加绝对位置的 y 坐标。
public static void AddPositionY(this Transform transform, float deltaValue)
{
Vector3 v = transform.position;
v.y += deltaValue;
transform.position = v;
}
// 增加绝对位置的 z 坐标。
public static void AddPositionZ(this Transform transform, float deltaValue)
{
Vector3 v = transform.position;
v.z += deltaValue;
transform.position = v;
}
// 设置相对位置的 x 坐标。
public static void SetLocalPositionX(this Transform transform, float newValue)
{
Vector3 v = transform.localPosition;
v.x = newValue;
transform.localPosition = v;
}
// 设置相对位置的 y 坐标。
public static void SetLocalPositionY(this Transform transform, float newValue)
{
Vector3 v = transform.localPosition;
v.y = newValue;
transform.localPosition = v;
}
// 设置相对位置的 z 坐标。
public static void SetLocalPositionZ(this Transform transform, float newValue)
{
Vector3 v = transform.localPosition;
v.z = newValue;
transform.localPosition = v;
}
// 增加相对位置的 x 坐标。
public static void AddLocalPositionX(this Transform transform, float deltaValue)
{
Vector3 v = transform.localPosition;
v.x += deltaValue;
transform.localPosition = v;
}
// 增加相对位置的 y 坐标。
public static void AddLocalPositionY(this Transform transform, float deltaValue)
{
Vector3 v = transform.localPosition;
v.y += deltaValue;
transform.localPosition = v;
}
// 增加相对位置的 z 坐标。
public static void AddLocalPositionZ(this Transform transform, float deltaValue)
{
Vector3 v = transform.localPosition;
v.z += deltaValue;
transform.localPosition = v;
}
// 二维空间下使 指向指向目标点的算法,使用世界坐标。
public static void LookAt2D(this Transform transform, Vector2 lookAtPoint2D)
{
Vector3 vector = lookAtPoint2D.ToVector3() - transform.position;
vector.y = 0f;
if (vector.magnitude > 0f)
{
transform.rotation = Quaternion.LookRotation(vector.normalized, Vector3.up);
}
}
Unity 的扩展方法记录
于 2022-10-16 21:16:41 首次发布