# complicated functions - global or private variables

Just wondering if someone can give me some advice on global and private variables.

I have quite a few functions with complex calculations (complex to me anyway)
I have attached an example of one of these functions. There are around 6 of these functions running inside update.
I have declared thses variables as global. Some are reused with new values assigned to them in different functions.

my questions is …
is it better to create / declair these variables inside each function. or keep them how they are as global variables.
Im thinking of the best way to try and optimize my code as the script containing all these functions will eventually be attached to a lot of objects in my scene.

also feel free to advise me on better ways of implementing my code (sin, cos, tan) calcs etc. its not my strong point

thanks in advance…

``````var angleRad : float = 0;
var angleSin : float = 0;
var angleCos : float = 0;
var angleTan : float = 0;

var distA : float = 0;
var distB : float = 0;
var distC : float = 0;
var distD : float = 0;

var angleA : float = 0;
var angleB : float = 0;
var angleC : float = 0;
var angleD : float = 0;

function StageDaOffset(){
angleA = 90 - angleAPlayerCorner;
angleRad = angleA * (Mathf.PI/180);
angleSin = Mathf.Sin(angleRad);
distA = angleSin * surfaceWidth;
distA = enemyCharacterZoneRadius - distA;
angleB = 180 - (angleA + 90);
angleC = (adjacentSurfaceAngle * 2) - (angleB + 90);
angleD = 180 - (angleC + 90);

angleRad = angleD * (Mathf.PI/180);
angleCos = Mathf.Cos(angleRad);
distB = enemyCharacterZoneRadius / angleCos;

angleTan = Mathf.Tan(angleRad);
distC = angleTan * distA;

angleRad = angleA * (Mathf.PI/180);
angleCos = Mathf.Cos(angleRad);
distD = angleCos * surfaceWidth;
}
``````

Use local variables where possible. It will make the code more readable and less bug-prone, and will have a (very slight) performance improvement. That goes for the angleAPlayerCorner etc. variables as well; I don’t know how you’re using that exactly, but they should probably be passed into the function instead of existing as global variables.

Also it looks like this would be an example of when you’d use static, which usually I advise caution about using, but in this case, with what looks like a global generic math function, it would make things cleaner to have it as a static function. Just as a silly example, if you pretend that Vector3.Distance doesn’t exist and you wanted to make a function that gets the distance between two positions, you could make a script called Vector.js (that just exists in the project and is not attached to anything) with this function:

``````static function Distance (a : Vector3, b : Vector3) : float {
return (a-b).magnitude;
}
``````

Then you could call “Vector.Distance (transform.position, other.transform.position)” from any script.