Below is what I am trying to do, play a sound and an animation by pressing fire button (previously assigned on input manager). Please note I use C# language:
using UnityEngine;
using System.Collections;
public class ShotgunFire : MonoBehaviour {
public AnimationClip ShotClip;
public AudioClip ShotSound;
Animation anim;
AudioSource audio;
// Use this for initialization
void Start ()
{
anim.AddClip(ShotClip, "fire");
}
// Update is called once per frame
void Update ()
{
if(Input.GetButton("Fire") == true)
{
audio.PlayOneShot(ShotSound);
anim.Play("fire");
}
}
}
The script above was attached as a component to my shotgun model, as shown on the picture below. As you may see, I have assigned assets to all public variables on the script, as requested.
And when I press play it keeps giving a NullReferenceException error, which is making me fry my brains trying to solve it! Lights please?
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(Animation))]
public class ShotgunFire : MonoBehaviour {
public AnimationClip ShotClip;
public AudioClip ShotSound;
// Use this for initialization
void Start ()
{
animation.AddClip(ShotClip, "fire");
}
// Update is called once per frame
void Update ()
{
if(Input.GetButton("Fire") == true)
{
audio.PlayOneShot(ShotSound);
animation.Play("fire");
}
}
}
EliteMossy, you forgot to say I had to add the components directly into the object, not associate them to variables in my script. But thanks for your help!
So this is how I solved the problem:
Instead of associating the components to variables in script, I added them directly into the object, making the inspector look like this:
Then, by using RequireComponent attributes and unity engine’s property variables (in this case audio and animation), I was able to control the object’s components by its class. The final code is as follows:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(Animation))]
public class ShotgunFire : MonoBehaviour {
// Use this for initialization
void Start (){}
// Update is called once per frame
void Update ()
{
if(Input.GetButton("Fire") == true)
{
audio.Play();
animation.Play();
}
}
}
I am migrating from XNA, where I had to do everything by code. So trust me when I say unity is being a challenging transition (but hopefully worth).
My code would have added them automatically if you dragged the script on to a GameObject. That is what RequireComponent does.
have you defined
– Benproductions1anim? If not thats your problem@Ralp remember to mark an answer as accepted if it works.
– EliteMossy