Hi,
I’m using unity from 5 days and I have some big difficulty with scripts, because I never used Java, so I try to ask here… maybe you can help me…
In the scene there are a Sphere and a Cube. The Sphere must move to Cube when I push a button.
This is the script:
private var speed = 0.25;
private var increment : float;
function OnGUI () {
// Build a Box
GUI.Box (Rect (10,10,100,90), "Move");
// Build the button. If push goto the function Move
if (GUI.Button (Rect (20,40,80,20), "Cube")) {
MoveSphere ();
}
}
function MoveSphere () {
// Look if the Sphere has a different position than Cube
if (transform.position != GameObject.Find("Cube").transform.position) {
if (increment <=1) {
increment += speed/100;
}
// Move the Sphere to the Cube position
transform.position = Vector3.Lerp(transform.position, GameObject.Find("Cube").transform.position, increment/2);
}
else {
print ("Finish!");
increment = speed/100;
return;
}
}
The first function creates a box and a button, if pushed begin the second function.
The problem is that the Sphere moves only a little distance, because need to repeat the function MoveSphere until the Sphere get the Cube position.
I tried to write an other call to function MoveSphere (); after the transform.position=Vector3.Lerp etc. etc. but the execution is so fast than all the cycle of move happens in less time than a frame refresh, so the Sphere goes to Cube in 1 frame only.
If I change the function MoveSphere () with the function Update () the Sphere moves right, like I want, but all begins when the script run and not when I push the button… and the function can’t stop with return command… so the function continue to calculate the same transform.position forever.
How can I repeat the function MoveSphere every frame (or every 1/30 seconds) like happen with function Update ?
Thankyou very much for any help and really sorry for my bad english…