0

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)
  • It seems somewhere in your code for `v2` and `foo` you are referencing the other class, which causes a cyclic dependency (because one class is referencing another, and vice-versa). – Martin Feb 17 '21 at 06:15
  • @Martin After my research I learned that's kind of bug which should be fixed in future versions. Now you can achieve this functionality by replacing `return v2.new()` to `load(/v2 script path/).new()`. That's working fine, but I'm not sure about optimization – Alexandr Maliovaniy Feb 20 '21 at 13:49

1 Answers1

0

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
Oliort UA
  • 1,568
  • 1
  • 14
  • 31
  • 1
    Yeah, it works the same as I mentioned in the comments above. In every case, you would load all scripts a second time. I found a kind of hack that allows work with this more comfortable: you can create a method for example `Copy(_x, _y)` that returns `get_script().new(_x, _y)` and now you can use it in other methods like `Add(v): return Copy(x + v.x, y + v.y)` – Alexandr Maliovaniy Mar 14 '21 at 20:36
  • Yeah, I hope it will be fixed soon to more comfortable syntax without any need of pretty workarounds. – Oliort UA Mar 14 '21 at 21:18