AlpakaJoe
AlpakaJoe

Reputation: 593

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

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:

Upvotes: 4

Views: 6045

Answers (2)

Jallrich
Jallrich

Reputation: 469

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;
  }
}

Upvotes: 1

Programmer
Programmer

Reputation: 125455

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();
}

Upvotes: 16

Related Questions