- Home /
Setting a variable : camera by using findObjectWithTag
So the problem I'm having is I have camera set up on the prefab of my turret. This prefab is then used to randomly spawn on a map. Now because its randomly spawned on the map I cannot attach cameras to the object directly. Well I can attach the camera on the prefab since it will never change what I want to do is include the main camera in this list of camera but I can't put it on the prefab. The turret is controlled by the player and I want him to be able to switch between the main view and turret view.
So what I'm trying to do is set my 2nd camera to an object tagged Main Camera. I'm not sure how to do this and have been looking all over the place for an answer.
here is my code that I have so far
var camera1 : Camera;
var camera2 : Camera;
private var t = 1;
function Update(){
if(t == 1)
{
camera1 = myObject.camera(GameObject.FindGameObjectWithTag("MainCamera"));
camera1.enabled = true;
camera2.enabled = false;
t = 2;
}
if(Input.GetButtonDown("1")){
if(camera1.enabled == true){
camera1.enabled = false;
camera2.enabled = true;
}
else{
camera1.enabled = true;
camera2.enabled = false;
}
}
}
this code does not work since GameObjects can not be changed to UnityEngine.Camera is there a way to do this by getting the camera and storing it into a variable.
Answer by syclamoth · Oct 25, 2011 at 12:38 AM
Instead of putting cameras on the turrets, why don't you just have empty transforms where the camera should go? Then, when you want to switch camera views, do something like this-
Camera.main.transform.parent = currentTurretTrans;
Camera.main.transform.localPosition = Vector3.zero;
Camera.main.transform.localRotation = Quaternion.identity;
Remember, if you're using this method, you need to put all of your various camera controller scripts on empty transforms, and then when you want to switch cameras, call that bit of code on the transform that you want to switch to.
Your answer
Follow this Question
Related Questions
Acessing scripts in other game objects with prefabs, without using GameObject.Find 1 Answer
How do I assign a prefab reference to a private variable? 1 Answer
Reinitialize prefab 0 Answers
Creating entities with some variations among them 0 Answers
GUI canvas' WorldSpace camera not copied into prefab 1 Answer