x


Why won't my script see the main camera?

This script is in a prefab. When I run the script, Unity says... "NullReferenceException: Object reference not set to an instance of an object"

function StartAtARandomSpot( zdepth : float )
{
    var campos : Vector3 = Vector3(Random.Range(0,scrWidth), scrHeight+80, zdepth);
    campos = Camera.main.ScreenToWorldPoint (campos);
    transform.position = campos;
    originalSpawnPoint = transform.position;    
}   

Any help would be greatly appreciated.

more ▼

asked Sep 23 '10 at 06:50 AM

Billamu gravatar image

Billamu
277 4 6 16

I've assumed the error is pointing to the line where you're calling 'Camera.main.ScreenToWorldPoint(campos);' If that's incorrect, please update your question to clarify! Cheers.

Sep 23 '10 at 07:09 AM Marowi
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Make sure that your camera is tagged as MainCamera, or "Camera.main" won't work. Otherwise, I've verified that your script is fine. Although, you could simplify it to:

function StartAtARandomSpot( zdepth : float )
{
    var campos : Vector3 = Vector3(Random.Range(0,scrWidth), scrHeight+80, zdepth);
    originalSpawnPoint = transform.position = Camera.main.ScreenToWorldPoint (campos);
}

(Note that you don't even need the campos variable, but for readability you could easily justify keeping it)

more ▼

answered Sep 23 '10 at 07:07 AM

Marowi gravatar image

Marowi
4.9k 4 14 53

Didn't realise you could double up your '='s there. Nice. My camera is tagged as MainCamera, but sadly the bug still remains.

Sep 23 '10 at 07:12 AM Billamu

Are you sure that the error is about the ScreenToWorldPoint line? If you comment it out, does the error still occur? If I put this code into an empty script on a new object, it works fine.

Sep 23 '10 at 07:30 AM Marowi

I've been tinkering with things and I've found that the prefabs were originally in the Heirachy; I was using an object pool on them. I've found that when I revert to instantiating the prefabs the problem goes away.

Sep 23 '10 at 08:35 AM Billamu

Glad you solved it - sorry that I couldn't help, beyond telling you that your script was fine!

Sep 23 '10 at 08:40 AM Marowi
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3314
x2979
x56
x34

asked: Sep 23 '10 at 06:50 AM

Seen: 1067 times

Last Updated: Sep 23 '10 at 06:50 AM