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