Changing visibility of objects with game tag

I’m trying to basically make some objects with a certain tag invisible on a key press in my controller script. I’m not sure how to search for all the game objects with a certain tag and change their visibility from the controller script. If I attach the following to the individual objects it works fine however I would rather have it controlled from one place rather than having a script attached to all the objects I want to affect.

void Update () {
	if (Input.GetKey(KeyCode.Space))
	{
		renderer.enabled = false;
		collider.enabled = false;
	}
}

Like I said this works fine if attached straight to the object however how would I change it to work from one script by finding their tags then setting the renderer and collider to false. I’ve looked at the GameObject.FindGameObjectsWithTag script reference however I’m getting confused with the foreach () section. Any pointers would be appreciated.

Note in your original code, you should have been using ‘GetKeyDown’ instead of ‘GetKey’. ‘GetKey’ is called every frame while the key is held down resulting in multiple unnecessary settings of your variables. Here is a bit of code that uses the tags to set the enabled flags for the renderer and the collider.

void Update () {
	if (Input.GetKeyDown(KeyCode.Space)) {
		GameObject[] gos = GameObject.FindGameObjectsWithTag("SomeTag");
		foreach (GameObject go in gos) {
			go.renderer.enabled = false;
			go.collider.enabled = false;
		}
	}
}