Object reference not set to an instance of an object when using touch controls

Hey there…

After I have deployed the game into a device, I am running it and, some times, I have 2 errors, when moving to the right or left and trying to go to the opposite direction:

  1. Exception: Object reference not set to an instance of an object
    Type: System.NullReferenceException
    Module: Assembly-CSarp
    InnerException:
    AdditionalInfo:
    at PlayerController.MovingWithTouchs()
    at PlayerController.FixedUpdate()
    at PlayerController.$Invoke0(Int64 Instance, Int64* args)
    at UnityEngine.Internal.$MethodUtility.InvokeMethod(Int64 Instance, Int64*args, IntPtr method)

NullReferenceException: Object reference not set to an instance of an object.

  1. The character acts weird, meaning, sometimes you lift up your finger but still moving and sometimes it does not respond inmediately, when you try to go to the other direction.

This is the whole PlayerController script:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float _speed = 10f;
    public bool _right = true;

    public GameObject player;

    private float waitTime;
    public bool lostLife;
    public GameObject _losingLifeObject;
    public Transform PPosition;

    public GameObject LLP;

    public bool izquierda;
    public bool derecha;

    // Update is called once per frame
    void Update () {
        if (lostLife)
        {
            waitTime += Time.deltaTime;
            if (waitTime >= 3)
            {
                LLP.transform.position = new Vector3(-100, -100, 0);
                InstantiatePlayer();
                waitTime = 0;
                lostLife = false;
            }
        }
    }

    void FixedUpdate()
    {
        float move = Input.GetAxis("Horizontal");
        rigidbody2D.velocity = new Vector2(move * _speed, rigidbody2D.velocity.y);
        if (move > 0 && !_right)
            Flip();
        else if (move < 0 && _right)
            Flip();

        MovingWithTouchs();

    }

    void Flip()
    {
        _right = !_right;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

    void OnTriggerEnter2D(Collider2D c)
    {
        string layerName = LayerMask.LayerToName(c.gameObject.layer);

        if (layerName == "fruits")
        {
            ScoreScript.AddPoint(FindObjectOfType<FruitsScript>().points);
            Destroy(c.gameObject);
        }
        if (layerName == "enemy")
        {
            Destroy(c.gameObject);
            FindObjectOfType<PlayerCreation>()._heart = true;
            InstantiateLoser();
            FindObjectOfType<GroundScript>().grounded = true;
            lostLife = true;
            if (!_right)
            {
                Flip();
            }
           
            FindObjectOfType<PlayerCreation>().player.transform.position = new Vector3(-100, -100, 0);
        }
    }
    private void InstantiatePlayer()
    {
        FindObjectOfType<PlayerCreation>().createPlayer = true;
    }

    public void InstantiateLoser()
    {
        LLP = Instantiate(_losingLifeObject, PPosition.transform.position, PPosition.transform.rotation) as GameObject;
    }

    void MovingWithTouchs()
    {
        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);

        if (Input.touchCount > 0)
        {
            for (int i = 0; i < Input.touchCount; i++)
            {
                Touch t = Input.GetTouch(i);

                if (t.phase == TouchPhase.Began)
                {
                    if (hit.collider.tag == "LeftArrow")
                    {
                        izquierda = true;
                        MoveLeft();
                    }
                    if (hit.collider.tag == "RightArrow")
                    {
                        derecha = true;
                        MoveRight();
                    }
                }
                if (t.phase == TouchPhase.Stationary)
                {
                    if (hit.collider.tag == "LeftArrow")
                    {
                        izquierda = true;
                        MoveLeft();
                    }
                    if (hit.collider.tag == "RightArrow")
                    {
                        derecha = true;
                        MoveRight();
                    }
                }
                if (t.phase == TouchPhase.Ended)
                {
                    if (hit.collider.tag == "LeftArrow")
                    {
                        izquierda = false;
                    }
                    if (hit.collider.tag == "RightArrow")
                    {
                        derecha = false;
                    }
                }
            }
        }
    }

    void MoveLeft()
    {
        if (izquierda)
        {
            if (_right)
            {
                Flip();
            }
            this.transform.Translate(Vector3.left * 7.0f * Time.deltaTime);
            derecha = false;
        }
    }

    void MoveRight()
    {
        if (derecha)
        {
            if (!_right)
            {
                Flip();
            }
            this.transform.Translate(Vector3.right * 7.0f * Time.deltaTime);
            izquierda = false;
        }
    }
}

Any ideas on how to fix it?

From Physics2D.Raycast documentation (Unity - Scripting API: Physics2D.Raycast):

I suspect to bolded part is what is happening - you never check whether it actually hits anything.

By the way - Visual Studio should point you at the exact line where the exception is getting thrown of you enable break on exception by going to Debug → Exceptions, ticking Common Language Runtime Exceptions and pressing OK.

What I am guessing is that maybe the exception occurs when there´s something else with a collider on the same spot:

My right and left arrows are just invisible GOs taking half of the screen each and, because of that, sometimes the playable character is in the middle…

What do you think?

(by the way, I cant check on VS, because this is a WP game I am making)

What do you mean? You can debug Unity apps/your scripts running on Windows Phone just fine using Visual Studio.