【问题标题】:Can't I add an extension method to Vector3 in Unity?不能在 Unity 中为 Vector3 添加扩展方法吗?
【发布时间】: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);

有什么办法吗?谢谢。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    试试这个:

    public static class Vector3Extensions
    {
        public static Vector3 SetX(this Vector3 pos, float x)
        {
            return new Vector3(x, pos.y, pos.z);
        }
    }
    

    并像这样使用它:

    Vector3 v = new Vector3(1, 2, 3);
    
    v = v.SetX(4);
    

    或者,对于转换,像这样:

    transform.position = transform.position.SetX(4);
    

    编辑:

    根据 D. Stanley 的观点,您可以使用以下方法扩展 Transform 类:

    public static class TransformExtensions
    {
        public static void SetXPos(this Transform t, float x)
        {
            t.position = t.position.SetX(x);
        }
    }
    

    然后这样称呼它:

    transform.SetXPos(4);
    

    【讨论】:

    • +1 这里的关键是你必须重新设置position 属性。无法就地更改不可变的属性值。
    • 感谢您的快速回复。它对我有很大帮助。我决定像你展示的那样使用transform.SetXPos() 方法。谢谢。
    • 很高兴我能帮上忙。我希望您将我的回答标记为正确。干杯!
    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2019-06-27
    • 2012-07-12
    • 1970-01-01
    相关资源
    最近更新 更多