Vector 扩展方法无意中复制参数
我无法让扩展方法工作,它将运行,但我作为参数放入其中的向量3与我在TurnClockWiseXZ方法中操作的向量不同 这是调用该方法的类Vector 扩展方法无意中复制参数,vector,reference,unity3d,extension-methods,Vector,Reference,Unity3d,Extension Methods,我无法让扩展方法工作,它将运行,但我作为参数放入其中的向量3与我在TurnClockWiseXZ方法中操作的向量不同 这是调用该方法的类 using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { void FixedUpdate () { Vector3 test = new Vector3(2,0,3); Debug.L
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
void FixedUpdate () {
Vector3 test = new Vector3(2,0,3);
Debug.Log ("1: "+test);
test.TurnClockWiseXZ();
Debug.Log ("2: "+test);
}
}
这是我添加方法的地方:
using UnityEngine;
using System.Collections;
public static class ExtendClass {
public static void TurnClockWiseXZ( this Vector3 vector){
float x = vector.z;
float y = vector.y;
float z = -vector.x;
vector.Set(x,y,z);
}
}
以下是我收到的调试消息:
1:(2.0,0.0,3.0)
2:(2.0,0.0,3.0)
这就是我想要的:
1:(2.0,0.0,3.0)
2:(3.0,0.0,-2.0)不幸的是,由于Vector3是一个结构(因此也是一个值类型),所以它总是通过复制自身(按值传递)来传递到方法中。因此,扩展方法内部的任何修改只会影响副本 我看到了一些替代方案 1) 使扩展方法返回新复制的向量并重置外部变量。调用时如下所示:
test=test.TurnClockwiseXZ()代码>
2) 改为使用静态方法(不是扩展方法),该方法返回void,但将向量作为ref
参数。这看起来是这样的:ExtendClass.TurnClockwiseXZ(reftest)
定义为public void turnsclockwisexz(ref Vector3 vect)
它通过引用传递向量,因此它修改函数内部的外部变量
3) 如果您大部分时间只是修改变换内部的位置(就像我一样),那么您可以让extension方法直接对变换进行操作。因为转换是一个类(而不是结构),所以默认情况下它是通过引用传递的,扩展方法也可以工作。该解决方案如下所示:
public void TurnClockwiseXZ(this Transform transform) {
float x = transform.position.z;
float y = transform.position.y;
float z = -transform.position.x;
transform.position = new Vector3(x,y,z);
}
并用作:transform.TurnClockwiseXZ()代码>
我个人在转换中有SetX、SetY和SetZ的扩展方法,可以轻松修改位置。省去了一些麻烦