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!

asked Apr 5, 2018 in Engine by imekon (229 points)

2 Answers

+1 vote
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.

answered Apr 6, 2018 by bitwes (134 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.

answered Apr 6, 2018 by Zylann (27,002 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 How to use this Q&A? before posting your first questions.