简体   繁体   中英

Phaser3 adding a state throws an error. Cannot read property 'add' of undefined

I am currently trying to make a game with Phaser and I am following an online tutorial. The guy in the video does not get this error even though we have the same code. Could it have to do with the Phaser version? Or what is it that causes this error?

This is the error : Uncaught TypeError: Cannot read property 'add' of undefined

Here is the code for the html file where it is thrown. @ game.state.add('Boot', Game.Boot);

 <!doctype html> <html> <meta charset="UTF-8" /> <title>My example game</title> <!-- <script src="//cdn.jsdelivr.net/npm/phaser@3.2.1/dist/phaser.js"></script> --> <script src="phaser.js"></script> <script src="Boot.js"></script> <script src="Preloader.js"></script> <script src="MainMenu.js"></script> <script src="Level1.js"></script> <body> <script type="text/javascript"> window.onload = function() { var game = new Phaser.Game(800, 600, Phaser.CANVAS, ''); game.state.add('Boot', Game.Boot); // <---- game.state.add('Preloader', Game.Preloader); game.state.add('MainMenu', Game.MainMenu); game.state.add('Level1', Game.Level1); game.state.start('Boot'); console.log("Done!"); }; </script> </body> </html> 

Based upon the comment in your missing head and question, it looks like you're using Phaser 3.

In Phaser 3 the State Manager was replaced by Scenes. So I would verify that you're referencing Phaser 2 (CE ideally) or 3. Since phaser.state is undefined, this suggests version 3 is being used.

If you want to continue with Phaser 3 take a look at the official tutorial at https://phaser.io/tutorials/making-your-first-phaser-3-game .

You should also add a <head> and </head> to your markup. I believe the browser should handle the fact that these are missing, but good practice to follow even for tutorial work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM