Forum Archive › Am I using classes correctly? › Reply To: Am I using classes correctly?
@jgonzalez I cleaned it up in the way that you suggested and the reason I am using classes is that I will be creating multiple weapons that all work pretty much the same way and it seemed like using a main Weapon class could save me a lot of redundant typing. The issue I am running into now is with the audio playing. Below is the script for the Weapon class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour {
public AudioClip clip;
public AudioSource audioSource;
public GameObject bullet, thisBullet;
public int firePower = 30;
public int bulletDelay = 90;
public int fireSpeed = 10;
public void Start () {
audioSource = GetComponent<AudioSource>();
//audioSource.clip = clip;
}
public void BulletDelay ()
{
bulletDelay--;
if (bulletDelay < 0 && OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger))
{
audioSource.Play();
bulletDelay = fireSpeed;
ShootGun();
}
}
public void ShootGun()
{
thisBullet = Instantiate(bullet, transform.position, transform.rotation);
thisBullet.GetComponent<Rigidbody>().AddRelativeForce(0, 0, firePower, ForceMode.Impulse);
}
}
and below is the script for the Cannon that is inheriting the Weapon class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cannon : Weapon {
Weapon cannon = new Weapon();
void Update()
{
cannon.BulletDelay();
}
}
When I play the game and press the shoot button on my Oculus controller, I get the following error, “
NullReferenceException: Object reference not set to an instance of an object
Weapon.BulletDelay () (at Assets/Scripts/Weapon.cs:23)
Cannon.Update () (at Assets/Scripts/Cannon.cs:11) “
I rewatched your video on how to play audio clips and I am still not sure what it is that I am doing wrong here. It was working perfectly earlier when I had the Weapon class applied directly to the weapon so I suspect it might have something to do with it being called from another class but I am not sure.