Unity Ridgidbody约束,冻结位置Y.

时间:2016-03-26 11:28:22

标签: c# unity3d

我想在 Unity 中冻结块的y位置。 这是我的 C#代码:

var test = GetComponent<Rigidbody>().constraints;
test = RigidbodyConstraints.FreezePositionY;

它出现没有错误但Y位置不会冻结。

有人可以帮助我吗?我已经阅读了文档,但它只是说要做我做过的事情。

1 个答案:

答案 0 :(得分:1)

RigidbodyConstaints枚举enum,请注意小词in the doc),您必须先直接更改它,而不先复制它。使用该代码,您可以删除该枚举的副本,然后对其进行修改,以及失败的原因:

using UnityEngine;
using System.Collections;

public class PosFreezer : MonoBehaviour {

    void Start () {
        var rb = GetComponent<Rigidbody>();
        var constr = rb.constraints; //grab a copy (NOT a reference)
        constr = RigidbodyConstraints.FreezePositionY; //(modify the copy)
    }
}

这不是:

using UnityEngine;
using System.Collections;

public class PosFreezer : MonoBehaviour {

    void Start () {
        var rb = GetComponent<Rigidbody>();
        //Modify the constraints directly.
        rb.constraints = RigidbodyConstraints.FreezePositionY;
    }
}

所以,请记住,与enum的实例相比,每个struct都是值类型,如classreference type {1}}。抓取值类型的副本并在其中修改它可能不会做你想要的。但是,如果您写过:

,您的代码也会有效
var test = GetComponent<Rigidbody>().constraints;
test = RigidbodyConstraints.FreezePositionY;
GetComponent<Rigidbody>().constraints = test;

但无论如何,这都是混乱和不可读的。

相关问题