How to assign a parent based on the childs relative position.


I have a moving object (Capsule) and a stationary object (Ring). I am trying to get the ring to be the parent object of the capsule if the capsule is within 5 units of the ring. (For the sake of discussion we will say along the y axis, the ultimate goal is to have the ring become the parent when the capsule comes within a circle around the ring of radius 5)

Anyways, I have successfully parented the capsule absolutely via script. When attempting to add the position part I don’t get any errors, but the capsule does not become parented.

I have attached a copy of my script below. I’m hoping someone can see an error in my code or provide an alternative route to explore?

var Capsule : Transform;
var Ring : Transform;
var xtemp;
var ytemp;

function Start ()

function Parent (ytemp : int){

ytemp = Capsule.transform.position.y;

if (ytemp >= 0 && ytemp <= 5)
Capsule.transform.parent = Ring.transform;


function Update()


Nice attempt… Here’s a better way:

var capsule : Transform; 
var ring : Transform;
var parentingDistance : float = 5.0;

function Start(){
capsule = GameObject.Find("NameOfCapsule").GetComponent(Transform);  // swap in name of your object
ring = GameObject.Find("NameOfRing").GetComponent(Transform);        // here too

function Update(){
if(Vector3.Distance(ring.position,capsule.position) < parentingDistance && !capsule.parent)
capsule.parent = ring;
else if(Vector3.Distance(ring.position,capsule.position) > parentingDistance && capsule.parent)
capsule.parent = null;

Vector3.Distance makes this a breeze!
I believe this should work for you