Question by
Kyura21 · Mar 31, 2017 at 07:38 AM ·
unity 5raycastnullreferenceexceptionray
Ray null reference exception and wrong direction when casting it
Hi All,
in a few words here's my problem:
I got a camera attached to a MouseManager script (C#). I got an aquarium were some fishes spawn and go happy to theyr life. From this view i need to cast a ray to the acquarium on the mouse click ( i have to select the fishes from the mouse click ). then i need to attach the transform of the fish selected from the mouse click to the mouse position (drag & drop).
Here's my code.
public class MouseManager : MonoBehaviour {
public Camera Camm;
void Start(){
RaycastHit vHit = new RaycastHit();
Ray raggio = Camm.ScreenPointToRay(Input.mousePosition);
}
void Update(){
if (Input.GetMouseButtonDown (0)) {
if(Physics.Raycast(raggio,out vHit,1000)){
//Physics.Raycast (raggio, out vHit, 100);
Debug.DrawRay (raggio.origin, raggio.direction * 10, Color.red, 1);
Debug.Log(vHit.collider.gameObject);
}
}
if (umano.cam1.transform.position == umano.pos3.transform.position) {
if (Input.GetMouseButtonDown (0) && Physics.Raycast (raggio, out hit, 100)) {
//Physics.Raycast (raggio, out hit, 10);
Debug.DrawRay (raggio.origin, raggio.direction * 10, Color.red, 3);
Debug.Log(hit.collider.gameObject);
if (hit.collider.tag == "pesce") {
Debug.Log (hit.collider.gameObject);
}
}
}
}
public void OnMouseDown(){
dist = Camera.main.WorldToScreenPoint (transform.position);
posx = Input.mousePosition.x - dist.x;
posy = Input.mousePosition.y - dist.y;
}
public void DragDrop(){
Vector3 curPos = new Vector3 (Input.mousePosition.x - posx, Input.mousePosition.y - posy, dist.z);
Vector3 worldPos = Camera.main.ScreenToWorldPoint (curPos);
transform.position = worldPos;
}
}
The problem is that the ray it's going everywhere but not in the position of the mouse.
Someone can help me?
Kind regards
Comment