Error is “NullReferenceException: object reference not set to an instance of an object”
Unity tells me , trouble in the string
Camera.main.GetComponent<CameraFollow>().gameOver = true;
please help me to fix that.
Full code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallController : MonoBehaviour {
[SerializeField]
private float speed;
bool started;
Rigidbody rb;
bool gameOver;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Use this for initialization
void Start () {
started = false;
gameOver = false;
}
// Update is called once per frame
void Update () {
if(!started)
{
if(Input.GetMouseButtonDown (0))
{
rb.velocity = new Vector3(speed, 0, 0);
started = true;
}
}
Debug.DrawRay(transform.position, Vector3.down, Color.red);
if(!Physics.Raycast (transform.position, Vector3.down, 1f))
{
gameOver = true;
rb.velocity = new Vector3(0, -25f, 0);
Camera.main.GetComponent<CameraFollow>().gameOver = true;
}
if(Input.GetMouseButtonDown (0) && !gameOver)
{
SwitchDirection ();
}
}
void SwitchDirection ()
{
if (rb.velocity.z > 0)
{
rb.velocity = new Vector3(speed, 0, 0);
}
else if (rb.velocity.x > 0)
{
rb.velocity = new Vector3(0, 0, speed);
}
}
}
Full Script for camera follow
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public GameObject ball;
Vector3 offset;
public float lerpRate;
public bool gameOver;
// Use this for initialization
void Start () {
offset = ball.transform.position - transform.position;
gameOver = false;
}
// Update is called once per frame
void Update () {
if (!gameOver)
{
follow();
}
}
void follow()
{
Vector3 pos = transform.position;
Vector3 targetPos = ball.transform.position - offset;
pos = Vector3.Lerp(pos, targetPos, lerpRate * Time.deltaTime);
transform.position = pos;
}
}
I will be very grateful.