Swap texture2D on enemy sprite once reached a certain point

I am trying to make a 2D game, I am using this script, I have 3 empty gameobjects as way points, 1 (where enemy spawns) 2 & 3 which it moves to and fro in a loop:

var waypoint : Transform[];
var speed : float = 20;
private var currentWaypoint : int;
var loop : boolean = false;
var Distance : float = 1;

function Awake(){


} function Update () {

    if(currentWaypoint < waypoint.length)
    {
    var target : Vector3 = waypoint[currentWaypoint].position;
    var moveDirection : Vector3 = target - transform.position;
     
    var velocity = rigidbody.velocity;
    if(moveDirection.magnitude < Distance)
    {
    currentWaypoint++;
    }
     
    else{
    velocity = moveDirection.normalized * speed;
    }
    }
     
    else{
    if(loop)
    {
    currentWaypoint = 0;
    }
    else
    {
    velocity = Vector3.zero;
    }
    }
    rigidbody.velocity = velocity;

}

I am using this script to animate the texture2D:

var numFrames : int = 3;
var curFrame : int = 1;

function Update(){

transform.position.z = 0.01;

renderer.material.mainTextureOffset.x += 1.0 / numFrames + Time.timeScale;
curFrame += 1;

if (curFrame > numFrames){
renderer.material.mainTextureOffset.x = 0;
curFrame = 1;

}

}

What I am trying to do is have the texture2D change when the enemy is facing left or right (currently just looks correct one way then moonwalks back lol) I have tried to make a script to do this, here it is below:

public var walkright : Texture2D; //walking right
public var walkleft : Texture2D; //walking left
public var mesh : GameObject; //Mesh

function Update () {

if (mesh.transform.position.x < (5.097385)){

mesh.renderer.material.mainTexture = walkleft;
}

if (mesh.transform.position.x > (-4.12935)){
mesh.renderer.material.mainTexture = walkright;
}
}

can anyone help me/suggest where I am going wrong? I’m thinking I need to say if distance from waypoint 2 is decreasing use texture left and same for waypoint 3 but I don’t know how to type this in code

I do my coding in C#, so this might not be 100% syntax accurate:

public var walkright : Texture2D; //walking right
public var walkleft : Texture2D; //walking left
public var mesh : GameObject; //Mesh
private var oldXPos : float; //Old x position
 
function Update () {
 
if (mesh.transform.position.x >= oldXPos)
{
  mesh.renderer.material.mainTexture = walkright;
}
else
{
  mesh.renderer.material.mainTexture = walkleft;
}
 
oldXPos = mesh.transform.position.x;
}

You will probably want to initialize oldXPos to something that gives the mesh the initial state animation that you are going to want.