- Home /
Passing an AudioClip parameter to Method
Hey,
I have the problem that I am getting NullReferenceExceptions when I want to instantiate a sfx for the weapon.
For this I use a SFX-prefab that play only its parameter-given AudioClip:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof (AudioSource))]
public class SFX : MonoBehaviour {
private AudioSource aud;
void Start () {
aud = GetComponent<AudioSource>();
aud.spatialBlend = 1f;
}
public void selectSFX(AudioClip sound){
aud.clip = sound; // ERROR
aud.Play();
Destroy(gameObject, aud.clip.length);
}
}
Now I instantiate it in the Weapons-class:
GameObject sfxClone = Instantiate(Resources.Load("Prefabs/SFX"), bulletEmpty.position, transform.rotation) as GameObject;
sfxClone.GetComponent<SFX>().selectSFX(shootSound);
but this gives me the NullReferenceException in SFX, line with //ERROR
The shootSound-variable in the weaponScript is assigned.
Thanks in advance
shootSound is a public variable in the weapons class and assigned by default to an existing shootSound.
Is your SFX actually a prefab or just a script you put in Resources/Prefabs folder?
@incorrect No it ia a prefab that contains the sfx script and then an audiosource component.
But I'm pretty much shure that if you add this line of code
if(sfxClone == null) Debug.Log("sfxClone is null");
after
GameObject sfxClone = Instantiate(Resources.Load("Prefabs/SFX"), bulletEmpty.position, transform.rotation) as GameObject;
you will see, that nothing was loaded.
Answer by lassade · Jan 26, 2016 at 06:05 PM
From the Unity manual
Note for C# and Boo users: use Awake instead of the constructor for initialization, as the serialized state of the component is undefined at construction time. Awake is called once, just like the constructor.
http://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html
So change Start to Awake.
Btw Start is called in the frame the game object is enabled.
Start and Awake are both can be used, they are not constructors.
Futhermore, both can be executed the same frame.
Like the Awake function, Start is called exactly once in the lifetime of the script. However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled. Start may not be called on the same frame as Awake if the script is not enabled at initialisation time.