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!

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();
		}

You can call these functions easy!

       if(nearPip == true)
       {
         Rotator();

       }
       if(nearPip == false)
       {
         Movement();

       }

@alucardj Thank you very much! :slight_smile: