- Home /
Member cannot be accessed with an instance reference; qualify it with a type name instead
I was in the middle of programming a block puzzle, when the block entered a trigger it's position was set to the triggers position and a door opened. So far everything worked, but I wanted to lock the block's position to the trigger so I tried to freeze the Rigidbody constraints but I got an error that said:
"Member 'RigidbodyConstraints2D.FreezePositionX' cannot be accessed with an instance reference; qualify it with a type name instead"
Here's the code:
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Box")
{
other.transform.position = transform.position;
Door.SetActive(false);
other.GetComponent<RigidbodyConstraints2D>().FreezePositionX = true;
}
}
Answer by doublemax · Jan 16, 2017 at 01:51 PM
other.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePositionX;
Also note that:
other.GetComponent<Rigidbody2D>()
might return null so you should probably check that too unless you know it'll be there beforehand.
Okay, now I've run into a new problem,When I freeze the X axis it removes the constraint I have on the rotation, and I can't have it freeze both X and Y. Sorry to keep bothering you.
Use: RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY ... or ... FreezePosition ... which is the same i.e. the two merged together with the | (or operator).
Thank you! Now it's working exactly how I wanted it to!
Everything correct. Just to add a few words of explanation:
RigidbodyConstraints2D is not a class or component but an enum type. The members of an enum are not variables but constants. The Unity documentation frequently labels thing wrong because most of their docs are auto-generated.
An enum as type is basically the same as the type "int". So it simply holds a 32bit "number". It just provides some special restrictions to the user so you can only assign values that are defined in the enum(eration) as constants.
The "constraints" variable (which is of type RigidbodyConstraints2D) is used as a bitmask.
The enum is declared like this:
public enum RigidbodyConstraints2D
{
None = 0,
FreezePositionX = 1, // 0000 0001
FreezePositionY = 2, // 0000 0010
FreezePosition = 3, // 0000 0011
FreezeRotation = 4, // 0000 0100
FreezeAll = 7 // 0000 0111
}
As you can see "FreezePosition" has a value of "3" which is just the combined bit patterns of FreezePositionX and FreezePositionY. Just like FreezeAll has a value of 7 which is FreezePositionX, FreezePositionY and FreezeRotation together
So as example if you want to freeze the "Y" axis and freeze the rotation you would have:
FreezePositionY 0010 2
or FreezeRotation 0100 4
----------------------------------
= 0110 6