How can I set my cube moving left and right with custom switch?

Hello. I have been trying to write a script that can make the cube(an enemy)in my platform game to start moving from left and right. The script is in JavaScript. I only manage to make the cube move left, but only moving left. While the game is played I click on the switch in the inspector and then the cube starts moving to the right. How can I tell the cube to move which way to go using the script?


var DestinationSpot:Transform;
var OriginSpot:Transform;
var Speed:float;
var Switch:boolean = false;
    // For these 2 if statements, it's checking the position of the enemy.
    // If it's at the destination spot, it sets Switch to true.
    if(transform.position == DestinationSpot.position)
    {
        Switch = true;
    }
    if(transform.position == OriginSpot.position)
    {
        Switch = false;
    }
     
    // If Switch becomes true, it tells the enemy to move to its Origin.
    if(Switch)
    {
        transform.position = Vector3.MoveTowards(transform.position, OriginSpot.position, Speed);
    }
    else
    {
        // If Switch is false, it tells the enemy to move to the destination.
        transform.position = Vector3.MoveTowards(transform.position, DestinationSpot.position, Speed);
    }

Your big problem here, is that you need to put your code inside an Update() function so that it gets called once per frame. Right now it only gets executed once. In addition, you should use ‘speed * Time.deltaTime’ as the last parameter in your MoveTowards() so that the code is frame-rate independent:

function Update() {
    // For these 2 if statements, it's checking the position of the enemy.
    // If it's at the destination spot, it sets Switch to true.
    if(transform.position == DestinationSpot.position)
    {
        Switch = true;
    }
    if(transform.position == OriginSpot.position)
    {
        Switch = false;
    }
 
    // If Switch becomes true, it tells the enemy to move to its Origin.
    if(Switch)
    {
        transform.position = Vector3.MoveTowards(transform.position, OriginSpot.position, Speed * Time.deltaTime);
    }
    else
    {
        // If Switch is false, it tells the enemy to move to the destination.
        transform.position = Vector3.MoveTowards(transform.position, DestinationSpot.position, Speed * Time.deltaTime);
    }
 }

Note when you have something that oscillates, consider using Mathf.PingPong() or Mathf.Sin() to set the position. Example:

#pragma strict

var dest : Transform;
var org : Transform;
var speed : float = 1.5;

function Update() {
    var t = Mathf.PingPong(Time.time * speed, 1.0);
	transform.position = Vector3.Lerp(dest.position, org.position, t);
 }