Hey I am building a 2D game at the moment, with a joystick to move the character around. I Used this Joystick the same on a 3D game that worked fine. However when I am using it on my 2D i get an error saying: NullReferenceException: Object reference not set to an instance of an object
Under the movement line of code in my PlayerController script:
public Rigidbody2D rb;
public float speed;
public Animator anim;
private ManagerJoystick _mngrJoystick;
private float inputX;
private float inputZ;
private Vector2 m_Movement;
void start()
{
rb = GetComponent<Rigidbody2D>();
_mngrJoystick = GameObject.Find("Joystick").GetComponent<ManagerJoystick>();
}
void Movement()
{
inputX = _mngrJoystick.inputHorizontal();
inputZ = _mngrJoystick.inputVertical();
}
void FixedUpdate()
{
Movement();
}
}
This is how the JoyStickManager has been setup at the bottom in the public float Vertical & Horizontal input:
void Start()
{
imgJoystickBg = GetComponent<Image>();
imgJoystick = transform.GetChild(0).GetComponent<Image>();
}
public void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
imgJoystickBg.rectTransform,
eventData.position,
eventData.pressEventCamera,
out posInput))
{
posInput.x = posInput.x / (imgJoystickBg.rectTransform.sizeDelta.x);
posInput.y = posInput.y / (imgJoystickBg.rectTransform.sizeDelta.y);
if (posInput.magnitude > 1f)
{
posInput = posInput.normalized;
}
imgJoystick.rectTransform.anchoredPosition = new Vector2(
posInput.x * (imgJoystickBg.rectTransform.sizeDelta.x / 2),
posInput.y * (imgJoystickBg.rectTransform.sizeDelta.y / 2));
}
}
public void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public void OnPointerUp(PointerEventData eventData)
{
posInput = Vector2.zero;
imgJoystick.rectTransform.anchoredPosition = Vector2.zero;
}
public float inputHorizontal()
{
if (posInput.x != 0)
return posInput.x;
else
return Input.GetAxis("Horizontal");
}
public float inputVertical()
{
if (posInput.y != 0)
return posInput.y;
else
return Input.GetAxis("Vertical");
}
}