0 votes

So I have one script:

extends Node

class Stuff:
    var text
    var size

    func _init(t, s):
        text = t
        size = s

In another script, I access it with:

extends Node

onready var stuff = load("res://stuff.gd")

func _ready():
    var inst = stuff.Stuff.new("fred", 100)
    print(inst.text)
    print(inst.size)

Is there any way to access Stuff without using stuff.Stuff? It just seems so clumsy!

in Engine by (254 points)

2 Answers

+2 votes
onready var Stuff = load("res://stuff.gd").Stuff
func _ready():
  var instance = Stuff.new()

"best practice" is to name your variables that are references to classes using PascalCase.

by (143 points)
+1 vote

Alternatively, you can also change your stuff.gd to not extend anything:

stuff.gd

var text
var size

func _init(t, s):
    text = t
    size = s

Then you can access it like that:

extends Node

const Stuff = preload("res://stuff.gd")

func _ready():
    var inst = Stuff.new("fred", 100)

If you prefer to use subclasses with the class keyword, you can do so, and then append .Stuff after the preload like bitwes did.

by (28,835 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.