Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

I want an event to occur when my gameobject is in a collider, and a button was pressed?

Discussion in 'Scripting' started by Ben555, Sep 19, 2020.

  1. Ben555

    Ben555

    Joined:
    May 22, 2019
    Posts:
    13
    Right now I have this:

    Code (CSharp):
    1.  private void OnTriggerStay(Collider collider)
    2. {
    3.      if (collider.gameObject.tag == "Pickup" && buttonPress == true)
    4.      {
    5.          GameObject spawnNeutral = (GameObject)Instantiate(neutral, transform.position, transform.rotation);
    6.      }
    7. }
    8. public void SpawnButton()
    9. {
    10.      buttonPress = true;
    11. }
    However once the button is pressed, then the gameobject can enter the trigger whenever and it will work. I only want it to work when it is inside the trigger.
     
  2. Zer0Cool

    Zer0Cool

    Joined:
    Oct 24, 2014
    Posts:
    203
    Code (CSharp):
    1. bool allowButtonPress = false;
    2.  
    3. private void OnTriggerStay(Collider collider)
    4. {
    5.      allowButtonPress = true;
    6.      if (collider.gameObject.tag == "Pickup" && buttonPress == true)
    7.      {
    8.          GameObject spawnNeutral = (GameObject)Instantiate(neutral, transform.position, transform.rotation);
    9.          buttonPress = false; // i assume you should reset the button press here
    10.      }
    11. }
    12.  
    13. private void OnTriggerExit(Collider collider)
    14. {
    15.      allowButtonPress = false;
    16. }
    17.  
    18.  
    19. public void SpawnButton()
    20. {
    21.    if (allowButtonPress) buttonPress = true;
    22. }
     
    Last edited: Sep 19, 2020