- Home /
NullReferenceException when using Single Joystick prefab
Hi everybody
I have the following problem with the Single Joystick prefab (in Standard Assets Mobile)
I drop the Single Joystick into my scene
Parameters : Dead Zone x = 0, y = 0.5, Normalized = checked
I want to read its x position. So here is what I wrote in my script :
var speedRotation = 3.0;
function Update()
{
var joy:Joystick = GetComponent(Joystick);
transform.Rotate(0, joy.position.x * speedRotation, 0); // this is the line in error in the console
}
When I launch my game, the console shows me the following error for this line :
NullReferenceException: Object reference not set to an instance of an object
It seems like the "joy" variable is null. So am I doing something wrong ? I tried to put the GetComponent(Joystick) in the Start() function, but same problem.
Thanks in advance
No, I just dropped the prefab into my scene. This prefab is not attached to any object, it is global. What is attached to my object is only this script. I tried to insert the prefab as a "son" of my object in the hierarchy, but I have the same problem.
An instantiated prefab is never 'global'. I'm not sure we're talking about the same thing here. What components does the object in question contain? You need to have a component of type 'Joystick' for that line to work.
This object has 3 components : - Transformation - GUITexture - Joystick
In my scene, I have created a cube and I want to control it with this joystick. So I dropped the prefab "Single Joystick" into my scene, and I dropped the script above on the cube.
Edit: maybe I should call GameObject.Find() before GetComponent(), to get a handler to my prefab ?
Answer by Harko33 · May 19, 2012 at 03:37 PM
var joy:Joystick = GameObject.Find("Single Joystick").GetComponent(Joystick);
did the trick ! Thanks to sysclamoth for inspiring me :)