Reputation: 367
I want to freeze the y position of a block in Unity. Here is my C# code:
var test = GetComponent<Rigidbody>().constraints;
test = RigidbodyConstraints.FreezePositionY;
It comes up with no errors however the Y position doesn't freeze.
Could someone help me? I have read the documentation but it just says to do what I have done.
Upvotes: 0
Views: 6677
Reputation: 5353
RigidbodyConstaints
is an enumeration (enum
, mind that small word in the doc), you must change it directly without making a copy of it first. With that code, you're pulling a copy of that enum, then modify it, that's why it this fails:
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)
}
}
This does not:
using UnityEngine;
using System.Collections;
public class PosFreezer : MonoBehaviour {
void Start () {
var rb = GetComponent<Rigidbody>();
//Modify the constraints directly.
rb.constraints = RigidbodyConstraints.FreezePositionY;
}
}
So, remember, every enum
is a value type, like a struct
, in comparison to an instance of a class
, which is a reference type
. Grabbing a copy of a value type and modifying it localy probably doesn't do what you want. Your code would however also have worked if you had written:
var test = GetComponent<Rigidbody>().constraints;
test = RigidbodyConstraints.FreezePositionY;
GetComponent<Rigidbody>().constraints = test;
But that's to messy and unreadable anyways.
Upvotes: 1