|
|
|
|
Reply From: |
tmattoneill |
So I’ve gotten some conflicting advice and some that I don’t understand. However, I have figured this out so I thought I’d put the answer here.
There’s a few ways to do this.
First, there’s the way of doing it within one script. This works as expected and is the most ‘pythonic’ example.
my_script.gd:
class MyThing:
var _var1
func _init(var1):
self._var1 = var1
func set_val(arg):
self._var1 = arg
func get_val():
return self._var1
func _ready():
var thing = MyThing.new(100)
print (thing.get_val()) # print out the value of thing
thing.set_val(50) # change the value to 50
print(thing.get_val()) # print out the new value
The Second way is to manage classes in multiple files. Here I’ll have a file to define the class my_thing.gd and a main class file main.gd that calls and instantiates new items.
main.gd:
var thing = load("res://my_thing.gd").new(100) # create a new thing with a 100 value
print (thing.get_val()) # print out the value of thing
thing.set_val(50) # change the value to 50
print(thing.get_val()) # print out the new value
my_thing.gd:
# Class my_thing.gd
# takes a value and allows you to view, update or change it.
var _var1
func _init(var1):
self._var1 = var1
func set_val(arg):
self._var1 = arg
func get_val():
return self._var1
But I think the cleanest and best way to manage it is a slight variation of the above. The my_thing.gd remains the same but I manage the instances in main.gd differently.
main.gd
var Thing = load("res://my_thing.gd") # create a Thing reference object
thing = Thing.new(100) # create an instance with initial value of 100 of a Thing
print (thing.get_val()) # print out the value of thing
thing.set_val(50) # change the value to 50
print(thing.get_val()) # print out the new value
I really like this as I can now do things like:
var things = []
for i in range(100):
things.append(Thing.new(0))
and get a nice clean list of new things!
Why don’t you link to your cross-post at /r/godot ?
I didn’t realize you could do the first one with classes. I was thinking of only nodes, and how they have to be instanced.
I checked it out, and you could also keep you classes in a separate GD script and use them as such:
class.gd
class my_class:
var m1
var m2
func _init(parm1, parm2):
m1 = parm1
m2 = parm2
And called like:
extends Node2D
func _ready():
var script = preload("res://class.gd")
var thing = script.my_class.new(1,2)
print(thing.m1)
print(thing.m2)
avencherus | 2016-11-10 09:01
Yes, you can work with normal classes and inner classes that way, I thought he refered to Object subclases