- Home /
Calling functions in Javascript
Here I have a script that creates two movement states for a game object - rotating or traveling in a straight line. However I want to create two functions in my script to call upon in the Update function, but I don't know how to do it. Here's what I've got:
var pip : Transform;
var gel : Transform;
var nearPip = false;
var speed : float = -20;
function Update ()
{
if(Input.GetButton("Fire1"))
{
if(nearPip == true)
{
var pivot = pip.position;
gel.transform.RotateAround (pivot, Vector3.forward, 50 * Time.deltaTime);
}
else if (nearPip == false)
{
transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
}
}
}
But I'd much prefer to have it like this:
if(nearPip == true){
//insert Rotator function
}
else if(nearPip == false){
//insert Movement function
}
//and then under the Update function...
function Rotator(){
var pivot = pip.position;
gel.transform.RotateAround (pivot, Vector3.forward, 50 * Time.deltaTime);
}
function Movement(){
transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
}
Any help on how to call these functions correctly would be great, thank you peeps!
Answer by AlucardJay · May 15, 2013 at 01:25 PM
You are so incredibly close.
To call a function, simply call it by name as you do with a command
function PickMe()
{
// do stuff
}
call the function with :
PickMe();
note the parenthesis and the semicolon ();
So for your example script it would be :
var pip : Transform;
var gel : Transform;
var nearPip = false;
var speed : float = -20;
function Update ()
{
if (Input.GetButton("Fire1"))
{
if ( nearPip == true )
{
//insert Rotator function
Rotator();
}
else if ( nearPip == false )
{
//insert Movement function
Movement();
}
}
}
function Rotator()
{
var pivot = pip.position;
gel.transform.RotateAround (pivot, Vector3.forward, 50 * Time.deltaTime);
}
function Movement()
{
transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
}
Something else : it is worthy to note that :
if ( nearPip == true )
is the same as writing :
if ( nearPip )
and for not true :
if ( nearPip == false )
is the same as writing :
if ( !nearPip )
note the exclamation mark.
if ( nearPip )
{
//insert Rotator function
Rotator();
}
else if ( !nearPip )
{
//insert Movement function
Movement();
}
@alucardj this is exactly what I was after for and a nice explanation, thank you! :)
hello, that's a very nice formulated and documented answer thx a lot!!!
Answer by programmrzinc · May 15, 2013 at 01:20 PM
You can call these functions easy!
if(nearPip == true)
{
Rotator();
}
if(nearPip == false)
{
Movement();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613102251im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Updating rotation of client not working - strange error 0 Answers
Help with Grid Movement 2 Answers
Navigating the 3D platform 0 Answers
Rotate Character with movement 3 Answers
Orbit around an object 0 Answers