Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Button in conflict with Instantiate

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

  1. Cobra_2o1o

    Cobra_2o1o

    Joined:
    Jul 25, 2016
    Posts:
    30
    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:
    727
    Don't instantiate on
    GetTouch()
    ; use the button's onClick event instead.
     
  3. Cobra_2o1o

    Cobra_2o1o

    Joined:
    Jul 25, 2016
    Posts:
    30
    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:
    727
    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.
     
    Cobra_2o1o likes this.
  5. Cobra_2o1o

    Cobra_2o1o

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