- Home /
HitTest giving NullReferenceException when the mouse is not over some GUI element
Working on a project (as a noob) and got a question about HitTest. Im working on a PC, but my game is targeted for iOS, iPhone4. Its a car game.
The script csGasProba is attached to my main camera, and for public GUILayer test i selected my main camera. Now when ever my mouse is not over GUI element i get:
NullReferenceException csGasProba.Update () (at Assets/Scripts/test_scripts/csGasProba.cs:)
Just tested it on iPhone and when i press and release the Gas button the car accelerates as if the Gas was pressed, but if i press the Gas the car accelerates and then if i press some other GUI element the Gas stops accelerating. I have an empty GameObject with component GUITexture, this is the Gas. and i have another Brake and Wheel gameObjects with GUITextures as components.
please help, any info or link will be helpfull
using UnityEngine;
using System.Collections;
public class csGasProba : MonoBehaviour {
public GUILayer test;
void Update()
{
if (test.HitTest(Input.mousePosition).name == "GAS")
{
csRoadMovement.roadSpeed += 2f*Time.deltaTime;
}
if (test.HitTest(Input.mousePosition).name == "BREAK")
{
csRoadMovement.roadSpeed -= 4f*Time.deltaTime;
}
}
}
Answer by Paulius-Liekis · Nov 27, 2012 at 02:14 PM
First check that result of test.HitTest(Input.mousePosition) is not null and then use name property on it.
SOLVED.
Thank you Paulius, just did that and no more null reference errors, here is the final code that works:
using UnityEngine;
using System.Collections;
public class csGasProba : $$anonymous$$onoBehaviour {
public GUILayer test;
void Update()
{
if (test.HitTest(Input.mousePosition) != null)
{
if (test.HitTest(Input.mousePosition).name == "GAS")
{
csRoad$$anonymous$$ovement.roadSpeed += 2f*Time.deltaTime;
}
if (test.HitTest(Input.mousePosition).name == "BREA$$anonymous$$")
{
csRoad$$anonymous$$ovement.roadSpeed -= 4f*Time.deltaTime;
}
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity event calling function gets nullreferencexception on bool 0 Answers
NullReferenceException script problem? 0 Answers
[Roll-a-ball] Changing UI text (NRE) 0 Answers