I get the error “Object reference not set to an instance of an object
Testprog.CastRay ()
(at Assets/TestProg.cs:38)
TestProg.Update () (at Assets/TestProg.cs:19)”
using UnityEngine;
using System.Collections;
public class ColorChanger : MonoBehaviour {
Color selectColor=Color.blue;
public Texture2D blueButton=null,greenButton=null;
//public GameObject red,red2,yellow,yellow2;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
Debug.Log(“Pressed left click, casting ray.”);
CastRay();
}
}
private void OnGUI()
{
if (GUI.Button (new Rect (400, 30, 50, 75), blueButton))
selectColor = Color.blue;
if (GUI.Button (new Rect (450, 30, 50, 75), greenButton))
selectColor = Color.green;
}
Is it tagged “MainCamera”, though? Would help if we had line numbers. Which line are you getting the error on?
Another thing. “if (hitInfo != null)” isn’t good. It’s just “if (hitInfo)”. RayCast doesn’t return null. So, you could be erroring out in the next line when no collider was hit.
I’m thinking the issue is on the line after that, actually. I don’t think “hitInfo != null” is equivalent to a guarantee that hitInfo has valid data - so hitInfo.collider might be null, in which case hitInfo.collider.gameObject would throw that error. You need to check if hitInfo.collider is null, instead. (as in the documentation’s example)
(Sidenote: I was thinking that Physics2D.Raycast worked the same way as Physics.Raycast, until I looked up the documentation in response to your code. It does not work the same - with Physics.Raycast, it returns a bool and passes out RaycastHit as an output parameter.)
voidStart()
{}// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log(“Pressed left click, casting ray.”);
CastRay();}
}
void CastRay()
{
Ray ray =Camera.main.ScreenPointToRay(Input.mousePosition);RaycastHit2D hit =Physics2D.Raycast(ray.origin, ray.direction,Mathf.Infinity);