0 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

asked Jul 5 in Engine by mcolpus (15 points)

1 Answer

0 votes
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.

answered Jul 5 by Calinou (6,336 points)
selected Jul 5 by mcolpus

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 How to use this Q&A? before posting your first questions.