[Sugarcube2] Using JS Class to make objects ingame

Twine Version:2
Story Format: Sugarcube

Hello

I made a special foulder on my local disc C:
C:\test
and put all files there for simplicity
I have two files in a foulder

Person.js

class Person {
	constructor(name = 'Anon') {
        this.name = name
        this.energy = 5
    }
}       

and thePerson.html twine/Sugarcube file with a single passage

<<script>>
importScripts('Person.js')
	.then(function() {
		setup.JSLoaded = true;
	}).catch(function(error) {  
		setup.JSLoaded = false; 
		alert("Error: Could not find file.");
	}
);

	State.variables.player = new Person('Alex');
<</script>>

<<print setup.JSLoaded>>
$player
$player.name
$player.energy 

I tried

importScripts('Person.js')

importScripts('c:\test\Person.js')

importScripts('./Person.js')

I tried to start from Twine and from saved .xml with Chrome in each case but it makes no difference.

It’s just trows

Error: <<script>>: bad evaluation: Person is not defined

And not even sets setup.JSLoaded to true or falsem it’s reads [undefined]. Alert is triggers in some cases in some it’s not.

What do I do wrong, and how can I do it right?

PS: if you will advice a Tweego, then please explain it, cos I tried to read about it online and failed to figiure out what is it, how and for what it’s used instead of just Twine…

As far as the path goes, if you have both files in the same directory, then something like importScripts('Person.js') is what you’ll want.

The problem you’re having is that importScripts() is asynchronous, returning a Promise object, but you’re treating it like it’s synchronous. (See: Asynchronous Programming)

Unless you have a pressing need to use external files, I’d seriously suggest simply putting your class within your project’s Story JavaScript (within the story menu) to bypass the asynchronicity issue altogether.

That said, it will necessitate some changes to your classes. Chiefly, that you’ll need to manually make the class an auto-global. For example:

window.Person = class Person {

Also, regardless of what route you take, you’ll need to implement a few methods on your classes to make them revivable. See Non-generic object types (a.k.a. classes) in the docs for details.

1 Like

It works to put it into Story JavaScript! And even in passages within script clause. Thats almost perfect but I wat to use .js files for better compatibiliuty with VC code.

I’ll look for Asynchronous Programming as yo suggested

Many thanks!

[EDIT] Disregard this. I just make bad comment clause in story JS and that was the case

One more thing. I mannaged to plug in .js file with

window.Person = class Person {

and it works ingame, but trows discardable error on a start.

Error: [tw-user-script-0]: invalid or unexpected token.

what can it be?