So I’m having trouble with my Ball.cs script responding to commands once I’ve made the DragLaunch.cs script to access it. The methods all worked before, and theoretically work now, but for some reason now I get a bunch of Null Reference Exceptions. After adding a bunch of extra redundancy to my code to eliminate the NREs I still get an error “Can not play a disabled audio source” which is clearly not null, or disabled. Regardless, it still prevents Ball.cs from doing it’s job, the ball never launches. See screenshot and code below. Anybody have any idea what’s going on here?
Drag Launch:
Summary
using UnityEngine;
[RequireComponent(typeof(Ball))]
public class DragLaunch : MonoBehaviour {
private Ball ball;
private Vector3 dragStart, dragEnd;
private float startTime, endTime;
private void Awake()
{
ball = gameObject.GetComponent<Ball>();
}
public void DragStart()
{
dragStart = Input.mousePosition;
startTime = Time.time;
}
public void DragEnd()
{
dragEnd = Input.mousePosition;
endTime = Time.time;
float dragTime = endTime - startTime;
float dragSpeedX = (dragStart.x - dragEnd.x) / dragTime;
float dragSpeedZ = (dragStart.y - dragEnd.y) / dragTime;
if(ball != null)
{
ball.Launch(new Vector3(dragSpeedX, 0, dragSpeedZ));
}
else
{
ball = gameObject.GetComponent<Ball>();
ball.Launch(new Vector3(dragSpeedX, 0, dragSpeedZ));
}
}
}
Ball:
Summary
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(AudioSource))]
public class Ball : MonoBehaviour {
private Rigidbody rigidBody;
private AudioSource audioSource;
void Start () {
rigidBody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
rigidBody.useGravity = false;
}
public void Launch(Vector3 velocity)
{
if(rigidBody != null)
{
rigidBody.useGravity = true;
rigidBody.velocity = velocity;
}
else
{
rigidBody = GetComponent<Rigidbody>();
rigidBody.useGravity = true;
rigidBody.velocity = velocity;
}
if(audioSource != null)
{
audioSource.enabled = true;
audioSource.Play();
}
else
{
audioSource = GetComponent<AudioSource>();
audioSource.enabled = true;
audioSource.Play();
}
}
}