简体   繁体   中英

how to access camera from another object in unity 3d

My script is attached to a character controller.

And i declared,

public Camera camera;

in class. In update function i given,

if(Input.GetMouseButtonDown(0)){ 
Ray ray = camera.ScreenPointToRay(Input.mousePosition); 
if (Physics.Raycast (ray, out hit3, 400.0F)){
    print(hit3.collider.gameObject.name); 
}
}

But i am getting error

"UnassignedReferenceException: 
The variable camera of 'characterScript' has not been assigned.
You probably need to assign the camera variable of the 
characterScript script in the inspector."

Help me with a good solution.

Thanks in Advance.

Drag and drop it to the variable in the UI, or add this bit in the script to do it automatically at startup:

void Start()
{ 
    camera = (Camera) GameObject.FindObjectOfType(typeof(Camera));
}

The cast might be redundant. Also, only works properly if you have exactly one camera.

You can also access the camera(s) from anywhere by using the following static variables of the Camera class:

Camera.current The camera we are currently rendering with.

Camera.main The first enabled camera tagged "MainCamera".

Camera.allCameras Returns all enabled cameras in the scene.

No need to look for it, the Camera class takes care of keeping track of its instances for us :)

hth.

Jerome

You didnt initialize your camera. you have to set it through the UI of unity3D. Just drag and drop the camera to the public parametr.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM