If you have an object with a material that supports color transparency, you can use this script to control it’s transparency in run time. For example you can make some buttons and use one of 2 methods available in this script to set its transparency.
It has two kind of transparency changing feature, one is simple changing without fading, the second one has fading feature and you can adjust the duration in second for that fading effect.
Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetTransparency : MonoBehaviour
{
public float defaultTransparency = 1f;
public float fadeDuration = 3f;
float currentTransparency;
float toFadeTo;
float tempDist;
bool isFadingUp;
bool isFadingDown;
void Start()
{
currentTransparency = defaultTransparency;
ApplyTransparency();
}
void FixedUpdate(){
if(isFadingUp){
if(currentTransparency < toFadeTo){
currentTransparency += (tempDist/fadeDuration) * Time.deltaTime;
ApplyTransparency();
}else{
isFadingUp = false;
}
}
else if(isFadingDown){
if(currentTransparency > toFadeTo){
currentTransparency -= (tempDist/fadeDuration) * Time.deltaTime;
ApplyTransparency();
}else{
isFadingDown = false;
}
}
}
void ApplyTransparency(){
GetComponent<MeshRenderer>().material.color = new Color(1.0f, 1.0f, 1.0f, currentTransparency);
}
public void SetT(float newT){
currentTransparency = newT;
ApplyTransparency();
}
public void FadeT(float newT){
toFadeTo = newT;
if(currentTransparency < toFadeTo){
tempDist = toFadeTo - currentTransparency;
isFadingUp = true;
}else{
tempDist = currentTransparency - toFadeTo;
isFadingDown = true;
}
}
}