How to pass position information between two objects?

Hi,

I have a randomly spawning set of cubes using the instantiate command using C sharp.

Once you click on the cube a sphere is spawned, again in a random place.

This all works fine (lots of spheres are spawned when you keep clicking on different cubes). What I need now is for the sphere to go towards the very cube that I clicked for it to spawn. Not just any cube.

I’m relatively new to this so I thought of two ways this might work:

  1. Storing the coordinates of the cube in a temporary object.
  2. Adding the spheres as children to the cubes

What I’m essentially looking for is a for the cube to create the sphere and then say “Oh, btw here are my coordinates, come get me!”

Please let me know if there is a simple way of doing this (I just know there is!).

Thank you for the help.

Regards,
G

Make a script that follows a position or transform. Then when you Instantiate the object (sphere), use GetComponent to access the follow script and set the target. For example:

public class MoveTowardsTarget : MonoBehaviour {

	public Transform target;
	public float moveSpeed = 0.1f;

	// Update is called once per frame
	void Update () {
		if (target != null)
		{
			this.transform.position = Vector3.MoveTowards(transform.position, target.position, moveSpeed);
		}
	}
}

public class SpawnOnClick : MonoBehaviour {

	public GameObject spawnObject;

	void OnMouseDown()
	{
		Vector3 randomPos = new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0);
		GameObject newObject = Instantiate(spawnObject, randomPos, Quaternion.identity) as GameObject;
		MoveTowardsTarget moveScript = newObject.GetComponent<MoveTowardsTarget>();
		if (moveScript != null)
		{
			moveScript.target = this.transform;
		}
	}
}

Just declare a vector3 type variable in which you can store the position information of the cube…
then you can just use the movetowards function or something to move the sphere towards the Vector3 position,