UI Buttons and physics.
I am working on a 2D game that mixes the UI with the physics. Let's suppose we have 4 buttons (left, up, right, down), in a canvas, and whenever a button is pressed, we apply forces to one RigidBody2D and move it.
My question is:
Which code is more efficient, and better performance wise?
Version I. (Buttons)
void Start(){
this.leftControl.onClick.AddListener(() => { MoveLeft(); });
}
void MoveLeft(){
GetComponent<RigidBody2D>().AddForce(Vector2.left);
}
Version II. (GameObjects)
Or instead of buttons, adding 4 GameObjects and detect the "click" with RayCasts.
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero);
if (hit.collider != null){
string colliderTag = hit.collider.gameObject.tag;
if (colliderTag == "LeftControl" ) {
GetComponent<RigidBody2D>().AddForce(Vector2.left);
}
}
I like the version I better, but I am not sure it even is good praxis. My main concern is the performance, because in the version II the detection is on Update() method, while in the Version I, I don't know how often is the "listener" checked.
Thanks, and I am sorry if the question is stupid, I am new to Unity.
Your answer
Follow this Question
Related Questions
UI button not working (Unity 3D) 0 Answers
Problem with Application.Quit 2 Answers
Creating dynamically moving buttons/GUI objects. 1 Answer
A doubt on loading Scenes 0 Answers