I’m referencing another script inside a Unity event to change the direction of the player in-game.

The problem is that my script changes the x value to a negative float but it doesn’t change it back to positive even though it can successfully check for a negative value.

I wasn’t sure if I needed another collision check but why can it change the x value from positive to negative but not from negative to positive. Any help is appreciated.

public void OnTriggerStay2D(Collider2D collider)
    {
        var autocroll = collider.gameObject.GetComponent<Autoscroll>();
        float myDirection = autocroll.directionForce.x;

        if(collider.gameObject.tag == "Player")
        {
            if (myDirection < 0) //Moving left
            {
                myDirection = -5f; //Turn right
                print("moving left");
            }

            if(myDirection > 0) //Moving right
            {
                myDirection = 5f; //Turn left
            }
        }
    }

Because myDirection isnt a pointer/reference, is a copy. in myDirection you are not saving the reference to autcroll.directionForce.x but just the value.

float valuaA  = 0;
float valueB = 0;
//-------------------both floats are 0

valuaA = 5;
valueB = valuaA;
//------------------both floats are 5

valueB++;
//-----------------valuaA = 5 and valueB = 6

so to fix this simply change the property value

autocroll.directionForce.x = 5;//and the same with -5

Instead of using two if statements I just cleaned up the code to set it as a negative value of itself each time it enters a specific collider.

 public void OnTriggerEnter2D(Collider2D collider)
    {
        var autoscroll = collider.gameObject.GetComponent<Autoscroll>();

        if(collider.gameObject.tag == "Player")
        {
            autoscroll.directionForce.x = autoscroll.directionForce.x * -Mathf.Abs(1);
        }
    }