Getting position of an object

I have an object which named “spaceship” and i’ve assigned a controller script to that object.

And i want to camera just follow its z axis. So other x and y axis won’t be applied to camera. This is what i want to do. But Unity gives NullReferenceException error. I’ve tried different variations but i failed to achieve.

Please help about that issue.

This is camera’s script:

function Update () 
{
var pos = GameObject.Find("spaceship").transform.position.z;
var poskam = GameObject.Find("MainCamera").transform.position.z;
poskam = pos;
}

AND CONTROLLER SCRIPT:

// This script moves the character
controller forward

/// and sideways based on the arrow keys.

/// It also jumps when pressing space.

/// Make sure to attach a character controller to the same game

object.

/// It is recommended that you make only one call to Move or

SimpleMove per frame.

var speed : float = 6.0;

var jumpSpeed : float = 8.0;

var gravity : float = 20.0;



private var moveDirection : Vector3 = Vector3.zero;



function Update() {

var controller : CharacterController =

GetComponent(CharacterController);

if (controller.isGrounded) {

// We are grounded, so recalculate

// move direction directly from axes

moveDirection = Vector3(Input.GetAxis("Horizontal"),

0,

Input.GetAxis("Vertical"));

moveDirection = transform.TransformDirection(moveDirection);

moveDirection *= speed;



if (Input.GetButton ("Jump")) {

moveDirection.y = jumpSpeed;

}

}



// Apply gravity

moveDirection.y -= gravity * Time.deltaTime;



// Move the controller

controller.Move(moveDirection * Time.deltaTime);

}

Try adding a space to “Main[space]Camera”–> GameObject.Find(“Main Camera”)

Added note :

  1. You don’t want to be calling GameObject.Find in Update() like that… it’s slow.

Error is on the

> var pos =
> GameObject.Find("spaceship").transform.position.z;

line.
Also already object moving. So i don’t think it’s related with charactercontroller. Just camera doesn’t gets z position.