Basic Scripting question

I would like to use this script to have the object with this component automatically look at the main camera. How can I do this? I don’t want to have to drag the camera into the target variable

// This complete script can be attached to a camera to make it 

// continuously point at another object.



// The target variable shows up as a property in the inspector. 

// Drag another object onto it to make the camera look at it.

var target : Transform; 



// Rotate the camera every frame so it keeps looking at the target 

function Update() {

transform.LookAt(target);

}

why not just drag the camera on to the variable?

fucntion Start () {
target = Camera.main.transform;
}

@ NerBoyStudios, Becuase its going to be on a prefab that gets spawned.

@appels Thanks for the help but I am getting compiler errors with the code you posted above.

even on a prefab that gets spawned you can assign the camera.
what error are you getting ?

With this code I get:

Assets/Scripts/lookatCamera.js(1,9): UCE0001: ‘;’ expected. Insert a semicolon at the end.
Assets/Scripts/lookatCamera.js(1,18): UCE0001: ‘;’ expected. Insert a semicolon at the end.
Assets/Scripts/lookatCamera.js(2,8): BCE0044: expecting :, found ‘=’.

fucntion Start () {

target = Camera.main.transform;

} 



function Update() {

transform.LookAt(target);

}

maybe the typo, your spelling of function , lol?

Lol thanks that fixed most of the error messages:
Now I am still getting:

Assets/Scripts/lookatCamera.js(6,18): BCE0005: Unknown identifier: ‘target’.

Spelling matters in programming.
fucntion != function
it’s not because i write some pseudo code that it allways is correct
you need to check it

Did you remember to add

var target : Transform;

At the top?

Here is where I am at, thanks again for all the help.
Error:
Assets/Scripts/lookatCamera.js(6,19): BCE0005: Unknown identifier: ‘target’.

function Start () {

var target = Camera.main.transform;

} 



function Update() {

transform.LookAt (target);

}

You have it defined in the start function , its not global to the script , its local to start alone.

var target : Transform;

function Start () {

target = Camera.main.transform;

} 



function Update() {

transform.LookAt (target);

}
var target:Transform;

function Start () {
    target = Camera.main.transform;
} 

function Update() {
    transform.LookAt (target);
}

Thats exactly what i wrote O.o , lol , yers just looks prettier. :stuck_out_tongue:

@willc

Thanks a bunch.

Well actually , appels gave you all the right info , just seems we needed to do a better job clarifying it for you. Anyways cool its working.

ah yes sorry, i didn’t see it :slight_smile:

Yes I have no scripting experience as you can tell :frowning: I will hit the docs soon.

transform.rotation.SetLookRotation(target);

:wink:

Except that target is a Transform, not a Vector3. That also makes it look the same direction as the camera, not towards it.