Moving a GameObject when it's within a distance from another?

How can i move a GameObject child from it’s Parent when the Object comes within a certain distance of another Object using JavaScript? I want to move the Object from it’s current position, by basically unparenting it from it’s Parent, and move it to the other GameObject. Then have it wait for about 0.2 seconds and then move the Object back to it’s Parented location and move the other object to the Parent’s Origin. An example would be if you have some object, let’s say a Cube or Sphere, Parented to the Player, and have the Cube/Sphere go over to the other Object to bring it back to your character and then go back to it’s Parented position.

There are many open question about what you are asking for. Here is a bit of example code. It goes on the child object. You don’t have to unparent the two object in order to solve this problem. ‘target’ is the object that triggers the movement. As long as the parent object is within ‘dist’, the child movement will cycle. If you don’t want that, you’ll have to code come additional state to catch the transition to/from ‘distance’ from target.

#pragma strict
 
public var target : Transform;
public var dist  = 2.5;
public var speed = 2.25; 

private var moving = false;
 
function Update() {
    if (!moving && Vector3.Distance(target.position, transform.position) < dist) {
    	MoveIt();
    }
}

function MoveIt() {
	moving = true;
	
	while (transform.position != target.position) {
	    transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
		yield;
	}

	yield WaitForSeconds(0.2);
	
	while (transform.localPosition != Vector3.zero) {
	    transform.localPosition = Vector3.MoveTowards(transform.localPosition, Vector3.zero, speed * Time.deltaTime);
		yield;
	}
	moving = false;
}

‘MoveIt()’ is a co-routine that will complete the cycle of movement. The last while() loop returns the child to the parent. Note how this code uses ‘localPosition’ rather than ‘position.’ This allows the child to return to the parent even if the parent moves while the child is moving.