- Home /
How do I enable a camera from another GameObject?
Hello, I have a script that is trying to enable a child camera on a seperate object. For some reason I can not figure out how to do this successfully. I have tried a few different methods. E.G. Player.GetComponentInChildren().enabled = true;
But this returns an error Assets/Scripts/RandomMatchmaker.cs(39,47): error CS0246: The type or namespace name 'camera' could not be found. Are you missing a using directive or an assembly reference?
I guess what I am looking for is some sort of example in C#. If it helps I am attempting to make a photon networked game, and I need this code to Instantiate a player and activate it's camera.
Thanks, if there is anything else you need to know feel free to ask in the comments.
Answer by Crazydadz · Nov 07, 2013 at 01:33 AM
Just the basic idea:
GameObject player = Instantiate(PlayerGameObject); // Instantiate the player
Camera cameraInChildren = player.GetComponentInChildren<Camera>(); //Find the first Camera component in his children
cameraInChildren.enabled = true;
Wow, Thanks I used your code with some modifications and it worked perfectly!
Is there any way to find any other cameras that may also be attached to the GameObject? This answer works well for finding the first camera, but I'm unable to use it for other camera components.
@JerryC92 First of all, this is a really old thread. But to answer your question you could use GetComponentsInChildren<>(). The "s" is crucial.
The difference is GetComponentsInChildren returns an array of any specific type it can find in the parent objects children. This means if you want to reference a particular type in the array you'll have to use an index.
Camera[] camerasInChildren;
void Start (){
camerasInChildren = GetComponentsInChildren<Camera>();
}
And to reference a Camera I'd use this:
int useCameraIndex = 1;
Camera usedCamera;
Camera[] camerasInChildren;
void Start () {
usedCamera = cameraInChildren [useCameraIndex];
}