When I make a custom script/class by going into the code editor and select File -> New Script it is not attached to any node in my scene tree. I am able to extend that class in my other scripts (that are attached to nodes) and use the inherited methods. Why does this work? Do all scripts that I make run in the background? Then why the need for Project Settings -> AutoLoads?

I think you don't really understand how OOP (object oriented programming works).

You scripts define classes. They are not executed, but your classes can be used to instantiate instances, which provide data and functionality. For example, if you have a class Player and a node player this script is assigned to, whenever this node is instantiated, a an instance of class Player is instantiated with it. When that node then gets it's methods like _processs called, the method of that instance will be called. Without any instance, no code will be executed.

Now if you inherit from another class, your class is an extension of that super class. I.e. your class contains everything that super class contains, as well as your own code. An instance of that class will then also instantiate the super class as part of your instance.

For example, foo.gd:

class_name Foo
func foo() -> String:
  return "Foo"

bar.gd:

extends Foo
class_name Bar

func fooBar() -> String:
  return foo() + "Bar"

If we instantiate Foo, we have an object that contains 1 function called foo

var f: Foo = Foo.new()
print(f.foo())

If we instantiate Bar, we have an object that contains the same info as an instance of Foo (i.e. an object with one function) plus additionally one function called fooBar.

var b: Bar = Bar.new()
print(b.foo())
print(b.fooBar())

Where fooBar actually calls the function foo of it's parent.

If no instance of any of that is created, no code will ever be executed.

This allows for many things, for example the reduction of code dublicates through inheritance. For example players and enemies have many common features, Life, skills, buffs, etc. So you could create an actor class that provides all the functionality for this, and create two classes Player and Enemy that extend from this. This way you have one code base for the similarities and two different classes for the differences

@Warfley,

Thank you for taking the time to explain this.

Can anyone explain when I should use a script autoload?

Autoloads I believe are used for things that are persistent across scenes. For example, for the player's item inventory, or an achievement tracker, you may want to carry over and be persistent across different levels. You should probably avoid using them for too many things (that may be bad design) but there are usually some things that will need to exist for the whole game.

3 years later