Question by
YahavHadad · Jul 26, 2017 at 03:43 PM ·
2dmovementphysicsbutton
How tou use a UI Button to move Player?
Hi, I'm trying to make an onClick event that will move the player right or left. The game is a 2D game.
When I click the Buttons I get two errors. One says: NullReferenceException : object reference not set to an instance of an object, and the other one says: There is no 'Rigidbody2D' attached to the "Right" game object, but a script is trying to access it. You probably need to add a Rigidbody2D to the game object "Right". Or your script needs to check if the component is attached before using it.
I'v set and RigitBody2D to the player, and a BoxCollider to the buttons
Here is my code: Buttons code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Movement : MonoBehaviour {
private Button Right;
private Button Left;
private Rigidbody2D ship;
// Use this for initialization
void Start () {
Button Right = GetComponent<Button> ();
Right.onClick.AddListener(MovementRight);
Button Left = GetComponent<Button>();
Left.onClick.AddListener(MovementLeft);
ship = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
}
void MovementRight()
{
Debug.Log ("Player Moved Right");
ship.velocity = Vector2.zero;
ship.AddForce (new Vector2 (200f, 0));
}
void MovementLeft()
{
Debug.Log ("Player Moved Left");
ship.velocity = Vector2.zero;
ship.AddForce (new Vector2 (-200f, 0));
}
}
Player Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ship : MonoBehaviour {
public float upForce;
public Rigidbody2D ship;
public GameObject Player;
// Use this for initialization
void Start () {
ship = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(1))
{
ship.velocity = Vector2.zero;
ship.AddForce(new Vector2(0, 200f));
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612131231im_/https://answers.unity.com/themes/thub/images/avi.jpg)