Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Switch camera with js

Discussion in 'Scripting' started by jonathantopf, Mar 23, 2011.

  1. jonathantopf

    jonathantopf

    Joined:
    Mar 17, 2011
    Posts:
    6
    H there, Im just starting with unity and wanted to try some simple scripting. Ive set up a simple scene with two cameras and I wanted to set up a button to toggle between them I.e. I press "b" and i look through one camera, and I press "n" and look through the other, heres the code I tried to cobble together which unsurprisingly isn't working, (I just attached the code to a game object assuming that that would make it evaluate?) any help would be greatly appreciated.

    Code (csharp):
    1.  
    2. var cam1 = GameObject.FindWithTag("MainCamera");
    3. var cam2 = GameObject.FindWithTag("testCam");
    4. var screenRect = Rect(0,0,100,100);
    5.  
    6. function Update () {
    7. if (Input.GetKey("b"))
    8.     {
    9.         DrawCamera(position:screenRect, camera:cam1, drawMode:DrawCameraMode=DrawCameraMode.normal):void;
    10.     }
    11.  
    12.     if (Input.GetKey("n"))
    13.         DrawCamera(position:screenRect, camera:cam2, drawMode:DrawCameraMode=DrawCameraMode.normal):void;
    14.  
    15.     {
    16.     }
    17. }
    18.  
    best, jon
     
  2. colbra

    colbra

    Joined:
    Jun 14, 2009
    Posts:
    32
    i simply just switch the position, exp
    var campositions : Transform[];

    function Update (){
    if (Input.GetKey("b")){
    Camera.main.transform.position = campositions[1].position;
    }
    if (Input.GetKey("n")){
    Camera.main.transform.position = campositions[2].position;
    }
    }

    this way you can have as many as you want
     
  3. jonathantopf

    jonathantopf

    Joined:
    Mar 17, 2011
    Posts:
    6
    Thats clever, i didn't think of that. Would this approach still be efficient if each camera had a different behaviour, I.e. I have one camera as a first person camera and one as say a security camera?

    Thanks for the quick reply.

    jon
     
  4. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    It's actually quite easy to switch cameras in Unity:

    Code (csharp):
    1. var camera1:Camera;
    2. var camera2:Camera;
    3.  
    4. function Start()
    5. {
    6. camera1.enabled = true;
    7. camera2.enabled = false;
    8. }
    9.  
    10. function Update()
    11. {
    12. if (Input.GetKeyDown("b"))
    13. {
    14. camera2.enabled = true;
    15. camera1.enabled = false;
    16. }
    17.  
    18. else if (Input.GetKeyDown("n"))
    19. {
    20. camera2.enabled = false;
    21. camera1.enabled = true;
    22. }
    23. }
     
  5. jonathantopf

    jonathantopf

    Joined:
    Mar 17, 2011
    Posts:
    6
    i knew it had to be simple, in that case when you defined the variables like this:
    Code (csharp):
    1. var camera1:Camera;
    2. var camera2:Camera;
    What should 'Camera' be, should it be the name of the camera or the cameras tag, I'm not so sure on how to address these kind of things, its all new to me.

    Thanks, j
     
  6. kiranmaya

    kiranmaya

    Joined:
    May 27, 2010
    Posts:
    218
    you should drag and drop camera objects into script inspector. simple
    this is best option,instead of finding with name or tag
     
  7. billykater

    billykater

    Joined:
    Mar 12, 2011
    Posts:
    326
    the :Camera specifies the type of the variable. Just like you have int, string, bool variables you can have "bigger objects" like camera.

    Normally the type can be inferred by your assignment like the following.
    Code (csharp):
    1.  
    2. var a = true;
    3. //actually translates to
    4. var a : Boolean = true;
    5.  
    Code (csharp):
    1.  
    2. var screenRect = Rect(0,0,100,100);
    3. //translates to
    4. var screenRect:Rect = Rect(0,0,100,100);
    5.  
    An added bonus from unity is that if you specify a type unity knows like camera you can visually set the variable inside the inspector. So if you put Cameras A,B and C into your scene you can select any of these cameras in the inspector as camera1 or camera2.
     
  8. jonathantopf

    jonathantopf

    Joined:
    Mar 17, 2011
    Posts:
    6
    Wow thats totally genius, I love it. Now everything is working fine. Just out of interest if i wanted to address a camera directly from within the script how would I do that?
    j
     
  9. colbra

    colbra

    Joined:
    Jun 14, 2009
    Posts:
    32
    yeah just make that position object do what ever, for instance i make a cameraattributes.js if i want it to do something
     
  10. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    You could use Gameobject.Find to address the camera, but Find is not particularly efficient. If you know you're going to use two particular cameras (or any gameobjects for that matter) it's better to store them as variables. You could also assign the camera to a variable in the Start() function as well. That way you're only finding the object once instead of on every button press.

    By the way, if you want to toggle the cameras on a single button you can do this:

    Code (csharp):
    1. var camera1 : Camera;
    2. var camera2 : Camera;
    3. private var cameraSwitch : boolean = true;
    4.  
    5. function Update()
    6. {
    7. if (Input.GetKeyDown("n"))
    8. {
    9. cameraSwitch = !cameraSwitch;
    10. camera1.enabled = cameraSwitch;
    11. camera2.enabled = !cameraSwitch;
    12. }
    13. }
     
  11. billykater

    billykater

    Joined:
    Mar 12, 2011
    Posts:
    326
    Code (csharp):
    1.  
    2. cameraObject = GameObject.Find(nameOfCamera);
    3. camera1 = cameraObject.GetComponent("Camera");
    4.  
    This code will get you the camera component of the specified camera object.

    As the others said before don't use this kind of lookup inside any function that gets called each frame.
     
  12. jonathantopf

    jonathantopf

    Joined:
    Mar 17, 2011
    Posts:
    6
    thanks for all the replies, I'm really impressed with how many and how quick the responses are. I'm getting the effect I want now which is amazing as i only installed unity yesterday! Although I'm begining to think that my js is a bit rough, im not sure exactly what the ':' operator does for example, i'd better go and read some more.

    Many thanks, j
     
  13. CheyTac

    CheyTac

    Joined:
    Feb 17, 2011
    Posts:
    71
    var camera1: Transform
    var camera2: Transform;

    function Start()
    {
    camera1.enabled = true;
    camera2.enabled = false;
    }

    function Update()
    {
    if (Input.GetKeyDown("b"))
    {
    camera2.enabled = true;
    camera1.enabled = false;
    }

    else if (Input.GetKeyDown("n"))
    {
    camera2.enabled = false;
    camera1.enabled = true;
    }
    }
     
  14. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    Hey CheyTac. Just to let you know, declaring your cameras as Transforms isn't going to work as you've coded it above. You'd have to drill down through GetComponent as in billykater's example. You're better off declaring cameras as:
    Code (csharp):
    1. var myCam : Camera;
    Then you can address the camera component directly.
     
  15. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    Hi, I really like the simplicity of tool55's script and how it allows you to add the cameras directly in the inspector. I am trying to implement this using a 3 or more camera system. I've added a third variable and attached the camera in the inspector but it still only switches between two cameras. Is this because of the boolean? Can anyone see what I'm doing wrong?

    Here is my script:

    var camera1 : Camera;
    var camera2 : Camera;
    var camera3 : Camera;
    private var cameraSwitch : boolean = true;

    function Update()
    {
    if (Input.GetKeyDown("n"))
    {
    cameraSwitch = !cameraSwitch;
    camera1.enabled = cameraSwitch;
    camera2.enabled = cameraSwitch;
    camera2.enabled = !cameraSwitch;
    }
    }
     
    Last edited: Oct 13, 2011
  16. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    With 3 cameras you'll probably want to put them in an array. The script you posted switches between two cameras because the last line essentially undoes the line before it. Boolean's are just true/false so only good for switching between two states or two objects, at least in this simple form. A built in array would work fine. Then iterate through them. I'll try to post a script later if someone doesn't beat me to it :)

    Code (csharp):
    1. var myCameras : Camera [];
    2.  
     
  17. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    Thank you for your quick reply tool55. Sorry, but by array do you mean that the cameras need to be assigned inside the [] brackets? :S
    I'm still only learning scripting.

    I have also tried another Multiple Camera system written in C# here -->

    http://www.unifycommunity.com/wiki/index.php?title=SwitchCamera

    However the problem with that one is that it activates the first camera automatically on runtime, whereas I need it to only activate when pressing the key. I'm using this to switch my player cameras and my vehicle cameras at separate times but using the same key "c". I've put together a diagram -->

    http://i1216.photobucket.com/albums/dd368/Pilot_09/Camera_Setup01.png

    Hopefully that explains better what I'm trying to do :)
     
    Last edited: Oct 13, 2011
  18. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    Here is a basic example of a camera switcher... it allows you to press the "N" key to cycle through the list of cameras that you assign in the inspector. It also allows you to press a number and get a corresponding camera.

    Its basic, but it illustrates an easy camera controller. It also contains error checkers, like if you don't assign any cameras to the array, it wont work.
    Code (csharp):
    1.  
    2. var cameras : Camera[];
    3. var currentCamera = 0;
    4.  
    5. function Start () {
    6.     if(cameras.Length == 0) return;
    7.     if(currentCamera < 0) currentCamera = 0;
    8.     EnableCamera(currentCamera);
    9. }
    10.  
    11. function Update(){
    12.     if(cameras.Length == 0) return;
    13.     if(Input.GetKeyDown(KeyCode.N)) NextCamera();
    14.    
    15.     if(Input.GetKeyDown(KeyCode.Alpha1))EnableCamera(0);
    16.     if(Input.GetKeyDown(KeyCode.Alpha2))EnableCamera(1);
    17.     if(Input.GetKeyDown(KeyCode.Alpha3))EnableCamera(2);
    18.     if(Input.GetKeyDown(KeyCode.Alpha4))EnableCamera(3);
    19.     if(Input.GetKeyDown(KeyCode.Alpha5))EnableCamera(4);
    20.     if(Input.GetKeyDown(KeyCode.Alpha6))EnableCamera(5);
    21.     if(Input.GetKeyDown(KeyCode.Alpha7))EnableCamera(6);
    22.     if(Input.GetKeyDown(KeyCode.Alpha8))EnableCamera(7);
    23.     if(Input.GetKeyDown(KeyCode.Alpha9))EnableCamera(8);
    24.     if(Input.GetKeyDown(KeyCode.Alpha0))EnableCamera(9);
    25. }
    26.  
    27. function NextCamera(){
    28.     DisableAllCameras();
    29.     currentCamera = (currentCamera + 1) % cameras.Length;
    30.     cameras[currentCamera].enabled = true;
    31. }
    32.  
    33. function EnableCamera(num : int){
    34.     DisableAllCameras();
    35.     currentCamera = num % cameras.Length;
    36.     cameras[currentCamera].enabled = true;
    37. }
    38.  
    39. function DisableAllCameras(){
    40.     for(var i=0; i<cameras.Length; i++)
    41.         cameras[i].enabled = false;
    42. }
    43.  
     
  19. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    With the built in arrays you will see the array appear in the inspector. No need to put the cameras in the brackets. It will ask you for the array length (in your case 3, but it could be 100 or whatever) and you'll instantly get a drop down list with empty camera slots. Just drag and drop your cameras into the slots to assign them to the array. BigMisterB's switcher should be okay. You may not need all the if statements if you don't want to assign separate keys on top of the N key. We'll see if we can simplify it for you. Just no time this minute. I'll try to look at it later today.
     
  20. kiranmaya

    kiranmaya

    Joined:
    May 27, 2010
    Posts:
    218
    Code (csharp):
    1.  
    2.  
    3. var myCameras : Camera [];
    4. var i:int =0;
    5. function Update()
    6. {
    7. if(Input.GetKeyDown(Keycode.C))
    8. {
    9. i++;
    10. }
    11. if( i > myCameras.length )
    12. {
    13. i=0;
    14. }
    15.  
    16. for(var j:int  ; j<=myCameras.length;j++ )
    17. {
    18. if(j ==i )
    19. {
    20. myCameras[j].enabled = true;
    21. }
    22. else
    23. {
    24. myCameras[j].enabled = false;
    25. }
    26. }
    27.  
    28.  
    29.  
    30. }
    31.  
    32.  
    drag and drop the cameras to this script
    hope this will work .
     
  21. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    Hi guys, thank you so much for your help, really appreciate it.

    Apologies for the late reply, I have been trying all day to get this working, but still little success :(

    I have implemented the script (attached it to an player which has the character controller and other scripts parented) and it switches the cameras very well, sincerely, thank you for your efforts BigMisterB and tool55 (and Kiranmaya, I couldn't get your script to work though). However the problem is, how do I implement this (using the same key trigger) when I have two gameobjects, each with their own separate cameras eg. Player go with an FPS TPS camera, Vehicle go with a trailing camera, bumper dashboard cameras. At the moment, when I press the trigger key it changes to the cameras assigned in the array irrespective of which gameobject is currently active, allowing the player to switch to the vehicle cameras without actually being in the vehicle. Would it be possible to somehow reference the cameras to their gameobject? Or to to have the vehicle cameras deactivated unless their gameobject the active one? I'm not sure which approach would be the best to take.

    I'm sorry if I am sounding greedy, I am just trying to learn as best as I can. My assets folder is full of so many camera switching scripts! I have tried and implemented many different camera systems in both js and C#, however I always seem to get stuck on this one same thing. If you have the time, please, I would appreciate a little more advice. Thank you
     
    Last edited: Oct 14, 2011
  22. Krizz

    Krizz

    Joined:
    Mar 1, 2011
    Posts:
    7
    When i saw this thread i wanted to do a camera switch code by my self :)
    For me C# is easier, so my code is in C#.. hope it wont be trouble for you..

    I added a fuction for the AudioListener aswell, it might not be optimised but anyway its there :)
    sry for bad eng :)

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class CamSwitch : MonoBehaviour {
    6.    
    7.     public AudioListener[] Mics;
    8.     public Camera[] Cams;
    9.     private int CurCam;
    10.     private int CurMic;
    11.    
    12.     void Start () {
    13.        
    14.         CurCam = 0;
    15.         CurMic = 0;
    16.         EnaCam(CurCam);
    17.         EnaMic(CurMic);
    18.     }
    19.    
    20.     void Update () {
    21.        
    22.         if (Input.GetKeyDown(KeyCode.M)) {
    23.             NextCam();
    24.             NextMic();
    25.         }
    26.     }
    27.    
    28.     void EnaCam (int IdCam) {
    29.         if (Cams[IdCam] != null)
    30.             foreach (Camera C in Cams)
    31.                 C.enabled = false;
    32.         Cams[IdCam].enabled = true;
    33.     }
    34.    
    35.     void EnaMic (int IdMic) {
    36.         if (Mics[IdMic] != null)
    37.             foreach (AudioListener M in Mics)
    38.                 M.enabled = false;
    39.         Mics[IdMic].enabled = true;
    40.     }
    41.    
    42.     void NextCam () {
    43.         if (CurCam >= Cams.Length - 1)
    44.             CurCam = 0;
    45.         else
    46.             CurCam++;
    47.         EnaCam(CurCam);
    48.     }
    49.    
    50.     void NextMic () {
    51.         if (CurMic >= Mics.Length - 1)
    52.             CurMic = 0;
    53.         else
    54.             CurMic++;
    55.         EnaMic(CurMic);
    56.     }
    57. }
    58.  
     
    Last edited: Oct 14, 2011
  23. Krizz

    Krizz

    Joined:
    Mar 1, 2011
    Posts:
    7
    I think you can prevent this for hapening with a boolean.

    So my guessing is, if ur not in a car you have a bool "walk" thats = true. and you can only switch cameras in a array thats activ when bool "walk" is true.
    But when you enter a car you set bool "walk"=false and bool "car"=true and have that array of cameras when ur driving a car. in this way you can even add arrays for cameras for boats, planes etc.

    Remember that this is my guessing, i have never done this. and hope that misterB and tool55 givs better answer.
    Hope you understand me and my not so good eng :)
     
  24. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    Thank you for your input Krizz, and don't worry you're English is fine :)

    I have tried your script and it works really well for the switching with one gameobject. I also like the audio listener addition since many other scripts do not have this, and I am always left with a "too many audio listeners" warning.

    I think you are definitely right about the boolean. I have seen other scripts use this also but for some reason it didn't work when I tested them, ALL the cameras kept switching. And since at this stage I only know how to piece scripts together (not write them myself) I am not quite sure how to implement the boolean in your above script. But it sounds promising.

    I am wondering if a collider could be used as an ontrigger to determine which cameras can be switched, that way I could add all the non player cameras into one array and then simply activate the relevant ones when the player is in the gameobject's collider. I am not sure how to write such a script though :(
     
  25. Krizz

    Krizz

    Joined:
    Mar 1, 2011
    Posts:
    7
    guess my eng is fine then :)
    I will try some simpel method first for the boolean to activate diffrent arrays.
    i'll be back soon i hope with a working solution :)

    EDIT..

    yet again Krizz strikes with a phenomenal piece of code, kidding haha
    got it working anyways:)
    All you have to do is change the bool "InCar" to be activated only when you are in the car, and not only when you press E.
    BUT there is one problem here.. this code only works with one car. unless your character only have access to one car.
    If you are making a "GTA" type game where you have access to 100+ cars, you need to make an array to all of them.
    and that is performance hungary. (i will try to make one more advanced code to sort this out) but i kinda need help then.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. using System.Collections;
    5.  
    6.  
    7.  
    8. public class CamMultiSwitch : MonoBehaviour {
    9.  
    10.    
    11.  
    12.     public AudioListener[] CarMics;
    13.  
    14.     public AudioListener[] Mics;
    15.  
    16.     public Camera[] CarCams;
    17.  
    18.     public Camera[] Cams;
    19.  
    20.     private int CurCam;
    21.  
    22.     private int CurCarCam;
    23.  
    24.     private int CurMic;
    25.  
    26.     private int CurCarMic;
    27.  
    28.     public bool InCar;
    29.  
    30.    
    31.  
    32.     void Start () {
    33.  
    34.        
    35.  
    36.         CurCam = 0;
    37.  
    38.         CurCarCam = 0;
    39.  
    40.         CurMic = 0;
    41.  
    42.         CurCarMic = 0;
    43.  
    44.         EnaCam(CurCam, CurCarCam);
    45.  
    46.         EnaMic(CurMic, CurCarMic);
    47.  
    48.         InCar = false;
    49.  
    50.     }
    51.  
    52.    
    53.  
    54.     void Update () {
    55.  
    56.        
    57.  
    58.         if (Input.GetKeyDown(KeyCode.E)) {
    59.  
    60.             if (InCar == false)
    61.  
    62.                 InCar = true;
    63.  
    64.             else
    65.  
    66.                 InCar = false;
    67.  
    68.             EnaCam(CurCam, CurCarCam);
    69.  
    70.             EnaMic(CurMic, CurCarMic);
    71.  
    72.         }
    73.  
    74.        
    75.  
    76.         if (Input.GetKeyDown(KeyCode.M)) {
    77.  
    78.             NextCam();
    79.  
    80.             NextMic();
    81.  
    82.         }
    83.  
    84.     }
    85.  
    86.    
    87.  
    88.     void EnaCam (int IdCam, int IdCarCam) {
    89.  
    90.         if (Cams[IdCam]  CarCams[IdCarCam] != null) {
    91.  
    92.             foreach (Camera C in Cams)
    93.  
    94.                 C.enabled = false;
    95.  
    96.             foreach (Camera C in CarCams)
    97.  
    98.                 C.enabled = false;
    99.  
    100.         }
    101.  
    102.         if (InCar == false)
    103.  
    104.             Cams[IdCam].enabled = true;
    105.  
    106.         else
    107.  
    108.             Cams[IdCam].enabled = false;
    109.  
    110.        
    111.  
    112.         if (InCar == true)
    113.  
    114.             CarCams[IdCarCam].enabled = true;
    115.  
    116.         else
    117.  
    118.             CarCams[IdCarCam].enabled = false;
    119.  
    120.     }
    121.  
    122.    
    123.  
    124.     void EnaMic (int IdMic, int IdCarMic) {
    125.  
    126.         if (Mics[IdMic]  CarMics[IdCarMic] != null)
    127.  
    128.             foreach (AudioListener M in Mics)
    129.  
    130.                 M.enabled = false;
    131.  
    132.             foreach (AudioListener M in CarMics)
    133.  
    134.                 M.enabled = false;
    135.  
    136.         if (InCar == false)
    137.  
    138.             Mics[IdMic].enabled = true;
    139.  
    140.         else
    141.  
    142.             Mics[IdMic].enabled = false;
    143.  
    144.        
    145.  
    146.         if (InCar == true)
    147.  
    148.             CarMics[IdCarMic].enabled = true;
    149.  
    150.         else
    151.  
    152.             CarMics[IdCarMic].enabled = false;
    153.  
    154.     }
    155.  
    156.    
    157.  
    158.     void NextCam () {
    159.  
    160.         if (InCar == false)
    161.  
    162.             if (CurCam >= Cams.Length - 1)
    163.  
    164.                 CurCam = 0;
    165.  
    166.             else
    167.  
    168.                 CurCam++;
    169.  
    170.         else
    171.  
    172.             if (CurCarCam >= CarCams.Length - 1)
    173.  
    174.                 CurCarCam = 0;
    175.  
    176.             else
    177.  
    178.                 CurCarCam++;
    179.  
    180.         EnaCam(CurCam, CurCarCam);
    181.  
    182.     }
    183.  
    184.    
    185.  
    186.     void NextMic () {
    187.  
    188.         if (InCar == false)
    189.  
    190.             if (CurMic >= Mics.Length - 1)
    191.  
    192.                 CurMic = 0;
    193.  
    194.             else
    195.  
    196.                 CurMic++;
    197.  
    198.         else
    199.  
    200.             if (CurCarMic >= CarMics.Length - 1)
    201.  
    202.                 CurCarMic = 0;
    203.  
    204.             else
    205.  
    206.                 CurCarMic++;
    207.  
    208.         EnaMic(CurMic, CurCarMic);
    209.  
    210.     }
    211.  
    212. }
    213.  
     
    Last edited: Oct 16, 2011
  26. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    @Krizz It is definitely fine :)
    And apologies for not replying back, I have been having very severe weather here since the start of the week and been without internet until tonight!
    Again, thank you so much for your efforts, but indeed I do need a system that works with multiple vehicles. But don't worry, I have managed to implement your earlier script perfectly alongside the script listed below. Me and another forum member are trying to resolve one final issue before this system is 100% complete. If you would like to help here is the link to our Unity Answer page, but I'll give you a quick overview. Here is the script:
    // add your player and camera
    var PlayerA : GameObject;
    var PlayerB : GameObject;
    var PlayerACam : GameObject;
    var PlayerBCam : GameObject;

    function Start (){
    PlayerA.active = true;
    PlayerB.active = false;
    PlayerACam.camera.enabled = true;
    PlayerBCam.camera.enabled = false;
    }

    function Update (){
    // Hit 1 key to PlayerA playable
    if(Input.GetKeyUp("1")){
    PlayerA.active = true;
    PlayerB.active = false;
    PlayerACam.camera.enabled = true;
    PlayerBCam.camera.enabled = false;
    }

    // Hit 2 key to PlayerB playable
    if(Input.GetKeyUp("2")){
    PlayerB.active = true;
    PlayerA.active = false;
    PlayerBCam.camera.enabled = true;
    PlayerACam.camera.enabled = false;
    }
    }

    It is very straight forward, basically by switching controllers using the "1" and "2" keys only the cameras related to the active gameobject are enabled, which means they can easily be switched through using your script without interference. What we're trying to do is simple - make it that you can only switch controllers (from player to vehicle for example) when we are inside the box collider of the gameobject we are switching to. Otherwise one can switch from player to vehicle (or vice versa) whether they are standing next to the car, or on the other side of town. In this way, by using the box collider as a trigger it is easier to select which particular vehicle the player wants to "climb into".

    I understand that this is slightly branching into another direction, but if you do have anymore suggestions we would really appreciate your input. Especially since you have been so helpful already.

    Thank you again Krizz. And keep up the great work!
     
    Last edited: Oct 19, 2011
  27. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    Haven't looked too closely at your script but a couple of suggestions come to mind on first glance:

    1. You might want to declare you cameras as Camera; not GameObject; Saves some drilling down through hierarchy.
    2. It would probably be good to use an else if statement instead of an if statement for your "Hit 2 to PlayerB playable" statement. What if someone presses both keys? You could get some glitchy behavior. With an "else if" you'd be making the Key 1 the default.
    3. I'm not sure you need to enable the cameras at all if they're children of the Player. When you make an object inactive, you make the children inactive, too. Someone can correct me if I'm wrong on this.
    4. And you might be able to use a boolean to make the switching code more compact since there are only two players.
    5. Lastly, you talk about using a trigger to tell when the player is near the car. You might want to use raycasting instead. The reason for this is that then the player not only has to be near the car, he has to be facing the car. You can set the raycast to 1 meter or whatever you choose. This may not be an issue for you since you have the player press a button to switch to the car, but it could be a problem if it's automatic. Another example would be opening a door. You want the player facing the door to open it, not just running by.

    Anyway, just some thoughts on a quick glance.
     
  28. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    Hi, thank you for having a look.

    1. Yes you are right, this does help when looking through the hierarchy. Thanks
    2. Yes definitely. I haven't completely finished this part of the script as i'm trying to test and finalize the more complex functionality first
    3. All the cameras aren't in fact parented to the player, the main cameras follow each player via script (rather than parenting), which is why I have done this in this way
    4. There are only two players for testing purposes. I plan to have more than one vehicle which is why I have been avoiding booleans
    5. I have tried what you proposed with the raycast but it basically doesn't work for the following reasons:
    When the player is close to the vehicle, they press a key and enter the vehicle (and trigger collider) via animation, upon which the controls change to the vehicle. The raycast does work when approaching the vehicle, however once inside I need a similar technique to exit the vehicle, whereby the user presses a key which changes controls back to the player and exits them from the vehicle via animation. Since the player is already inside the collider the raycast cannot create the necessary trigger.

    I have found a script which I think is close to the functionality I would need:

    function OnCollisionStay (other : Collider) {
    if( Input.GetKeyDown( "f" ) )
    {
    audio.Play(03);
    }
    }

    However this one is for playing audio, and also doesn't check for a tag which I would need to add. I have tried to incorporate this into my script, but i get a number of errors:

    // add your player and camera
    var PlayerA : GameObject;
    var PlayerB : GameObject;
    var PlayerACam : GameObject;
    var PlayerBCam : GameObject;

    function Start (){
    PlayerA.active = true;
    PlayerB.active = false;
    PlayerACam.camera.enabled = true;
    PlayerBCam.camera.enabled = false;
    }

    function Update (){
    // Hit 1 key to PlayerA playable
    if(Input.GetKeyUp("1")){
    PlayerA.active = true;
    PlayerB.active = false;
    PlayerACam.camera.enabled = true;
    PlayerBCam.camera.enabled = false;
    }

    function OnCollisionStay (other : Collider) {
    if( Input.GetKeyDown( "2" ) )
    {
    PlayerB.active = true;
    PlayerA.active = false;
    PlayerBCam.camera.enabled = true;
    PlayerACam.camera.enabled = false;
    }
    }
    }

    What am I doing wrong?
     
  29. cgf

    cgf

    Joined:
    Oct 16, 2011
    Posts:
    25
    If i understand you right you could have 4 states:
    1. outside vehicle -> on "f" enter vehicle if raycast hits a vehicle in front of you
    2. entering vehicle -> non-interactive animation
    3. inside vehicle -> on "f" exit vehicle
    4. exiting vehicle -> non-interactive animation

    On start/end of entering/exiting you can switch controllers/cameras/... accordingly and you'd only raycast on "f" in state 1.
     
    Last edited: Oct 20, 2011
  30. Pilot

    Pilot

    Joined:
    Oct 13, 2011
    Posts:
    20
    Sure that sounds correct, you could definitely break it down in that way.
    The problem is that with my scripting knowledge I don't know how I would go about setting 4 separate states in that way.
    This is why I have tried to keep to the simple: OnTriggerEnter/OnTriggerStay/OnCollisionStay OnTriggerExit, which appears to be the simplest functionality specific for this sort of situation.
    But thank you, appreciate your input :)
     
  31. Chuckler

    Chuckler

    Joined:
    Mar 15, 2012
    Posts:
    4
    Saweet! :D
     
  32. yaelka

    yaelka

    Joined:
    Jan 3, 2017
    Posts:
    1
    I can't get any of these scripts to work. Is there a newer script for this? I'm using Unity 5.4.3 :)