J
J
Jekol2018-05-02 18:52:22
C++ / C#
Jekol, 2018-05-02 18:52:22

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

Joystick movement script. 2 objects central (moving) (joystick) and static (joystickBG) NullReferenceException: Object reference not set to an instance of an object.

spoiler
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class MobileController : MonoBehaviour,IDragHandler,IPointerUpHandler,IPointerDownHandler 
{

  private Image joystickBG;
  [SerializeField]
  private Image joystick;
  private Vector2 inputVector;

  private void start ()
  {
    joystickBG = GetComponent<Image>();
    joystick = transform.GetChild(0).GetComponent<Image>();
  }

  public virtual void OnPointerDown(PointerEventData ped)
  {
    OnDrag (ped);
  }

  public virtual void OnPointerUp(PointerEventData ped)
  {
    print ("PointerUP");
    inputVector = Vector2.zero;
    joystick.rectTransform.anchoredPosition = Vector2.zero;
  }

  public virtual void OnDrag(PointerEventData ped)
  {
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle (joystickBG.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
      pos.x = (pos.x / joystickBG.rectTransform.sizeDelta.x);
      pos.y = (pos.y / joystickBG.rectTransform.sizeDelta.y);

      inputVector = new Vector2 (pos.x * 2 - 1, pos.y * 2 - 1);
      inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

      joystick.rectTransform.anchoredPosition = new Vector2(inputVector.x * (joystickBG.rectTransform.sizeDelta.x / 2), inputVector.y * (joystickBG.rectTransform.sizeDelta.y / 2));
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2018-05-02
@Jekol

The manual even has a special article about this exception. You should start by double-clicking on an error in the console, you will have to open an editor with a highlighted line in which the error occurred. In most cases, this is enough, and you can immediately understand which object turned out to be null and why. If you don’t figure it out right away, then either connect with a debugger and see what doesn’t work there, or cover everything with debugs and read the console.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question