Alright, so what I’m trying to do with this script is to define a box (or rather, define a range of possible x and y coordinates) using Camera.ScreenToWorldPoint in a 2D game, as follows:
#pragma strict
var mainCam : Camera;
private var randomPointBox : Vector3 = new Vector3 (mainCam.ScreenToWorldPoint (new Vector3 (Screen.width * 1, 0, 0)).x, mainCam.ScreenToWorldPoint (new Vector3 (Screen.height *1, 0, 0)).y, 0);
private var pointB = Vector3;
function (Start)
{
pointB = new Vector3 (Random.Range (-randomPointBox.x, randomPointBox.x), Random.Range (-randomPointBox.y, randomPointBox.y), randomPointBox.z);
Debug.Log (pointB);
}
When I build or save the script, I get no errors, but when I attempt to drag my game object “MainCamera” into the “mainCam” variable I can’t, initially anyway. If I create a prefab of the “MainCamera” game object, I can drag it in, but when I run the game, point B prints as (0.0, 0.0, 0.0), and I get a null reference exception:
NullReferenceException: Object reference not set to an instance of an object
script…ctor () (at Assets/Scripts/Script.js:4)
which corresponds to line 4, my randomPointBox variable, and is therefore referring to “mainCam” not having an instance of the MainCamera, which makes total sense since I can only pull in the prefab of the main camera in the main Unity window.
I’ve watched a few tutorials where people use a similar technique, and just drag the main camera in from the hierarchy. What am I doing wrong?
Thanks again - I’ve only been with the Unity community for a few days and you’ve already been amazingly helpful. Hopefully soon I’ll be able to start answering questions, not just asking them.