Can you please help me with this problem, I'm adding FMOD to UNITY and want to change my music when Player gets damage, from FMOD side is OK, but in Unity it gives me an error: NullReferenceException: Object reference not set to an instance of an object MusicControl.Update () (at Assets/MusicControl.cs:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using FMOD.Studio;
public class MusicControl : MonoBehaviour {
[FMODUnity.EventRef]
public string explosion = "event:/EXPLOSION";
[FMODUnity.EventRef]
public string shoot = "event:/SHOOT SOUND";
[FMODUnity.EventRef]
public string menuMusic = "event:/MENU MUSIC";
int val;
public FMOD.Studio.EventInstance musicEv;
public FMOD.Studio.ParameterInstance musicPar;
void Start()
{
}
//music for menu, I'm call this function when my stage starts(menu game)
public void MenuMusic()
{
musicEv = FMODUnity.RuntimeManager.CreateInstance(menuMusic);
musicEv.start();
}
//music for level 1, I'm call this function when my stage starts(level game)
public void LevelMusic()
{
musicEv = FMODUnity.RuntimeManager.CreateInstance(menuMusic);
musicEv.setParameterValue("FIGHT MUSIC", 100f);
musicEv.getParameter("HEALTH", out musicPar);
musicPar.setValue(100);
musicEv.start();
}
//I'm call this function when stages is close up
public void StopMusic()
{
musicEv.stop(FMOD.Studio.STOP_MODE.IMMEDIATE);
}
// I'm take current Health from Player script
void Update()
val = GameObject.Find("Player").GetComponent<Player>().stats.curHealth;
musicPar.setValue(val); //Unity gives me an error - NullReferenceException: Object reference not set to an instance of an object MusicControl.Update () (at Assets/MusicControl.cs:147)
}
}
Thanks for advance
The
musicEv
andmusicPar
variables are declared but never initialized before use in theUpdate()
function.You tried to to initialize them in the
MenuMusic()
andLevelMusic()
functions but there is no guarantee that these functions will be called before theUpdate()
function where you actually use them.Remove
musicEv = FMODUnity.RuntimeManager.CreateInstance(menuMusic);
from bothMenuMusic()
andLevelMusic()
functions and move it to theStart()
orAwake()
function in order to initializemusicEv
.After that, you can then initialize
musicPar
by callingmusicEv.getParameter("HEALTH", out musicPar);
.Also, don't do
val = GameObject.Find("Player")
in the Update function. Do it once inStart()
orAwake()
function then save it to a global variable. In fact, it would be good to just cache thePlayer
script that is attached to it.