Button in conflict with Instantiate

Hi there,

I have a settings button and an instantiate script which instantiates to Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position). When I touch the button, first it instantiates and then it activates the button. I don’t want that.
I did some debugging and the order of actions when the button is clicked is:

  • Object is instantiated
  • Button is pressed
  • Instantiating permission turned off

I don’t really know how to change that order of actions so nothing is instantiated when the button is pressed…

Don’t instantiate on GetTouch(); use the button’s onClick event instead.

You mean use onClick for the button?

using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    public Button settingsButton;

    private void Start()
    {
        settingsButton.onClick.AddListener(TaskOnClick);
    }

    public void TaskOnClick()
    {
        Debug.Log("Settings Button Pressed Using OnClick");
    }

The order with the script:

  1. Object instantiated
  2. Button Pressed
  3. Settings Button Pressed Using OnClick

My bad, I misread the OP thinking you wanted to instantiate the object after the button was pressed.

You can check if you have touched a UI element using IsPointerOverGameObject.
If true, then a UI element has been touched. You can try instantiating the object only when this returns false.

1 Like

YES. Thank you, I thought I would never fix it, it works now. Thank you, sir.