How can I combine GUI button with script that is put on different gam objects?

My problem is: I have written a C# script which allows me to switch between different materials. The materials are used on several different game objects. When I control the switching by the function: if (Input.GetKeyDown(KeyCode.K)) everything works fine. All the game objects change their material.
Now, when I want to use a GUI button: if (GUI.Button (new Rect (10,10,150,100), “button”)) to control the switching of the materials it works only on 1 game object not on all as it is desired.
Can anybody tell me why this happens or how I can manage this problem???

Thanx to everyone!!!

Aljoscha

using UnityEngine;
using System.Collections;

public class SWP2 : MonoBehaviour {

public Material[] mats;
public GameObject ga;
private int index = 0;

// Use this for initialization
void Start () {
	ga.renderer.material = mats[index];
}

// Update is called once per frame
void Update () {
	if (Input.GetKeyDown(KeyCode.K))
	{
		index++;
		if (index > mats.Length - 1)
		{
			index = 0;
		}
		ga.renderer.material = mats[index];
	}
}

}

For what you outline a simple solution is to change the texture of the sharedMaterial.

  • Attach the following to script to an empty game object
  • Drag an drop any one of the game objects that you want to change to the ‘ga’ variable
  • Set the size of the texs, and drag and drop textures into the slots
  • Hit play

Note that when you stop the app, you will see the last material displayed. That is, when run in the editor, it makes a permanent change to the material. That is why the first texture is assigned in Start(). This will work fine in a build.

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

	public GameObject ga;
	public Texture[] texs;
	private int index = 0;

	void Start() {
		ga.renderer.sharedMaterial.mainTexture = texs[0];
	}

	void OnGUI() {
		if (GUI.Button (new Rect(10,10, 75, 35), "Change")) {
			index = (index + 1) % texs.Length;
			ga.renderer.sharedMaterial.mainTexture = texs[index];
		}
	}
}

Note that there other approaches more along the lines of what you were seeking to do. So if this does not work for you, I’ll be glad to outline an alternate solution.