It keeps returning true!!!

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

I made a function that returns the value of either true or false based on weather the switch is pressed, but no mater what is keeps returning True and never false. Here is the code for it please help.

func _physics_process(delta):
if Input.is_action_just_pressed("Action") and g:
		if green == true:
			green = false
		else:
			green = true
if green == true:
	an.play("On")
	am = 1
if green == false:
	an.play("Off")
	am = 0
func is_on():
if  am == 1:
	return true
if am == 0:
	return false

I forgot to say the variable “g” is checking weather the player entered the area of the switch.

adsad | 2022-11-24 23:01

:bust_in_silhouette: Reply From: Redical

Hello!
I was remaking this to see why this was happening for you, but as I was typing it I realized that “else” is whenever the if statement is false, so maybe you need to change the else to something like this (this works perfectly for me):

extends Node2D

var green = false
var am = 0

func _physics_process(_delta):
if Input.is_action_just_pressed("Action"):
	if green == true:
		green = false
	elif green == false:   <----- Here is the part you need to change
		green = true
if green == true:
	# Play on animation
if green == false:
	# Play off animation

func is_on():
if am == 1:
	return true
if am == 0:
	return false

Hope this helps!

:bust_in_silhouette: Reply From: jgodfrey

I don’t see anything inherently wrong with your code, though it can be cleaned up a lot. Here’s an update that should be functionally the same as your original code, but shorter and cleaner (though, untested):

func _physics_process(delta):
    if Input.is_action_just_pressed("Action") and g:
        green = !green
    if green:
        an.play("On")
        am = 1
    else:
        an.play("Off")
        am = 0

func is_on():
    return am == 1

Now, a few questions.

  • What is the g variable in the Input logic and where is it set?
  • Do your animations (On and Off) play as intended?
  • Where do you call is_on() from? That call isn’t in the above code. Maybe show that code here?
  1. the g variable is just making sure the player is in the area of the switch it is set in the same code (I’ll give you code for that in a sec, I’m on my phone the code is on the computer)
  2. Yes the animations play correctly
    3)I use the code in another object, yes I added the switch to be public (again I’ll give you the code in a moment)

adsad | 2022-11-25 19:36

It seems the function works in the same code, but in other objects it keeps returning the first value that the variable was assigned…

adsad | 2022-11-25 19:57

Thanks, helped a lot :slight_smile:

adsad | 2022-11-25 21:05