How to switch between cameras with set_current()?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By danoli

Hi,
I’m using Godot 3.1.1 and I need to switch between two cameras when a button is pressed. I was trying to use set_current to switch between them but it doesn’t seem to work. I have the following code:

extends Spatial

func _ready():
    pass

func _input(event):
    if event.is_action_pressed("switch"):
        $Camera1.set_current(not $Camera1.current)
        $Camera2.set_current(not $Camera2.current)

When I print the state before and after the set_current() function, it doesn’t change so the cameras are not switching. If I instead do it like the code below, it works.

func _input(event):
if event.is_action_pressed("switch"):
    if $Camera1.is_current():
        $Camera1.clear_current(true)
    else:
        $Camera2.clear_current(true)

Did I miss something about how set_current works()? Is it not supposed to be used like this?

:bust_in_silhouette: Reply From: kidscancode

Making one camera current automatically clears the current one. The problem with your first code block is that you can’t have no current camera. The first line is trying to set Camera1.current to false, without another camera to be selected.

Calling make_current() or clear_current() is the way to go.

Also, note that set_current() is not the preferred method. Set/get methods are not necessary (and don’t show up in autocomplete) because direct property access is preferred:

$Camera1.current = true

I get it now why it doesn’t work. I’ll keep the second code snippet then. Thanks.

danoli | 2019-08-20 16:34

can you explain it further

Xero | 2020-06-12 02:33

So I have been trying to use this to implement a sort of top down camera so I can see what my animations for my characterbody3d look like (note this camera is a static camera), and when I try to swap back to my FPP camera, it bugs out and gives the error-
Attempt to call function ‘clear_current’ in base ‘null instance’ on ‘null instance’.

Do you know a fix for this @kidscancode?’

NewbieGodotUser | 2022-09-12 19:04

null instance is what you get when you give get_node() an invalid path. Sounds like whatever you’re calling clear_current() on is invalid.

kidscancode | 2022-09-13 01:55

Got it! Thanks for the help!

NewbieGodotUser | 2022-09-13 18:21

How do i write the code if i want to switch between 3 or more cameras?

Isswas | 2022-11-25 16:08