Create an instance of class inside said class in GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Svampen
:warning: Old Version Published before Godot 3 was released.

Hi there! I’m new to Godot and GDScript with some experience in python and java.
Anyway i’m trying to create a simple map generator using a binary space partitioning algorithm.

In that algorithm i would like to be able to split a class Paper into two Papers of the same class see example:

class Paper: 
   var x
   ..
   ..
   var child_1
   var child_2

   func _init(x_pos,y_pos,w,h):
      x = x_pos
      ..
      
   func splitPaper():
      child_1 = Paper.new(args)
      child_2 = Paper.new(other args)

Unfortunately it results in a parser error identifier paper not found

The python way of doing it by giving self as an argument doesn’t work either.

Any ideas of how i could get around this?’

Thanks for your help!

:bust_in_silhouette: Reply From: davidoc

Create a “leaf” class, in your Paper class you hold a reference to it, something like this:

class Leaf:
    var x
    var y
    var w
    var h
    var p1 = null
    var p2 = null

class Paper:
	var Root = CreateLeaf(x,y,w,h)

	func CreateLeaf(x,y,w,h):
		var lf = Leaf.new()
		lf.x = x
		...
		lf.p1 = CreateLeaf(other x,y,w,h)
		lf.p2 = CreateLeaf(more x,y,w,h)
		return lf