Moving Object after spawn


After an object is instantiated, I would like it to move straight line across the map back and forth.

So I was wondering what would be most efficient way to do that? Thank you very much.

Make a script whose purpose is to move the object across the map back and forth. For example (manipulating position, not physics):

function Update ()
    transform.position.x = Mathf.PingPong(Time.time, 20);

Place this script on the prefab object that you're instantiating. Then, when you instantiate the prefab, you'll also get an instance of this script, which will begin execution immediately. For the purposes of this example, the script will move the object back and forth across the area from 0-20 units, world position. If you have more specific requirements, please say, and I can refine this answer.

You can also use the Animation Editor to create an animation that starts automatically once the object is instantiated and changes the GameObject's transform.position.x value over time. To get it to repeat, change the drop-down in the lower left-hand of the Animation Editor from "Default" to "Loop" or "Ping Pong", depending on the effect you're going for.

If you'd like a smoother animation for back and forth you could do the following

var degrees : float = 0;
var maxValue : int = 10;

function Update(){

 transform.Translate(0, maxValue * Mathf.Sin(degrees * (Mathf.PI/180)), 0);

 //keeps degrees from getting too high
     degrees > 360 ? degrees -= 360 : degrees += 2;

Here's another way to move an object back and forth (or up and down). I don't know if this method is more or less efficient than the Mathf.PingPong example, but I find that this gives me finer control over where the object changes direction.

Add this script to a game object (like a sphere) and put it at 0,0,0. You should see your sphere move between 2.5 and -2.5 on the Y axis.

var speed : float = 2.0;
private var trans : Transform;
private var dir : int = 1;

function Awake () {
    trans = transform;

function Update () {
    var moveSpeed = speed * Time.deltaTime;
    enemyPos = transform.localPosition.y;

    trans.Translate(0, moveSpeed*dir, 0);
    if(enemyPos >= 2.5) // this is in world coordinates
    	dir = -1;
    if(enemyPos <= -2.5) // this is in world coordinates
    	dir = 1;