Hi all,
I’ve been working on a game where, as a first step, a group of objects start bouncing when they are approached by the player. So far I’ve solved this by creating a plane and placing it under the group of objects, and setting it as a trigger. Then, in my script PlayerControls, I’ve made an OnTriggerEnter function, where the Bouncing script is supposed to be enabled upon collision.
I did some searching, and wrote something that should work, but doesn’t. Instead I get the error NullReferenceException: Object reference not set to an instance of an object on the line startBouncing.enabled = false;
in PlayerControls.
So apparently something goes wrong when referencing to the Bouncing script. However, I can’t find what goes wrong here as I don’t see the difference between my code and the ones referenced.
Note here that I tried disabling the Bouncing script as a first attempt instead of enabling it. Ideally, it would be disabled until I enabled it upon entering the trigger.
Here are the scripts I’ve got:
Bouncing
using UnityEngine;
using System.Collections;
public class Bouncing: MonoBehaviour {
public bool Move = true;
public Vector3 MoveVector = Vector3.up;
//public float MoveRange = 0.00001f;
//public float MoveSpeed = 0.2f;
private Bouncing bounceObject;
Vector3 startPosition;
void Start ()
{
bounceObject = this;
startPosition = bounceObject.transform.position;
}
// Update is called once per frame
void Update ()
{
if(Move) {
bounceObject.transform.position = startPosition + MoveVector * (0.5f * Mathf.Sin(Time.timeSinceLevelLoad * 3.3f));
}
}
}
PlayerControls
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerControls : MonoBehaviour {
public float speed;
private Rigidbody rb;
private Bouncing startBouncing;
void Start ()
{
rb = GetComponent<Rigidbody>();
startBouncing = GetComponent<Bouncing>();
}
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 OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive (false);
}
if (other.gameObject.CompareTag("Plane"))
{
startBouncing.enabled = false;
}
}
}
Here’s the main reference that I used:
http://unity3d.com/learn/tutorials/modules/beginner/scripting/enabling-disabling-components
If anyone could help me out, I’d greatly appreciate it! I feel like I’m missing a tiny thing but I just can’t find it.