I’m having trouble with child objects in a prefab. I created an empty gameobject, attached a script to it, dragged a camera into it, then dragged the gameobject into the Project panel to create a prefab out of it. Do I need to do anything special to define the camera as a child object? My code is…
transform.position = gui.docCamPos;
transform.camera.nearClipPlane = gui.docCamNear;
What am I doing wrong? Thanks.
No, all you have to do is drag the camera onto the empty object to parent the camera to the object. You don’t need any code to parent them unless you are creating the camera through scripts.
Seems like you really dragged another gameObject (a camera gameObject) into the main gameObjects hierarchy, didn’t you? In that case you code won’t work as transform.camera will as far as I know only return the camera on that very same gameObject, NOT in any of the children. So you have 2, or better 3 options:
- Attach the necessary camera script directly to that main gameObject. Plus any other necessary script for the camera to work of cause. I don’t really like that approach though since I personally prefer to keep cameras separated.
- Drag the camera gameObject into the main gameObject’s hierarchy like you did it now. In the script you mentioned use something like GetComponentInChildren() and assign the returned result to a variable which you can use to work with.
- Expose a public variable, drag the camera gameObject into the hierarchy, then drag the cam gameObject into the newly created variable slot in the inspector. Basically the same as the second option.
I’d go for 2 or 3.
thanks, option 2 made is clear for me. I had assumed if the camera was under the game oject in the hierarchy, you could access it easier. Thank you.