Efficient way with getter/setter property

Animator state and gravity scale are all managed, once per state change, within the setter.
This will also avoid abundant call of local variables and spaghetti codes of if/else’s.

Such a powerful and flexible method that I recently learned during this lecture.

private float initGravity;
private bool _isClimbingLadder;

private void Start()
    {
        initGravity = _rigidbody.gravityScale;
    }

private void ClimbLadder()
    {
        Climbing = _collider.IsTouchingLayers(LayerMask.GetMask(LADDER_LAYER_NAME_STRING));
        if (Climbing)
        {
            _rigidbody.velocity = new Vector2(
                _rigidbody.velocity.x,
                Input.GetAxisRaw(VERTICAL_AXIS_STRING) * climbLadderSpeed
                );
        }
    }

private bool Climbing
    {
        get { return _isClimbingLadder; }
        set
        {
            if (value == _isClimbingLadder) return;
            _isClimbingLadder = value;
            _animator.SetBool(CLIMB_ANIM_BOOL_STRING, value);

            switch(value)
            {
                case true:
                    _rigidbody.gravityScale = 0;
                    break;
                case false:
                    _rigidbody.gravityScale = initGravity;
                    break;
            }
        }
    }

Privacy & Terms