Я работаю над книгой Изучение развития игры Libgdx в главе 10, посвященной добавлению музыки и звука в игру. Я попробовал Googling, чтобы узнать, не сталкивался ли кто-либо с той же проблемой с нулевым указателем с добавлением музыки, но не повезло.LibGDX NullPointer Исключение при попытке загрузить музыку
По существу пытается загрузить в музыкальную дорожку из другого класса под названием «Активы» для запуска в моей основной игре.
Я вижу, что активы загружены, они печатаются на консоли. Поэтому я не думаю, что это проблема с тем, чтобы не найти файл.
com.woodgdx.game.Assets: # of assets loaded: 9
com.woodgdx.game.Assets: asset: ../core/assets/sounds/jump_with_feather.wav
com.woodgdx.game.Assets: asset: ../core/assets/canyonbunny.pack.png
com.woodgdx.game.Assets: asset: ../core/assets/music/keith303_-_brand_new_highscore.mp3
com.woodgdx.game.Assets: asset: ../core/assets/sounds/live_lost.wav
com.woodgdx.game.Assets: asset: ../core/assets/canyonbunny.pack2.png
com.woodgdx.game.Assets: asset: ../core/assets/sounds/pickup_feather.wav
com.woodgdx.game.Assets: asset: ../core/assets/sounds/jump.wav
com.woodgdx.game.Assets: asset: ../core/assets/canyonbunny.pack.atlas
com.woodgdx.game.Assets: asset: ../core/assets/sounds/pickup_coin.wav
Так что я не совсем уверен, что происходит ...
ошибка сама по себе ..
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.woodgdx.game.woodGdxGame.create(woodGdxGame.java:29)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:147)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)
Основной класс
package com.woodgdx.game;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.woodgdx.game.Assets;
import com.woodgdx.game.screens.MenuScreen;
import com.woodgdx.game.util.AudioManager;
import com.woodgdx.game.util.GamePreferences;
/**
* The main game file with the main
* engine methods
* @author xxxx
*/
public class woodGdxGame extends Game
{
@Override
public void create()
{
// Set Libgdx log level
Gdx.app.setLogLevel(Application.LOG_DEBUG);
// Load assets
Assets.instance.init(new AssetManager());
// Load preferences for audio settings and start playing music
GamePreferences.instance.load();
AudioManager.instance.play(Assets.instance.music.song01);
// Start game at menu screen
setScreen(new MenuScreen(this));
}
}
Ошибка возникает на этой линии.
AudioManager.instance.play(Assets.instance.music.song01);
Класс My Assets содержит этот внутренний класс. То, как это было в книге, я получил ту же ошибку, когда я сделал это своим классом.
/**
* Music for game loaded
* @author xxxx
*
*/
public class AssetMusic
{
//Our music object
public final Music song01;
/**
* Retrieves the music file for the music
* @param am
*/
public AssetMusic(AssetManager am)
{
song01 = am.get("../core/assets/music/keith303_-_brand_new_highscore.mp3", Music.class);
}
}
Тогда вот класс AudioManager, в котором они играют здесь немного.
/**
* Manages the playing and organization
* of audio files
* @author xxxx
*
*/
public class AudioManager
{
public static final AudioManager instance = new AudioManager();
private Music playingMusic;
// singleton: prevent instantiation from other classes
private AudioManager()
{
}
/**
* Play sound with default vol, pitch, and pan (0)
* @param sound
*/
public void play(Sound sound)
{
play(sound, 1);
}
/**
* Play sound with default pitch and pan (0) but different vol
* @param sound
* @param volume
*/
public void play(Sound sound, float volume)
{
play(sound, volume, 1);
}
/**
* Play sound with default pan (0) with different pitch and vol
* @param sound
* @param volume
* @param pitch
*/
public void play(Sound sound, float volume, float pitch)
{
play(sound, volume, pitch, 0);
}
/**
* Plays sound with a vol, pitch, and pan activated
* @param sound
* @param volume
* @param pitch
* @param pan
*/
public void play(Sound sound, float volume, float pitch, float pan)
{
//If sound is muted, dont play
if (!GamePreferences.instance.sound)
return;
sound.play(GamePreferences.instance.volSound * volume, pitch, pan);
}
/**
* Plays music on loop
* @param music
*/
public void play(Music music)
{
stopMusic();
playingMusic = music;
if (GamePreferences.instance.music)
{
music.setLooping(true);
music.setVolume(GamePreferences.instance.volMusic);
music.play();
}
}
/**
* Ends the music loop of doom
*/
public void stopMusic()
{
if (playingMusic != null)
playingMusic.stop();
}
/**
* Checks settings for muted music, vol level
*/
public void onSettingsUpdated()
{
//No music available
if (playingMusic == null)
return;
//Sets volume
playingMusic.setVolume(GamePreferences.instance.volMusic);
//Checks if music is not muted
if (GamePreferences.instance.music)
{
//If music isn't playing, play it
if (!playingMusic.isPlaying())
playingMusic.play();
}
//Mute music if selected so
else
{
playingMusic.pause();
}
}
}
Вы должны использовать инкапсуляцию, но независимо от того проблема в том, что 'Активы # music' равно нулю, так как ничего не разыменовывается на той линии, которая ISN» t константа (я предполагаю, что 'Assets # instance' производится так же, как' AudioManager') – Rogue
А, ок, да, это оказалось чем-то вроде метода инициализации, который имеет Libgdx. Да, я в основном копировал код книги, с другими курсами, которые я беру, и все, что у меня нет времени, чтобы сделать это фантазией и использовать для этого хорошие принципы мягкой инженерии. – user2052752
Спасибо за вашу помощь, однако, повел меня в правильном направлении. – user2052752