diff --git a/assets/content/cookbook/Advanced/02.ScriptedClasses.md b/assets/content/cookbook/Advanced/02.ScriptedClasses.md index 13c35b0e..9ce6e6b4 100644 --- a/assets/content/cookbook/Advanced/02.ScriptedClasses.md +++ b/assets/content/cookbook/Advanced/02.ScriptedClasses.md @@ -20,6 +20,54 @@ class BallisticSong extends Song { } ``` +## Extending Scripted Classes + +Since update `0.8.2`, a scripted class can also extend *another scripted class*, rather than only a native scriptable class. This is useful for sharing behavior between multiple scripted classes, like a base character that several custom characters all build on. + +```haxe +// MyBaseChar.hxc +// A scripted class that extends a native class, as usual. +import funkin.play.character.SparrowCharacter; + +class MyBaseChar extends SparrowCharacter { + public function new() { + super(); + } + + // Shared behavior for all characters based on this script. + function onDance() { + // ... + } +} +``` + +```haxe +// MyChar.hxc +// This scripted class extends the scripted class above. +import MyBaseChar; + +class MyChar extends MyBaseChar { + public function new() { + // The superclass is itself a scripted class; you still call its constructor. + super(); + } + + override function onDance() { + // Call the inherited scripted function first. + super.onDance(); + // Then add custom behavior. + // ... + } +} +``` + +There are a few rules to keep in mind: + +- If your class defines a `new()` constructor, you must call `super()` inside it, just like with a native superclass. If you don't define a constructor at all, the superclass's constructor is called automatically. +- A scripted class can't have an instance field with the same name as a field in its superclass — Polymod throws an error on that conflict. +- Scripted functions and fields are inherited through the entire chain of scripted superclasses, so you can extend a scripted class that itself extends another scripted class. +- Extending a native scriptable class (as shown in the example above) still works exactly as before. + ## List of Scriptable Classes There is a predefined list of classes which the game has set up to be scriptable, and will automatically load and execute when relevant. More of these will be added in the future.