Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

A Unity C# Script to set the transparency of an object

Posted on February 4, 2021February 4, 2021 by Habibie

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;
		}
	}
	
	
}
Post Views: 521
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Hover Reveal script for Unity to show and hide object on mouse hover
  • How to Prevent UI Clicks in Unity from “Bleeding Through” to 3D Objects Behind Them
  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
© 2026 ThirteeNov | Powered by Superbs Personal Blog theme