Search Unity

Help with script: Staying on button and press key = Erase a wall [solved]

Discussion in 'Scripting' started by LinkingPixels, Oct 18, 2019.

  1. LinkingPixels

    LinkingPixels

    Joined:
    Mar 20, 2019
    Posts:
    10
    Hi!

    Newbie to C# coding, appreciate to get some help. I have been trying to do following in a 2d game: When the player stay still on a button and press a key(space e.g.) the wall blocking the way will disappear.

    I have written a script that will erase the walls if you press space. But I don’t know how to only enable it if you stay still on the button.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class DestroyOther : MonoBehaviour
    5. {
    6.     public GameObject other;
    7.  
    8.  
    9.     void Update()
    10.     {
    11.         if (Input.GetKey(KeyCode.Space))
    12.         {
    13.             Destroy(other);
    14.         }
    15.     }
    16. }
     
    Last edited: Oct 19, 2019
  2. Deleted User

    Deleted User

    Guest

    What do you mean by "stay still"? Does that mean that the player on the screen is standing on an object or that the player who is handling the mouse device is pressing a button?

    Destroy(other) is generally used in a OnTriggerEnter2D or OnTriggerStay2D.
     
  3. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class EraseWall : MonoBehaviour
    4. {
    5.     // This script only make sense when you only have 1 wall
    6.     // but it will give you an idea to how to expand it
    7.  
    8.     // The wall at need to be erased
    9.     public GameObject wall;
    10.  
    11.  
    12.     /* Using OnTrigger****2D the detecting object need to have a 2D Collider with isTrigger as true
    13.      * The object that need to detect the object need to have a Rigidbody and a 2D Collider.
    14.      *
    15.      * Using OnTriggerStay2D will run the code at every frame when true.
    16.      * Using OnTriggerEnter2D will run the code one time, at entering
    17.      * Using OnTriggerExit2D will run the code one time, at exiting
    18.      */
    19.     private void OnTriggerStay2D(Collider2D other)
    20.     {
    21.         if(other.tag == "WallButton") {
    22.             Destroy(wall);
    23.         }
    24.     }
    25. }
    26.