Hello! I’m trying to make a Roll a ball game, however I keep getting this:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.FixedUpdate () (at Assets/Scripts/PlayerController.cs:47)
NullReferenceException: Object reference not set to an instance of an object
PlayerController.OnCollisionEnter () (at Assets/Scripts/PlayerController.cs:53)
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float speed;
public float jumpheight;
int JumpCount = 0;
public int MaxJumps = 1;
public AudioSource source;
public AudioClip jumpsound;
public AudioClip hitsound;
void Start()
{
JumpCount = MaxJumps;
source = gameObject.GetComponent<AudioSource>();
}
public void Jump()
{
rb.AddForce(new Vector3(0, jumpheight, 0), ForceMode.Impulse);
source.clip = jumpsound;
source.Play();
}
void Update()
{
rb = GetComponent<Rigidbody>();
if (Input.GetKeyDown("space"))
{
if (JumpCount > 0)
{
Jump();
JumpCount -= 1;
}
}
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
void OnCollisionEnter()
{
rb.velocity = Vector3.zero;
JumpCount = MaxJumps;
source.clip = hitsound;
source.Play();
}
}
It doesn’t affect the gameplay, but it’s there. Why?
Rand 47: rb.AddForce(movement * speed);
Rand 53: rb.velocity = Vector3.zero;