+2 votes

Hi,

The engine crashes when I inherit a subclass from another file. It works fine if I inherit a subclass from the same file.

For example:
Class.gd File

class Class1:
   extends "res://Test.gd".Class2
        func _init():
        pass

Test.gd

class Class2:
    func _init():
        print("Class 2 initialization!")

The engine crashes upon startup, sometimes with the error 'Could not determine inheritance' or it will crash without no error.

Please, could anyone give me an example of how to inherit a subclass/class from another file because I'm unable to do this. Currently, I'm only able to inherit a class from the same file but not from a different file.

Thanks

in Engine by (34 points)

1 Answer

+2 votes
Best answer

A godot script by itself is already a class, so you should not use class Class1 or class Class2 at the start of the file. There are quite a few errors in your code.

The right way to do it would be something like this:

my_class file:

extends Node # Your class can extend from any other node or class, even created ones
# Declaring variables common for the class
var name 
var age
var inventory
func _ready():
    pass

filethatextendsfromclass.gd file:

extends "res://my_class.gd"

# The vars inherited from the class file could be set on `_init` or any other loop like `_process` or `_fixed_process`
func _ready:
    name =  "frog" # See, I didn't specify "var" since all the
    age = 2        # following variables exists in "my_class.gd"
    inventory = ["Master Sword","Water"]
    print("Hi, I am ", name, ", ", age," years old and I have: ", inventory) # test-print
    pass

As you can see, the very first line of code should be extends "path to the file" or a name of a built in class. After that, it is just a matter of changing the vars on the file.

by (231 points)
selected by

Thanks for detailed answer!
Iv gone with the format you've stated. But I'm still curious as to how to inherit a subclass from another file since it states in the documentation:

 # Inherit/extend a subclass in another file
     extends "somefile.gd".SomeSubClass

This is new to me, care to send me a link to this part of the documentation? I could make some tests and also learn from it.

This does not answer the OPs question. How to inherit a named class?

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.