Search Unity

Button in conflict with Instantiate

Discussion in '2D' started by Silasi, Jul 21, 2019.

  1. Silasi

    Silasi

    Joined:
    Jul 25, 2016
    Posts:
    48
    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:
    1. Object is instantiated
    2. Button is pressed
    3. 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...
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Don't instantiate on
    GetTouch()
    ; use the button's onClick event instead.
     
  3. Silasi

    Silasi

    Joined:
    Jul 25, 2016
    Posts:
    48
    You mean use onClick for the button?

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class Player : MonoBehaviour
    5. {
    6.     public Button settingsButton;
    7.  
    8.     private void Start()
    9.     {
    10.         settingsButton.onClick.AddListener(TaskOnClick);
    11.     }
    12.  
    13.     public void TaskOnClick()
    14.     {
    15.         Debug.Log("Settings Button Pressed Using OnClick");
    16.     }
    The order with the script:
    1. Object instantiated
    2. Button Pressed
    3. Settings Button Pressed Using OnClick
     
  4. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    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.
     
    Silasi likes this.
  5. Silasi

    Silasi

    Joined:
    Jul 25, 2016
    Posts:
    48
    YES. Thank you, I thought I would never fix it, it works now. Thank you, sir.