GoTo Script not working

Hi everyone. I have a goto script that is attached to an empty gameObject, and that object is supposed to follow the player on the x and z axis, but not the y. However, it only works on the x axis. Any help would be appreciated. Here is my code:

var useXTransform : boolean = true;
var useYTransform : boolean = true;
var useZTransform : boolean = true;
var useXRotation : boolean = true;
var useYRotation : boolean = true;
var useZRotation : boolean = true;
var TargetObject : Transform;

function Update () 
{
    if(useXTransform)
    {
        transform.position.x = TargetObject.transform.position.x;
    }
    if(useYTransform)
    {
        transform.position.y = TargetObject.transform.position.y;
    }
    if(useZTransform)
    {
        transform.position.z = TargetObject.transform.position.z;
    }
    if(useXRotation)
    {
        transform.rotation.x = TargetObject.transform.rotation.x;
    }
    if(useYRotation)
    {
        transform.rotation.y = TargetObject.transform.rotation.y;
    }
    if(useZRotation)
    {
        transform.rotation.z = TargetObject.transform.rotation.z;
    }
}

1 Answer

1

If you cant move on Z axis then you probably have forgotton to check `useZTransform` in inspector.

Your code could be probably compacted so it's easier to read.

var useXTransform : boolean = true;
var useYTransform : boolean = true;
var useZTransform : boolean = true;
var useXRotation : boolean = true;
var useYRotation : boolean = true;
var useZRotation : boolean = true;
var TargetObject : Transform;

function Update() {
    UpdatePosition();
    UpdateRotation();
}

function UpdatePosition() {
    var position = TargetObject.position;
    if (!useXTransform) position.x = 0;
    if (!useYTransform) position.y = 0;
    if (!useZTransform) position.z = 0;
    transform.position = position;
}

function UpdateRotation() {
    var rotation = TargetObject.rotation;
    if (!useXRotation) rotation.x = 0;
    if (!useYRotation) rotation.y = 0;
    if (!useZRotation) rotation.z = 0;
    transform.rotation = rotation;
}

Haha, nice compaction there. :-)

–

It should also be faster since the original version accessed the transform of a transform, which is just plain redundant, and it only access transform.position once - instead of reading three times writing three times. Arguably you could save a few cycles checking if it's even necessary to set the position at all and avoid updating the transform all together. But it's such a micro optimization it's hardly worth it.

–