Hi. I’m pretty new here and I hope that I’m not repeating someone’s question.
I was doing one of Sebastian Lague’s video tutorial and one thing doesn’t work because somthing has changed in unity recently.
You can’t just get component and play audio just by writing audio.play. now you have to create a viariable, asignt the component to it and then play. ok, but, in this case it doesnt work. i’ve done this before, exectly the same thing in other projects and it was ok. here it is not.
"
UnassignedReferenceException: The variable shotAudio of Gun has not been assigned.
You probably need to assign the shotAudio variable of the Gun script in the inspector.
UnityEngine.AudioSource.Play () (at C:/buildslave/unity/build/artifacts/generated/common/modules/Audio/AudioBindings.gen.cs:617)
Gun.Update () (at Assets/Scripts/Gun.cs:23)
"
when I assign the audiosource in the Shot method it works… but not really properly (every shot cut’s previous’s sound). Assigning in start method doesn’t work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//[RequireComponent(typeof (AudioSource))]
public class Gun : MonoBehaviour {
AudioSource shotAudio;
public Transform spawn;
public enum GunType {Semi,Burst,Auto};
public GunType gunType;
public float rpm = 60;
// System
private float secondsBetweenShots;
private float NextPossibleShootTime;
void Start () {
secondsBetweenShots = 60 / rpm;
AudioSource shotAudio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
}
public void Shoot() {
if (CanShoot()) {
Ray ray = new Ray (spawn.position, spawn.forward);
RaycastHit hit;
float shotDistance = 20;
if (Physics.Raycast (ray, out hit, shotDistance)) {
shotDistance = hit.distance;
}
NextPossibleShootTime = Time.time + secondsBetweenShots;
Debug.DrawRay (ray.origin, ray.direction * shotDistance, Color.red, 1);
shotAudio.Play ();
}
}
public void ShootContinuous(){
if (gunType == GunType.Auto) {
Shoot ();
}
}
private bool CanShoot ()
{
bool canShoot = true;
if (Time.time < NextPossibleShootTime) {
canShoot = false;
}
return canShoot;
}
}