2016-08-21 3 views
0

좋아, 정말 이상한 문제가 있습니다. 지금은 C#/MonoGame (Linux)에서 간단한 게임을 작성하고 있습니다. SoundEffect을 재생하려고합니다. Play()으로 전화하면 (정확하게는 LoadContent() 방법으로로드 되었음에도 불구하고). 메시지가 이고 메시지가 Object Reference not set to an instance of an object입니다. 여기사운드가로드 되어도 SoundEffect.Play()가 NullReferenceException을 던지고 있습니다.

코드가

public class MyGame : Game 
{ 
    // .. 
    private SoundEffect _sfx; 

    public PingGame() 
    { 
     // ... 
    } 

    protected override void Initialize() 
    { 
     // ... 
    } 

    protected override void LoadContent() 
    { 
     // ... 

     // No errors here on loading it 
     _sfx = Content.Load<SoundEffect>("noise.wav"); 
    } 

    protected override void Update (GameTime gameTime) 
    { 
     // ... 

     if (playSound) 
     { 
      // This is where the error is thrown 
      _sfx.Play(); 
     } 

     // ... 
    } 

    protected override void Draw (GameTime gameTime) 
    { 
     // .. 
    } 
} 
+0

은 아마 당신은 [이 문제] (http://community.monogame.net/t/null-reference-exception-when-calling-play-on-a-soundeffect-or으로 실행했습니다 -soundeffectinstance/7319/10) – craftworkgames

답변

0

오류 메시지가이 모든 것을 말해 구조화하는 방법입니다. Update (GameTime gameTime)을 호출 할 때 _sfx 개체는 초기화되지 않습니다.

게임을 어떻게 디자인할지는 알 수 없지만 아래 코드를 변경하여 테스트 할 수 있으며 더 이상 null 참조 예외가 없습니다. 그게 당신이 코드를 어떻게 디자인하길 바라지는 않을지 모르지만 잘못된 코드와 수정 방법을 알려줍니다. 아래 코드를 참조하십시오.

protected override void Update (GameTime gameTime) 
{ 
    // ... 

    if (playSound) 
    { 
     // This is where the error is thrown 
     // THIS ENSURES WHEN THIS METHOD IS INVOKED _sfx is initialized. 

     _sfx = Content.Load<SoundEffect>("noise.wav"); 
     if(_sfx != null){ 
      _sfx.Play(); 
     } 
    } 
    // ... 
} 
+1

은'null '을 테스트하는 것이 더 좋을 것이고'_sfx == null' 인 경우 사운드를로드하는 것이 좋을 것입니다. –

+0

@ Jean-FrançoisFabre 절대적으로 null 체크가 추가되었습니다. –

+0

이 코드가 구조화 된 방식은 매번 사운드 효과를로드해야한다는 것을 의미합니까? – Benjamin

0

내 블라인드 추측은 (당신이 가지고 있지 않기 때문에 코드 포함)은 다음과 같습니다

  • GraphicsDeviceManager

    는 생성자의 내부에 만들어지지 않습니다
  • 을 (라고) base.Initialize (전에 작성해야합니다)
  • Initialize 방법에서 base.Initialize() 방법으로 전화하는 것을 잊지 마십시오.
+0

아니요. 그렇지 않습니다. 나는 그것을 두 번 확인했다. – Benjamin

0
protected override void Update(GameTime gameTime) 
{ 
    // ... 

    if (playSound) 
    { 
     if (_sfx == null) 
     { 
      Content.Load<SoundEffect>("noise.wav"); 
     } 
     _sfx.Play(); 
    } 
} 
관련 문제