http://docs.unity3d.com/Documentation/ScriptReference/Camera.ViewportPointToRay.html
http://answers.unity3d.com/questions/242983/change-materialstextures-on-mouse-click.html
you should probably work on basic programming concepts first… Before you start trying to cobble scripts together…
The first part DECLARES a few variables, one of which is an array:
var matArray : Material[];
private var index : int;
All that follows is related to these vars. There IS no “Materials array” built into Game Objects. This array must be set up.
if you really wanted to do it this way, here would be how:
first, create a script for your OBJECTS, called “ObjectMaterials”:
var index : int;
var matArray : Material[];
just those two lines will do it…
next, fix your camera script:
function Update () {
// Project a ray going through the center of the screen
var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
var hit : RaycastHit;
// If a ray hits an object, and the user presses the LMB, cycle through the objects' Material array
if (Physics.Raycast (ray, hit)) {
var materialScript : ObjectMaterials = hit.transform.gameObject.GetComponent(ObjectMaterials);
if(materialScript && Input.GetMouseButtonDown(0)){
Debug.Log("Clicked! : " + hit.transform.gameObject);
materialScript.index++;
materialScript.index = materialScript.index % materialScript.matArray.Length;
hit.transform.gameObject.renderer.material = materialScript.matArray[materialScript.index];
}
}
}
once you add copies of the first (two line) script to your objects (make sure it has the right name!), you must then set the length of the array and add materials to it. This can be done via the Inspector panel, with the object selected… (They would also need a Collider attached)
Once it’s all set up it should work…