How to Give Player Ability to Toggle Visibility of The Wall

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 wall so he can pass through it. Not only wall, the player can also toggle visibility of roof and floor.

80405-konsep.png

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;
		}
	}
}

Input.GetKey means “Hold” the key. So If you “press” the H key and “up” within 1 second, it may execute (1/Time.deltaTime) times.

Use GetKeyDown instead, it execute only once when you press it.