Reputation: 3058
I've created a game using Phaser, and I want to "port" it over to TypeScript. I'm running into a problem when I want to call the same function from several different states.
Among a few other variables and functions, there is for example a music on/off function and a function to fade the entire screen to black. I want to re-use these in the different Phaser.States
MainMenu, LevelSelect and Game. So I put them as global variables in the MyGameProj.Client namespace, however this gives an error Cannot find name ..
when I call them from the MainMenu state.
I know global variables and functions are considered A Bad Thing, but my question is;
how can I re-use one function in several different Phaser.States?
I've tried adding the global variables and functions in my boot state, like so:
[Boot.ts]
module MyGameProj.Client {
var SOUND_IS_ON = true;
var MUSIC_IS_ON = true;
function switchMusic(game, onoff) {
MUSIC_IS_ON = onoff;
// .. etc.
}
export class Boot extends Phaser.State {
preload() {
switchMusic(this.game, true); // no errors
//.. etc.
But then when I try to access the switchMusic from my MainMenu state, it gives an error 'Cannot find name switchMusic'. However, they can be used and called from within the Boot state.
[MainMenu.ts]
module MyGameProj.Client {
export class MainMenu extends Phaser.State {
create() {
switchMusic(this.game, true); // <- error; Cannot find name switchMusic
//.. etc.
Upvotes: 0
Views: 196
Reputation: 164327
If you define variable/functions inside your own module/namespace, as you did with MyGameProj.Client
then those are not considered global.
In order to use what you have in MyGameProj.Client
from another namespace/module you'll need to prefix the function/variable with the path of that said module:
MyGameProj.Client.switchMusic(this.game, true);
Also, if both modules (MyGameProj.Client
and MyGameProj.Client
) reside in different files then you'll need to let the compiler know where to find MyGameProj.Client
.
How to do that depends on how you load other scripts, you can either import it:
import * as m from "MyGameProj.Client";
or reference it:
/// <reference path="MyGameProj.Client.ts" />
You should read the Namespaces and Modules and Module Resolution sections of the official docs.
Upvotes: 1