How do I query the RigidbodyConstraints?

How can I query the rigidbody.constraints? I want to determine if certain objects have RigidbodyConstraints.FreezePositionY enabled.

3 Answers

3

Eric5h5’s solution no longer works (in C#, anyway). Here’s an up-to-date version:

    using System;
    using UnityEngine;
    
    public static class RigidbodyConstraintExentions
    {
    	public static bool HasConstraint(this RigidbodyConstraints thisConstraint, RigidbodyConstraints constraint)
    	{
    		return (thisConstraint & constraint) != RigidbodyConstraints.None;
    	}
    }

This isn't working for me. Did it change again? if ((rigidbody.constraints & RigidbodyConstraints.FreezeRotationZ) != RigidbodyConstraints.None) { Debug.Log("Rotation frozen"); euler.z = 0f; }

–

Hi,

here’s what works for me ( unity game engine - Unity3D Rigidbody Constraints Get Property - Stack Overflow)

if((rigidbody.constraints & RigidbodyConstraints.FreezePositionX) == RigidbodyConstraints.FreezePositionX) 
{
    // x-position is frozen
}

Bye,

Jean

See the docs. If you're trying to see if the constraints contain FreezePosition.Y among other values, rather than just checking to see if they are FreezePosition.Y, then you can mask it with &:

if (rigidbody.constraints & RigidbodyConstraints.FreezePositionY) {
    // constraints has at least FreezePositionY, don't care about others 
}

I have. Unfortunately the docs discuss setting the constraints, but not how to read which constraints are set - though it might just be me being thick, so if so, please do let me know how I can read the constraint settings

–

@Toxic Blob: wait, are you just checking for FreezePositionY or do you want to see if FreezePositionY is one of the constraints even though there might be others? The former should be obvious from the docs, the latter maybe not so obvious.

–

That's exactly what I was attempting to do. That solution wasn't exactly obvious. Thanks for the help! Superb!

–