Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: How to stop using "Input.GetMouseButton(0)" when pressing on UI Button?

Tags:

c#

unity3d

The player is a magican who can attack enemys with fireballs when pressing the left mouse button.

The code i use is pretty simple (inside the Update function):

if (Input.GetMouseButton(0) && canShoot)
{
    canShoot = false;
    Invoke("AllowCanShoot", fireBreak);
    Attack();
}

canShoot is a bool which stops the player from attacking once per frame.

AllowCanShoot is a function that sets canShoot to true.

Attack() is the function that handles the attack, not relevant for this question.

I also have a UI Button that appears on screen when the player is near the trader. When the player presses the UI Button he attacks the trader.

What i want is, that he could press the button without attacking him.

I can't disable attacking for the player, because enemys can get to the trader, too, and the player may have to fight then.

What i tried is:

  • setting the canShoot bool to false, when the UI Button is pressed, but this isn't working, the player is still attacking, maybe the Update function gets executed before the UI Button function?!
like image 427
AlpakaJoe Avatar asked Dec 06 '22 11:12

AlpakaJoe


2 Answers

You can use the EventSystem.IsPointerOverGameObject() function to make sure that the mouse is not over a UI object before attacking:

if (Input.GetMouseButton(0) && canShoot && !EventSystem.current.IsPointerOverGameObject())
{
    canShoot = false;
    Invoke("AllowCanShoot", fireBreak);
    Attack();
}
like image 186
Programmer Avatar answered Dec 13 '22 03:12

Programmer


If you can't disable attacking for the player, can you make it that when aiming at the trader, the player can't attack him?

Use a Raycast when near the trader.

Something like this maybe?

void NearTrader()
{
  if (Vector3.Distance(trader.position, player.position) < myDistance)
  {
    RaycastHit hit;

    if (Physics.Raycast(player.position, PlayerCamera.transform.forward, out hit, myRange))
      canShoot = false;
    else
      canShoot = true;
  }
}
like image 26
Javier Bullrich Avatar answered Dec 13 '22 05:12

Javier Bullrich