- Home /
How do I load a Camera into a prefab that isn't in the scene?
When inspecting the prefab object (that isnt in the scene), I'm trying to add a Main Camera to the Script component, but there is no option to add it.
I know you can add the camera when your object is in the scene, but how do I add it when the object isn't in the scene? Is it possible to do in the script?
Thanks
Answer by AhmadSannan · Feb 16, 2018 at 09:29 PM
You can use the find function.
camera = GameObject.find("CameraNameGoesHere");
I tried: public Camera mainCam = GameObject.Find("$$anonymous$$ain Camera"); but it gives me the following error: "Cannot implicitly convert type 'UnityEngine.GameObject' to UnityEngine.Camera"
Cast the Find result as UnityEngine.Camera
.
But I still don't understand what you want to achive. $$anonymous$$ainCamera
means that it is a simple camera in the scene with a special Tag. Also, GameObject.Find
returns a reference o a GameObject into the scene.
You can read more about $$anonymous$$ainCamera
here and about GameObject.Find
here
Casting will not work, i.e. cannot cast a GameObject
to a Camera
. He has to use GetComponent<Camera>()
:
Camera mainCam = GameObject.Find("$$anonymous$$ain Camera").GetComponent<Camera>().
In your statement Camera mainCam = GameObject.Find("$$anonymous$$ain Camera");
you do 2 things"
You declare the variable
mainCam
to be of typeCamera
You assign the result of the
GameObject.Find
method to themainCam
variable
However, the GameObject.Find
method returns a GameObject
. So, you are trying to assign a GameObject
to a variable that can only accept a Camera
. Hence the error you are getting.
I think you will benefit to make use of the Unity Tutorials, especially the "Scripting" section.
@mrcyanga$$anonymous$$g all you need to do is that mainCam should be of type GameObject, and then if you want the camera u can use : mainCam.GetComponent() and now you have a reference to the camera component of the mainCam