Accessing an objects' material array from a ray hit

Okay I’m a complete scripting noob so my attempt at this is a bit rubbish at the minute and I could use some help.

I have a ray projecting from my camera. I want to point it at an object and then left click on that object to cycle through its material array. So far I have this (copied and pasted from other scripts so I dont really know what I’m doing). I can’t get it to work. Where am I going wrong?

private var index : int;
var e : Event = Event.current;

function Update () {    
// Project a ray going through the center of the screen    
public var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));    

// If a ray hits an object, and the user pressess the LMB, cycle through the objects' Material array
if (Physics.Raycast (ray, hit)) {
    if(e.button == 0 && e.isMouse){
       Debug.Log("Left Click");
       index++;
       index = index % matArray.Length;
       renderer.material = matArray[index];
       }
    }
}

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…