Search code examples
godotgdscript

How to return instance of class in its method in godot script


I have class v2 that contains a method Add. This method should return a new instance of v2

my code looks like this

class_name v2

var x : float
var y : float

func _init(_x, _y):
    x = _x
    y = _y
    
func Add(v : v2):
    return v2.new(x + v.x, y + v.y) # error line

but when I'm trying to access class v2 from another class it shows me an error

class_name foo

var position = v2.new(0, 0)

#  Parse Error: The class "v2" couldn't be fully loaded (script error or cyclic dependency)

Solution

  • Using own name in class file is not allowed in Godot (creates a cyclic reference). You could get around the problem with this solution:

    class_name v2
    
    var x : float
    var y : float
    
    func _init(_x, _y):
        x = _x
        y = _y
    
    func Add(v):
        return get_script().new(x + v.x, y + v.y) # no error