Change object's material using GUI buttons via scripting

Hi…

I have a scene with “First Person Controller”, and 3 objects,
In run time I want to disable the “First Person Controller”, so I be able to use the mouse to click any of the 3 GUI buttons to change the material of the clicked object.
After that I want to enable the “First Person Controller” to move around again, so I can repeat the same sequence to deal with another object…

A friend helped me with 2 scripts:

  1. Camera code named “GUICam.js” linked with the camera of the “First Person Controller”

    var button1_tex : Texture;

    var button2_tex : Texture;

    var button3_tex : Texture;

    var materials : Material;

    var object : Renderer;

    var select : boolean = false;

    private var mouseLook : MouseLook;

    private var playerMouseLook : MouseLook;

    function Awake ( ) {

     mouseLook = transform.GetComponent(MouseLook);
    
     playerMouseLook = GameObject.FindGameObjectWithTag('Player').GetComponent(MouseLook);
    

    }

    function OnGUI ( ) {

     	if(select)
    
     {
    
     	Time.timeScale = 0;
    
     	mouseLook.enabled = false;
    
     	playerMouseLook.enabled = false;
    
     	
    
     	if ( GUI.Button (Rect (100, 570, 40, 40), button1_tex) )
    
     		changeTex(materials[0]);
    
     	
    
     	if ( GUI.Button (Rect (175, 570, 40, 40), button2_tex) )
    
     		changeTex(materials[1]);
    
     	
    
     	if ( GUI.Button (Rect (250, 570, 40, 40), button3_tex) )
    
     		changeTex(materials[2]);
    
     }
    

    }

    function changeTex(material : Material) {

     object.material = material;
    
     select = false;
    
     Time.timeScale = 1;
    
     mouseLook.enabled = true;
    
     playerMouseLook.enabled = true;
    

    }

  2. Object’s code, linked to the 3 Objects in the scene

    private var cam : GUICam;

    function Awake () {

     cam = Camera.main.GetComponent(GUICam);
    

    }

    function OnMouseDown () {

     cam.object = renderer;
    
     cam.select = true;
    

    }

So far it is ok, but…

In run time when I click an object, the GUI buttons appear and the view is freeze, then if I click any of the GUI buttons the material is changed but all GUI buttons disappear…!!? this is what I don’t like, I want they to be on the screen all the time…

I searched in Unity Answers, and found this

I tried this code to disable mouselook script in the “First Person Controller”

function Update () {

if (Input.GetKeyUp(KeyCode.Escape)) {

    var mouseLook = GetComponent.<MouseLook>();

    mouseLook.enabled = !mouseLook.enabled;

}



}

But unfortunately the GUI buttons still disappear each time I click any of them…

My request is, any help to fix the problem…!!?

Thanks in advance;

In changeTex you set select = false - that is what hides your GUI buttons… Remove it and put in some other control to turn them off.