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.
- 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.
- why doesn’t my code work?
thank you