How to optionally static typing external gdscript class?

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

Hi!

Using Godot 3.1, I’m trying to do this:

classA.gd:

var Foo 

classB.gd:

var Bar : classA

But I get an ‘classA is not a valid type’ error. Any hints?

Thanks in advance,
cybin

:bust_in_silhouette: Reply From: fpicoral

The operator : in Godot is used to say which is the variable type. For example, if you have a variable example and you want to make sure that it will always be and integer, you can do var example : int.
If you want to create a class and create a variable in this class, you need to do the following:

class Foo:
    var bar = “var1”
    var foo : int = 1

To get a variable/call a method outside the class, you need to do Foo.new().bar, which will return “var1”.

Unless you really need it, I would not recommend using classes. At least for me, I never found myself in a situation where a class would help me.

If you want a script to perform multiple things and keep you code organizated (at least for me this is the reason I would use a class) you can create a node only to hold a script and if you need this script in multiple places you can save this node as a scene and instanciate it where you need.

:bust_in_silhouette: Reply From: omggomb

You need to either use class_name for classA or load classA as a resource in classB:

var cA = load("classA.gd")
var instanceOfTypeClassA : cA

See Docs on static typing in the section “Custom variable types”