How do I get a single object to move?

I have multiple spheres and I want to move them independently. I want to “left-click-mouse” to select the sphere I want to move. Then I want to “right-click-mouse” to select a location for the sphere to move to. In theory, I should (I want to…) be able to move ALL the spheres simultaneously but each to a different location. I’m not getting any errors…but I’m not getting any movement either. Any suggestions?

void Update()
{

/////  I select the object here...

	if (Input.GetMouseButtonDown(0))  
	{
		RaycastHit hit; 
		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		if (Physics.Raycast(ray, out hit)) 
		{

			Collider col = hit.collider;
			if (col != null) 
			{
				test01 = hit.collider.name;
				Debug.Log (hit.collider.name);
			}
		}
	}

/////  I select the movement destination here...

	if (Input.GetMouseButtonDown(1))  
	{
		RaycastHit hit;
		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		if (Physics.Raycast(ray, out hit)) 
		{
			goToHere = hit.point;
			Debug.Log (hit.point);
		}
	}

/////  I (attempt) to get the object moving here by using foreach to check through every object and move the one with correct name

	foreach (GameObject gameObj in GameObject.FindObjectsOfType<GameObject>())
	{
		if (gameObj.name == test01)
		{
			transform.position = Vector3.MoveTowards (transform.position, goToHere, speed * Time.deltaTime);
		}
	}

}
  • Calling FindObjectsOfType is very slow and should be avoided in Update().
  • You are actually moving the GameObject with the movement script. You need to specify the GameObject or Transform that you want to move, otherwise transform is a reference to the transform of the GameObject your script is attached to.
  • Instead of referencing by name, why not reference the game object directly? Simply create a variable of type GameObject or Transform. You can then assign it through: myGameObject = hit.collider.gameObject; in line 16 in your snippet.