Unexpected "Identifier" in class body error when using export in Godot 4.0.2
Asked Answered
A

1

8

I'm currently working on a project in Godot 4.0.2 and I'm having trouble using the export keyword in my scripts. Every time I try to use it, I get an "Unexpected 'Identifier' in class body" error. I'm not sure what's causing this error or how to fix it.

Here's an example of the code I'm trying to use:

extends Node2D

export var growth_time = 10.0 var is_grown = false

I've tried searching for solutions online, but I haven't found anything that has helped. Can anyone explain what's causing this error and how to fix it? Additionally, is there anything I can do to prevent this error from occurring in the future?

click here for image

Ancient answered 30/4, 2023 at 11:57 Comment(0)
A
8

This is a variable called growth_time, its type is Variant:

# Godot 3.x or Godot 4.x
var growth_time

Here the variable is still a Variant, but it is initialized with a float value:

# Godot 3.x or Godot 4.x
var growth_time = 10.0

To export the variable (so it is available in the inspector), in Godot 3.x you did this:

# Godot 3.x
export (float) var growth_time

Since the variable is of type Variant, it cannot be exported without specifying a type. Here the variable is being exported as float.

However, the variable is still a Variant. It could have values that are not float if you set them from code. But it will show as an float in the inspector.

We need to fix that. Because in Godot 4.x, you don't do that. In fact, we could have fixed that in Godot 3.x, it looked like this:

# Godot 3.x
export var growth_time:float = 10.0

Or since you are initializing it, we can set the type implicitly:

# Godot 3.x
export var growth_time := 10.0

Now the variable is a float (either defined explicitly or inferred from the value you are using to initialize it), so we don't need to write float in export, because exporting a ´float´ as a float is the default (well, the other options to export a float are also float but you can specify a range or use an exponential scale).

Yes, Godot 3.x had typed variables. It is not a type hint.

And now, this is how that looks like in Godot 4.x:

# Godot 4.x
@export var growth_time:float = 10.0

Or like this:

# Godot 4.x
@export var growth_time := 10.0

That is because export is no longer a keyword, but an annotation instead. Annotations are a new language feature in GDScript 2.0 (the one that comes with Godot 4.x), and they all start with @.

This answer is adapted from another answer by me, over at gamedev (link).

Anesthesiology answered 1/5, 2023 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.