2
\$\begingroup\$

When keyboard 'H' is pressed i want the platformer (wall, roof, floor) become invisible when its visible and become visible when its invisible. Like giving the player ability to control visibility of certain wall so he can pass through it.

enter image description here

This is what i do so far but the wall become blink when i press 'H'. Sometimes the wall become invisible but sometimes it just blink.

public class HideWall : MonoBehaviour {

    public SpriteRenderer wall;
    public Collider2D wallCollider;
    public Effector2D wallEffector;
    private bool visible;

    // Use this for initialization
    void Start () {
        wall = GetComponent<SpriteRenderer> ();
        wallCollider = GetComponent<Collider2D> ();
        wallEffector = GetComponent<Effector2D> ();
        visible = true;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.H)) {
            wall.enabled = !wall.enabled;
            wallCollider.enabled = !wallCollider.enabled;
            wallEffector.enabled = !wallEffector.enabled;
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ The word you are looking for is "toggle" \$\endgroup\$ – Soapy Oct 18 '16 at 15:43
7
\$\begingroup\$

Using GetKeyDown() will trigger it only once when the key is actually pressed, removing any blinking that you see. GetKey() will return true for every frame the key is held down which isn't what you want.

Using the code from @Droppy's answer, you just need to simply store the state of hidden walls on the class instance itself (wantToHide).

If you're still stuck, here's the code to do it:

bool wantToHide = false;

void Update () {
    if(Input.GetKeyDown(KeyCode.H)) {
        wantToHide = !wantToHide;
        wall.enabled = !wantToHide;
        wallCollider.enabled = !wantToHide;
        wallEffector.enabled = !wantToHide;
    }
}
\$\endgroup\$
3
\$\begingroup\$

Only make the change if it's not already in the state you want:

void Update () {
    bool wantToHide = Input.GetKeyDown(KeyCode.H);
    bool alreadyHidden = !wall.enabled;
    if (wantToHide != alreadyHidden) {
        wall.enabled = !wantToHide;
        wallCollider.enabled = !wantToHide;
        wallEffector.enabled = !wantToHide;
    }
}

Also processing input within non-player-oriented script is kinda crappy; so create a player controller object and attach it to scene and get that to call the above script when the state changes.

\$\endgroup\$
  • \$\begingroup\$ Using your provided script i must hold 'H' to make the wall invisible. \$\endgroup\$ – Yusufmm Oct 18 '16 at 15:00
  • \$\begingroup\$ @Yusufmm OK, fixed the key method. \$\endgroup\$ – Droppy Oct 18 '16 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.