Hi, i have wrote a script that when we click with Fire1 on an object that have the tag “Bottle” pick up them. it works perfectly then i added a code to calculate the distance from object and player, and only able player to pick up the item when we are 2 meters from the object, but i have an error:
NullReferenceException
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:15)
Script:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private Transform pickObj = null;
private RaycastHit hit;
private Ray ray;
private float distance;
void Update (){
distance = Vector3.Distance(pickObj.transform.position, gameObject.transform.position);
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (!pickObj) {
if (Physics.Raycast(ray, out hit) && hit.transform.tag == "Bottle") {
if(distance <= 2) {
if(Input.GetMouseButton(0)) {
pickObj = hit.transform;
}
}
else {
pickObj.transform.active = false;
}
}
}
}
}