Object to wait and then move

Hi. Simple question here (I think); its my first project. I’m trying to get an object to wait for a random time, then move horizontally off the screen. The script below has the object wait ok, but then it doesn’t smooth move off the screen, it jumps to the position indicated by the speed.

var speed = 1; //arbitary speed to adjust later
var randomWait;
var targetPos = Vector2(200,0); //arbitary position to take the object off screen

function Start() {
	randomWait = Random.Range(1,6);
	WaitSeconds();
}

function WaitSeconds() {
	print ("wait " + randomWait + " seconds");
	yield WaitForSeconds(randomWait);
		
	transform.position = Vector2.MoveTowards(transform.position, targetPos, speed*Time.deltaTime);
}

I want to later add the ability for the player to click on the object to stop it moving.

Your code is only moving the block one frames worth now. You need to move it over a number of frames. In the following code, take a look at the ‘while’ loop added to your WaitSeconds() coroutine. As a bonus, I tossed in code that makes it stop moving when clicked. See the OnMouseDown() callback.

#pragma strict

var speed = 1; //arbitary speed to adjust later
var randomWait;
var targetPos = Vector2(200,0); //arbitary position to take the object off screen
 
function Start() {
    randomWait = Random.Range(1,6);
    WaitSeconds();
}
 
function WaitSeconds() {
    print ("wait " + randomWait + " seconds");
    yield WaitForSeconds(randomWait);
 	
 	while (transform.position != targetPos) {
    	transform.position = Vector3.MoveTowards(transform.position, targetPos, speed*Time.deltaTime);
        yield;
    }    	
}

function OnMouseDown() {
   targetPos = transform.position;
}