Search code examples
c#unity-game-engineif-statementgameobject

Switching between two GameObjects when a key is pressed down


I wanted to do a little car game where you drive forward.

Now I wanted to code a script that when you press the "V" key the camera switch to the other camera and if you press again it goes back.

I have 2 Camera Gameobjects, one behind my Car and one in the drivers Seat.

One camera is always disabled, so you can always see through one camera.

Default is:

BehindC - Active FrontC - Disabled

I tried to tell the script that when I press the "V" key and the Behind Camera is active, the Behind Camera should be disabled and the Front Camera enabled.

The other way is the same, if the Behind Camera is not active and I press "V", the Front Camera gets disabled and the Behind Camera gets enabled.

public class CameraSwitcher : MonoBehaviour
{
    //BehindC is the Camera behind my Car
    public GameObject BehindC;

    //FrontC is the Camera in the drivers Seat
    public GameObject FrontC;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.V) && BehindC.activeInHierarchy)
        {
            
                BehindC.SetActive(false);
                FrontC.SetActive(true);

        }

        else
        {
           
                BehindC.SetActive(true);
                FrontC.SetActive(false);

        };

    }
}

When I tried to run this and press "V" the camera switch to the Front and back to the Behind Camera in milliseconds but you can see this.

I think that this if statement checks this too fast and switch the cameras fast as well because the "void Update" method is too fast.

Maybe I need something that delays this and allows it to check only 1 time in a second or something idk.

I would appreciate it if you can explain how you would solve this and how the code works, because im new to coding in C#.

Thanks


Solution

  • So your problem is that every frame it checks whether you pressed 'V' and if the BehindC object is active. If so you activate the FrontC object and deactivate the BehindC one. But then in the next frame it checks again an sees that the BehindC object is disabeld an jumps right to the else-Statement and enables it again.

    What you need to do is instead of an else-Statement use an else if -Statement and define that it only reactivate the BehindC object when 'V' is pressed and the FrontC object is active.

    Like this:

     void Update()
        {
            if (Input.GetKeyDown(KeyCode.V) && BehindC.activeInHierarchy)
            {
                
                    BehindC.SetActive(false);
                    FrontC.SetActive(true);
    
            }
    
            else if (Input.GetKeyDown(KeyCode.V) && FrontC.activeInHierarchy)
            {
               
                    BehindC.SetActive(true);
                    FrontC.SetActive(false);
    
            };
    
        }