- Home /
NullReferenceException: Object reference not set to an instance of an object follow.move ()
I am tryin to get the co-ordinates of the input and move a sphere to that position.This script is attached to a normal sphere.But it says NullReferenceException: Object reference not set to an instance of an object at else in the code. Once I hit Run this error is being generated multiple times
I am a newbie to unity and scripting....Thanks in advance
using UnityEngine; using System.Collections;
public class follow : MonoBehaviour {
Vector3 pos;
void Start () {
Screen.sleepTimeout = SleepTimeout.NeverSleep;
pos = transform.position;
}
void Update ()
{
move ();
}
public void move()
{
if (Application.platform == RuntimePlatform.Android)
{
pos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.GetTouch (0).position.x, Input.GetTouch (0).position.y,1));
}
else
pos = Camera.main.ScreenToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,1));
transform.position = new Vector3(pos.x,pos.y,pos.z);
}
}
Answer by robertbu · Oct 01, 2014 at 04:33 AM
For future questions please format your code. After pasting, select your code and use the 101/010 button. And please include a copy of the error from the console as well. It gives us the line number and stack trace.
Your problem is this line:
pos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.GetTouch (0).position.x, Input.GetTouch (0).position.y,1));
Input.GetTouch(0) will be return null if no finger is touching the screen. Do it this way:
if (Input.touchCount > 0) {
Vector3 v = Input.GetTouch(0);
pos = Camera.main.ScreenToWorldPoint(new Vector3(v.x, v.y, 1));
}
Your answer
Follow this Question
Related Questions
List search gives null 2 Answers
need help with C# component reference 1 Answer
NullReferenceExeption on OnCharacterControllerHit 1 Answer
C# about NGUITools.AddChild and GetComponent Null 0 Answers
Strange NullReferenceException 1 Answer