I can inherit from another class but only if it’s in the same file which isn’t the best option. Is there any way to import a class from another file and inherit from it ? Or a better way to inherit from another class?
class Input extends pc.ScriptType
{
testFunction()
{
console.log("testing works");
}
}
class KeyboardInput extends Input {
initialize() {
console.log("Initializing Keyboard Input");
this.testFunction();
}
}
// register the class as a script
pc.registerScript(KeyboardInput,'keyboardInput');
Thank you for your answer (and also for the heads up), but I meant importing a class from another file. Right now, I need both classes to be in the same file which is what I’m trying to avoid.
They can be in separate files, no need to keep them together. Just make sure that the base class loads first, before the inherited ones. You can adjust the scripts loading order in the Project Settings, or simply make the base script higher in the scene hierarchy, so it gets parsed first at runtime.
From the screenshots you posted it should work correctly, unless on line 13 of keyboardInput.js you have something like
var input = new PixiInput(); // error
Keep in mind that your base class inherits pc.ScriptType. That is how you can access this.app or this.entity inside the scripts. You don’t use new keyword to instantiate them - the engine will do it for you. You would then access that instance the engine created via the entity’s script component. You know, the usual entity.script.pixiInput.
Thank you very much for your help! By testing with your small demo, I found why it was not working on my side.
My problem was simple. I changed the loading order in the editor but when I downloaded and did the test locally, I forgot to update the __settings__.js file, which is the one that contains the script order.
I cannot get it working. I have the correct scripts loading order and I register both scripts, but I cannot parse the child class in the editor as it says that the parent class is undefined.
Parent Class
I got this. It wasn’t working because I created the scripts locally and pushed them using playcanvas-sync. In that case, they need to be parsed manually, and they cannot (parent class is undefined). So for it to work you have to fool the editor: create a new script in the editor (it won’t ask for parsing), and change it to use inheritance afterwards. This way it works. Though this way is incredibly inconvinient.
This will improve in the upcoming ESM Scripts, you will be able to inherit from classes in separate modules in the same way you can with idiomatic javascript