Search Unity

change game object (cam) during runtime

Discussion in 'Scripting' started by Krodil, Dec 5, 2011.

  1. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
    Hey,
    I am pretty sure this answer is trivial, but I simplycant sort it out.

    I have in C# a variable where I drag in which camera is responsible for raycasts.
    public Camera raycastCamera;
    During runtime, I shift camera, hence I now want another cam to sort the raycasting for me.

    How do you replace in this case the main cam with lets say 'TopCam' in the variable during runtime?
     
    Last edited: Dec 5, 2011
  2. MWr

    MWr

    Joined:
    Apr 30, 2010
    Posts:
    15
    Hi,

    You need to first find the GameObject of the camera and then get the camera component from that GameObject.

    So to find a camera called TopCam you would do:

    Code (csharp):
    1.  
    2.         GameObject cameraObject = GameObject.Find("TopCam");
    3.         raycastCamera = cameraObject.camera;
    4.        
    5.  
    There are a number of other ways you could do it. You could have a public variable for each camera you are going to want to use and then set those up in the inspector and then just point your main variable to the one you want to use.

    Or you could use linq to search through the Camera.allCameras array. Which is a array of all the active cameras in the scene. So you could use something like:

    Code (csharp):
    1.  
    2.               raycastCamera =  Camera.allCameras.Where(cam => cam.name == "TopCam").First();
    3.  
    Note you would need to add "using System.Linq;" to the top of your c# file.

    I hope I understood your question correctly.
     
    Last edited: Dec 5, 2011
  3. INSANE_BR

    INSANE_BR

    Joined:
    Sep 10, 2009
    Posts:
    142
    I think the best way to do that would somehow use the code you made to switch cameras to also switch you raycastCamera variable.
     
  4. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
    How would you assign another camera to a var during run?
    The scipt I wish to change the raycastCam in is not attached to the cams, they could be if its needed..
    I have been struggling with this since last week :)
     
  5. INSANE_BR

    INSANE_BR

    Joined:
    Sep 10, 2009
    Posts:
    142
    I could make a list of cameras and drag all cameras that could be responsible for raycasts.

    Code (csharp):
    1.  
    2. public Camera[] raycastCamera;
    3.