When i use "if" it appears "Unexpected if in class body"

Godot Version

Godot 4.2.1 Stable

Question

I made a code like this:
var playing = 1
var something = 0
if playing = 1: error: Unexpected “if” in class body.
something = 1 error: Unexpected “Indent” in class body.
Write in a CharacterBody2D node. Please help.

From Godot Docs

[GDScript] uses an indentation-based syntax similar to languages like Python.

Your post is not formatted to show the indentation in your code. Therefore, it is hard to help you debug your issue.

Could you please provide your entire script with formatting?

NOTE: I have not used GDScript myself and am basing my reply solely on the documentation of the language.

Hello esteemed catgg54,

The error is as it says - if cannot appear in a class body, as the body of a class is declarative only, not imperative. That is to say, you cannot use if in the body of a class, because that code will never run - it must appear in a function in gdscript.

What you might be intending to do is to use a ternary expression, which is valid in the declarative section of code.

var something = 1 if playing else 0 would be the correct way of writing this code.

Keep in mind that as written, there is no point to writing a ternary expression like this, unless the independent variable changes, such as by @export.

Please advise if you are in need of further assistance.

Regards,

2 Likes

can u help me im trying to make an enemy code and its not working
extends CollisionShape3D
@onready var nav =$“…/NavigationAgent3D”
var speed = 3.5
var gravity = 9.8
func _procces(delta):
if not is_on_floor(9.8):
velocity.y -= gravity * delta
else:
velocity.y -= 2
var next_location = nav . Get_next_path_position()
var current_location = Global_transform.origin
var new_velocity = (next_location - current_location).normalized() * speed
velocity=velocity.move_toward(new_velocity,o.25)
Move_and_slide()

func target_position(target):
nav.target_position=target