- Home /
Need help with a raycast
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;
}
}
}
}
}
probable try saying input first then do the other stuffother wise your checking the distance alll the time and not just when the button is pressed
the null reference is pointing to your update, follow it, read it, the error pasted doesnt give enough info for someone to help
Answer by Unitraxx · Mar 30, 2013 at 11:12 PM
You can't calculate the distance, if pickObj == null. Which will always be null, since you only set it to something else if the distance is smaller than 2. But since that can't be calculated, you have to place the distance calculation after the ray cast calculation.
if(!pickObj) {
distance = Vector3.Distance(pickObj.transform.position, gameObject.transform.position);
if(Input.Get$$anonymous$$ouseButton(0)) {
still dont working :C
What's your error now ? (You did remove the line at line 10 did you? Having it twice in there won't help :) )
i will put there the script how i have:
but now i have null reference exepcion in distance = Vector3.Distance... line
using UnityEngine;
using System.Collections;
public class PlayerController : $$anonymous$$onoBehaviour {
private Transform pickObj;
private RaycastHit hit;
private Ray ray;
private float distance;
void Update (){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(!pickObj) {
distance = Vector3.Distance(pickObj.transform.position, gameObject.transform.position);
if(Input.Get$$anonymous$$ouseButton(0)) {
if (!pickObj) {
if (Physics.Raycast(ray, out hit) && hit.transform.tag == "Bottle") {
if(distance <= 2) {
pickObj = hit.transform;
}
}
else {
pickObj.transform.active = false;
}
}
}
}
}
}
replace pickObj.transform.position
at line 16 with pickObj.position
. And also at line 27, pickObj.transform.active
should be replaced with pickObj.active
.
still have the error on
distance = Vector3.Distance(pickObj.position, gameObject.transform.position);