- Home /
setting a parent's variable to a child's variable without changing the position of the child according to a parent's position
hi. I am new to unity and i need help with setting a child's variable without setting the position of the child according to the parent or is there a method where you don't need a child or parent. I really need help with this and the child is a rigidbody with the script that has variables "x", "y" and "z" and the parent is a camera. The camera is supposed to follow the rigidbody (which is a sphere called "Sphere") without doing some kind of weird thing like making the rigidbody zoom at 1000 units per second with the camera following it and falling into eternity at the end of the flat world. In fact, it is supposed to move only when the arrow keys are pressed. Here is the part where the parent's variables are set and where the child's variables:
var x=0.0;
var y=0.0;
var z=0.0;
function Update(){
x=transform.Find("Sphere").position.x;
y=transform.Find("Sphere").position.y;
z=transform.Find("Sphere").position.z;
transform.position=Vector3(x,y+2,z-0.8);
};
Answer by StephanK · Feb 12, 2011 at 11:17 AM
If you want the camera to follow the sphere the camera should be the child of the sphere not the other way round. No scripting needed for that at all. (Unless you want to add some damping or smoothing)
Well, that's the basic idea, but if it's a sphere and it's rolling on the ground it's better to have no parent-child relationship at all. Just use the smoothfollow script or similar scripts. A short look into the "unify community wiki" or the standard assets will help.
Answer by DaveA · Feb 12, 2011 at 10:28 AM
Update() gets called every frame. So a couple problems here. 1. Find() is an expensive call. Do it once (in Startup() for example) and save that result, using it in Update, you'll get better performance. 2. 'position' is world-position. So you've essentially created a donkey/carrot relationship, where each frame Update is called to move the gameobject a few units from Sphere, which will (being a child) move with it. Zoom! Look into using localPosition instead, if you need relative placement. You shouldn't have to move them relative to each other (unless of course you have to), just move the parent, and the child follows.
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Problem with making child an object 2 Answers
Line up camera views 0 Answers
Find children by tag from Player 1 Answer
How can I get a parent GameObject of gameObject using Javascript? 6 Answers