How to Maintain Y Position? C#

I want to have the player press the “MouseButton3” and have whatever height he was at the time he pressed the button be his locked Y axis position until he presses the button again.

Ex: Player presses button when his Y position was at 10. His Y position is locked at 10 until he presses the button again/releases the button.

1 Answer

1

You must use a flag to indicate if it’s locked or not. When the flag becomes true, save the locked height. If flag is true, force the y coordinate after the movement to the saved height:

EDITED: This answer had one error: the y element of transform.position was being assigned alone. It’s valid in Unityscript, but not in C#, as @Bunny83 said - the whole structure must be assigned. This error fixed now.

float lockedY;     // holds the locked height
bool lock = false; // true if locked

void Update(){
    if (Input.GetButtonDown("MouseButton3")){ // I suppose that's your button name
        lock = !lock; // toggle lock flag
        if (lock) lockedY = transform.position.y; // if lock became true save locked height
    }
    // do your movement stuff here
    // then force y to the locked height if lock active
    if (lock){
        Vector3 tmp = transform.position; // position is actually a
        tmp.y = lockedY;                  // property, thus you must set
        transform.position = tmp;         // all their members at once
    }
}

Don't forget that you can't set a member of a struct-property. You have to assign the whole Vector3 in C#. if (lock) { Vector3 tmp = transform.position; tmp.y = lockedY; transform.position = tmp; }

That's what happens when a JS guy tries to write C#... Thanks, @Bunny83!