[Gd 2.1] Does the .instance() function support arguments?

woopdeedoowoopdeedoo Posts: 109Member
edited April 2018 in Programming

I'm trying to instantiate a scene through code, and I'm also trying to use the _init() function of its base class. I usually use the _init() function when creating a node directly from a script (not attached to a scene) with:

pre_derp = preload("res://scripts/derp.gd")
# (...)
var derp = pre_derp.new(args)    # which invokes the _init(args) function

But now I'm trying to do:

pre_derp = preload("res://scenes/derp.tscn")
# (...) 
var derp = pre_derp.instance(args)    # error...

But it's telling me it's expecting only 1 argument. (And the _init() function expects 4 arguments, as shown below.)

Invalid call to function 'instance' in base 'PackedScene'. Expected 1 arguments.

The code behind it is the same, except I wasn't using the _init() function before. So maybe I made a mistake restructuring it. However, it may also be a problem with my inheritance hierarchy. I'm not sure what I'm doing here, so I have to also ask this: if I have a base class that uses _init(), do I need to define that function in its subclasses too? Or does the base class's _init() get automatically called if the subclasses don't have it?

In my case there's nothing the subclasses have to do in it, so I'm currently doing it like below, but since I'm getting that error above I can't tell if this makes any difference.

# subclass code
func _init(pos, g=0, fg=colors.RED4, bg=colors.BLACK).(pos, g, fg, bg):
    # I'm using this trick to pass the parameters to the base class, or at least
    # that's what I think that does, and it seems to work in other places of my code

... and...

# base class code
func _init(pos, g=0, fg=colors.RED4, bg=colors.BLACK):
    # does stuff...


  • arthurarthur Posts: 34Member

    When I need that, I use a initialize-like function after instancing but before adding to scene. This way, node data is initialized the moment the node starts processing.

  • woopdeedoowoopdeedoo Posts: 109Member
    edited May 2018

    Yea, it's what I ended up doing.

    func _create_cell(parent, x, y, glyph, fg, bg, add_bg ):
        var cell = pre.cell.instance()  # preloads listed in an autoload script 'pre'
        if add_bg:
        cell.init( Vector2(x, y), glyph, fg, bg )
        return cell

    But I still would like to understand how to go about it with node instancing. It works with scripts .new()...

Sign In or Register to comment.