# How to make code more efficient

Is there any possible way to optimize my code further? I am really aiming to squeeze out as much performance as possible.

A part of my code is below, but my entire code is this snippet about 20 times copied and pasted with different numbers (in one update function of course).

var other: Transform;

var other2: Transform;

``````function Update () {
if(other2.transform.eulerAngles.y > -1 && vother2.transform.eulerAngles.y < 1){
other.transform.localPosition.z = -(transform.position.z - other2.transform.position.z);
other.transform.localPosition.x  = -(transform.position.x - other2.transform.position.x);
other.transform.localPosition.y = transform.position.y - other2.transform.position.y;
}
}
``````

Is there any faster way, in regards to speed, processing time, and cpu impact, to do this? The position and local positions of all my variables will be changing constantly, or else I would declare the variables in my start function which I know can speed things up a little.

other and other2 are already transforms, so remove “transform” when referring to them. It would be faster to cache the transform of the current object.

``````var other: Transform;
var other2: Transform;
private var myTransform : Transform;

function Start () {
myTransform = transform;
}

function Update () {
if(other2.eulerAngles.y > -1 && other2.eulerAngles.y < 1){
other.localPosition.z = -(myTransform.position.z - other2.position.z);
other.localPosition.x  = -(myTransform.position.x - other2.position.x);
other.localPosition.y = myTransform.position.y - other2.position.y;
}
}
``````

You can calculate the difference, save it in a Vector3 var, change what you have to and assign it to other.position:

``````function Update () {

var angles2 = other2.eulerAngles;
var pos1: Vector3;

if (angles2.y>-1 && angles2.y<1){
// calculate all differences at once in pos1
pos1 = transform.position - other2.position;
// change signal of the coordinates you want
pos1.z = -pos1.z;
pos1.x = -pos1.x;
// assign the result to other.localPosition at once
other.localPosition = pos1;
}
}
``````

I don’t get why you’re using other.transform and other2.transform when those variables already contain the actual Transform components that you’re trying to access. other.transform IS other.

You need to cache all those positions and angles immediately after Update() starts.