Setting another script's property from code doesn't actually set the property

I am trying to instantiate a cube from a prefab and move it gradually from one position to another.

I have create a game object as a prefab.

Here is how I instantiate my cube:

    using UnityEngine;
    using System.Collections;
    public class CubeScript : MonoBehaviour {
    
    	public GameObject cube;
    
    	void Start () {
                    // instantiate cube 10 units under transform (of empty parent GameObject which is to whom this script is attached to)
                    GameObject obj = Instantiate (cube, transform.position - new Vector3(0, 10, 0), Quaternion.identity) as GameObject;
                    // Set this as the parent
    		obj.transform.parent = transform;
                    // Set end position of the cube
    		obj.GetComponent<Movement> ().endPosition = transform.position;
        }
    }

This script to attached to an empty game object which is to serve as a parent to all cubes.

I have attached a “movement” script to the cube prefab.

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

	public Vector3 endPosition;
	public float speed;
	void Start () {
           // dummy initialization of end position because we don't have end position yet.
		endPosition = transform.position;
		speed = 5.0f;
	}

	void Update () {
                // move the cube
		transform.position = Vector3.MoveTowards (transform.position, endPosition, speed * Time.deltaTime);
	}
}

What I notice is that the instantiate cube’s end position is never set. It stays the same as the initial position and hence there is no movement noticed.

  1. is there a better / more elegant way of achieving what I am trying to? I am particularly unhappy with how I am having to set the end position property of the instantiated cube after instantiating just so it moves.
  2. why doesn’t my code work?

thank you

I’m not clear on what you are actually trying to do. Where is the end position supposed to be? The cube parent object?

At the moment you are setting endPosition to the cube’s parent position in CubeScript:

obj.GetComponent<Movement>().endPosition = transform.position;

But then overwriting it to the cube’s spawn position on start in Movement:

endPosition = transform.position;

So your cube is just going to be trying to move towards where it already is. Remove endPosition from start and it should work, assuming you want to cubes to move towards the cube parent.