+2 votes

I want to create a class to hold some data. For the sake of the question, I want a Vector4 class. How would I build this with GDscript.
It seems that Custom Resources is the only method which has worked to an extent.

extends Resource
class_name Vector4 

export(float) var x = 0
export(float) var y = 0
export(float) var z = 0
export(float) var w = 0

func length():
    return sqrt(x*x + y*y + z*z + w*w)

This is all fine. But if I try to add a method to create a Vector4 from a Vector3 it gets errors about cyclic reference.

func from_v3(v: Vector3):
    return Vector4.new(v.x, v.y, v.z, 0)

This seems to be resolved if I use get_script(), but this wouldn't work in a static factory method.
Is there a better method? Also being able to override equality, or do something like Vector4.Up would be nice.

Alternatively, I've seen some people use dicts for structs but that seems to lose a lot. Thanks

in Engine by (17 points)

1 Answer

+1 vote
Best answer

You could use an inner class for this purpose.

Also, cyclic references will most likely be allowed in Godot 4.0 thanks to the GDScript rewrite.

by (12,871 points)
selected by

To make the inner class accessible elsewhere I guess you can use class_name on the parent class?
4.0 sounds nice

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 [email protected] with your username.