- Home /
Parenting a camera to different objects with input?
Let's say I have two characters on a scene, and I can switch control between them. Assume that when I press Q, I control Char1, and when I press E, I control Char2. How can I get the camera to check which character is being controlled, so that it pans to and follows that character?
If I was making this game without Unity, I would make an array of playable characters and each character would have a "isBeingControlled" bool, and the camera would cycle through the array of playable characters, checking each one's bool. But in Unity, I don't know how to access another object from a script attached to the camera.
If your camera has a behaviour script to follow a gameobject you can create a List or Array and then switch between them let the camera behaviour do its job automaticaly.
That way you don't even need to check the bool isBeingControlled (well only if you don't want that others move as well)
ps: to access another object simply call this in start():
anObject = Gameobject.Find("OBJECTNA$$anonymous$$E").GetComponent < TheScriptNA$$anonymous$$E >();
You can also find more of a kind and store them in arrays.
Thank you, that function will also be useful. But I can only choose one correct answer... which is weird, actually?
No problem m8 I just converted my statement to a comment so others can see it too :)
Answer by JoaoOliveira · Jan 13, 2014 at 03:47 PM
Following your idea: You create a "MyCharacterScript" with a public property "isBeingControlled" and attach it to both characters. On the script that is attached to your camera you add a public MyCharacterScript[] field. From this point on you can edit this array in the editor. In your case, you want to set its size to 2. Then you just need to drag and drop your characters to the array positions and you will have access to them.
Keep in mind that other solutions might be reasonable. For instance, having 2 cameras and having a script with a reference to both of them. Depending on the pressed key, you activate and deactivate the correct cameras.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130252im_/https://answers.unity.com/themes/thub/images/avi.jpg)