Why is this a null reference exception and how can I fix it. Its on line 44. Thanks!
using UnityEngine;
using System.Collections;
public class BallController : MonoBehaviour {
public float cSpeed = 15.0f; //Constant speed.
public float sFactor = 15.0f; //Smoothing factor.
public static int playerScore = 0; //Holds the current score of the player.
public static int enemyScore = 0; //Holds the current Enemy's score.
public Transform target;
public AudioClip Sfx;
public float z;
void Start(){
GetComponent<Rigidbody>().AddForce(new Vector3(10, 0, 0)); //Initial force to the x-axis to make it move to a direction.
}
void Update() {
PlayerController PC = GetComponent<PlayerController>();
EnemyController EC = GetComponent<EnemyController>();
Vector3 cVel = GetComponent<Rigidbody>().velocity;
Vector3 tVel = cVel.normalized * cSpeed;
GetComponent<Rigidbody>().velocity = Vector3.Lerp(cVel, tVel, Time.deltaTime * sFactor);
//Check the boundries on the x-axis.
if (transform.position.x > 23) {
enemyScore++; //Increase value by 1;
GetComponent<Rigidbody>().velocity = new Vector3(10, 0, 0);
transform.position = new Vector3(0, -16, -20); //Reset ball pos.
PC.position(-20F, -16F, -19.5F);
EC.position(20F, -16F, -19.5F);
}
if (transform.position.x < -23) {
playerScore++; //Increase value by 1;
GetComponent<Rigidbody>().velocity = new Vector3(10, 0, 0);
transform.position = new Vector3(0, -16, -20); //Reset ball pos.
PC.position(-20F, -16F, -19.5F);
EC.position(20F, -16F, -19.5F);
}
}
void OnGUI() {
GUI.Label(new Rect(10, 100, 100, 20), "Player 1: " + enemyScore);
GUI.Label(new Rect(310, 100, 100, 20), "SCORE");
GUI.Label(new Rect(580, 100, 100, 20), "Player 2: " + playerScore);
}
float hitFactor(Vector3 ballPos, Vector3 racketPos, float racketHeight) {
return (ballPos.z - racketPos.z) / racketHeight;
}
void OnCollisionEnter(Collision collision) {
GetComponent<AudioSource>().PlayOneShot (Sfx, 0.7F);
if (collision.gameObject.name == "Player") {
z = hitFactor(transform.position, collision.transform.position, collision.collider.bounds.size.z);
Vector3 dir = new Vector3(1, 0, z).normalized;
GetComponent<Rigidbody>().velocity = dir * cSpeed;
}
if (collision.gameObject.name == "Enemy") {
z = hitFactor(transform.position, collision.transform.position, collision.collider.bounds.size.z);
Vector3 dir = new Vector3(-1, 0, z).normalized;
GetComponent<Rigidbody>().velocity = dir * cSpeed;
}
}
}