Vanish one object with renderer.material?

Hello Everyone,

I’m trying to vanish one object using the function “renderer.material.color.a” using the mouse button to active it and re-active it.

I have some time trying but without success. I don’t have experience in Java or Unity Script.

Please Any help is more than welcome.

Please take a look to my script.

	var duration : float = 1.5; // time taken to disappear
	private var alpha: float = 1; // alpha starts at 1
	private var vanish = false;
 


	function Update(){
	
	if (vanish){ // only decrement alpha after button pressed
	alpha -= Time.deltaTime/duration;
	if (Input.GetButton("Fire1")){
	disappear();
	if (Input.GetButtonUP("Fire1")){
	appear();
	}
	}
	}
 
	function disappear(){
	renderer.material.color.a  = alpha; // set alpha f 
	if (alpha > 0){ // only draw t  while it's visible 
	vanish = true; // enable alpha decrement
	}
	}

	function appear(){
	renderer.material.color.a  = alpha; // set alpha  
	if (alpha > 1){ // only draw t  while it's visible 
	vanish = true; // enable alpha decrement
	}
    }

First of all if you want to use transparency you must make sure your shader can handle it. The default diffuse shader will never be transparent. Select a transparent shader from the drop down menu of the material.

About your code. It is a bit strange how you manipulate your alpha value. The alpha value is always between 0 and 1 so checking if your reference is greater 1 is quite fishy. You can use Mathf.Lerp to manipulate the alpha value in a smooth way. Try:

var fadeSpeed : float = 10;
function Update(){

    if(vanish){
        renderer.material.color.a = Mathf.Lerp(renderer.material.color.a, 0, Time.deltaTime * fadeSpeed);
    } else {
        renderer.material.color.a = Mathf.Lerp(renderer.material.color.a, 1, Time.deltaTime * fadeSpeed);
    }
    if(Input.GetButtonDown("Fire1")){      //You only need to check once not every frame like you did
        vanish = true;
    }
    if(Input.GetButtonUp("Fire1")){
        vanish = false;
    }
}

The Mathf.Lerp gets things done in a smooth way. The first if checks if the button is pressed down and sets vanish to true. The second if does the opposit when the button is released. The GetButton you used would set the value every frame as long as the button is held down.