- Home /
Using Ray cast for click to move
Trying to create a click to move system that is networked with Photon PUN, I am wanting it to move from a right click which is pretty straightforward but when I right click in game I get the following error
NullReferenceException: Object reference not set to an instance of an object SendInfo.Update () (at Assets/SendInfo.cs:14)
After digging a little in Visual Studio I noticed that the "ray" variable is = 0 on all points (direction and origin) and that the "hit" variable has a "lightmapCoord" that is throwing the following error
System.NullReferenceException: Object reference not set to an instance of an object
My code so far is as follows
using UnityEngine;
using System.Collections;
using Photon.Pun;
public class SendInfo : MonoBehaviour
{
void Update()
{
bool RMB = Input.GetMouseButtonDown(1);
if (RMB)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit) && hit.transform.CompareTag("Ground"))
{
this.GetComponent<PhotonView>().RPC("RecievedMove", RpcTarget.All, hit.point);
}
}
}
}
I cant see any obvious reason as to why it wouldn't be working but never really used ray casts before
Answer by VideoJames · Dec 12, 2019 at 01:52 AM
Looking at the error there is a null reference on line 14. The only thing I can see that can be null in that line is Camera.main Did you remove the Main Camera tag from your camera?
Answer by lgarczyn · Dec 12, 2019 at 12:03 AM
Did you check the value of hit after the raycast, or before?
Anyway, there's two possible problems: on this line
this.GetComponent<PhotonView>()
You don't actually check that the GetComponent returned null or not. You could do this:
this.GetComponent<PhotonView>()?.RPC("RecievedMove", RpcTarget.All, hit.point);
But it would do nothing if the first object your raycast hit doesn't have the component.
The other possible problem is your usage of the out variable. I wasn't even aware you could declare it inside the call, and it might be unadvisable. Change to this and try:
RaycastHit hit;
if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Ground"))
{
Your answer
Follow this Question
Related Questions
Can you figure out raycast origin position from RacyastHit? 2 Answers
Can't find a clone object with RayCast? [Solved] 2 Answers
Raycast script help? 1 Answer
Raycast hit in OnDrawGizmos but not in Update 1 Answer
Vehicle is vibrating on the edge of the ramp/surface when I get the normal of the surface 0 Answers