【发布时间】:2020-03-10 17:20:04
【问题描述】:
当我想在 Unity 中改变一个变换的位置时,我通常这样做:
var x = 10f;
transform.position = new Vector3(x, transform.position.y, transform.position.z);
但我认为这有点乏味。所以我将此扩展方法添加到 Vector3 类中。
public static class Vector3Extensions
{
public static void SetX(this Vector3 pos, float x)
{
pos = new Vector3(x, pos.y, pos.z);
}
....
当我调用它时,没有错误,但实际上值没有改变。是的,我知道这会发生,因为 Vector3 是结构。我试图在我的方法中添加一个 ref 关键字,
public static void SetX(ref this Vector3 pos, float x)
{
pos = new Vector3(x, pos.y, pos.z);
}
但它不起作用,因为出现“属性或索引器可能不会作为 out 或 ref 参数传递”错误。 我想这样做:
transform.position.SetX(10f);
有什么办法吗?谢谢。
【问题讨论】: