- Home /
How to change material's alpha of a GameObject ?
Hi Guys ! I've created this script to change light and alpha, the light part is good and work very well but not the alpha... What is the right way ? I put in the public Material a game object with the StandardShader, thank you.
using UnityEngine;
using System.Collections;
public class Light_decrease : MonoBehaviour
{
public Light dL;
public Material cubeSkyBox;
void OnTriggerStay ( Collider other)
{
if (other.gameObject.CompareTag ("Player"))
{
dL.intensity -= 1 * Time.deltaTime;
cubeSkyBox.color.a += 1 * Time.deltaTime;
}
}
}
Answer by Trevdevs · May 14, 2017 at 03:49 PM
I'm gonna go ahead and assume you are getting this error because your trying to modify the .a aspect of a color itself. It's like trying to change the position.x individually unity hates that for whatever reason.
The proper way to change a color would be this
void OnTriggerStay ( Collider other)
{
if (other.gameObject.CompareTag ("Player"))
{
dL.intensity -= 1 * Time.deltaTime;
Color color = cubeSkyBox.color
color.a += 1f * Time.deltaTime;
cubeSkyBox.color = color;
}
}
and heres a reference that may be helpful http://answers.unity3d.com/questions/584873/renderermaterialcolora.html hope this helps :)
O$$anonymous$$ but now I've a problem wen i restart the level the material alpha stay at 255 i try to "reset" it whit this but it not work...
using UnityEngine;
using System.Collections;
public class Light_decrease : $$anonymous$$onoBehaviour
{
public Light dL;
public $$anonymous$$aterial cubeSkyBox;
private Color color;
void Awake()
{
color = cubeSkyBox.color;
cubeSkyBox.color = color;
}
void Start()
{
color.a = 0f;
}
void Update()
{
if (color.a >= 188f)
{
color.a = 188f;
}
}
void OnTriggerStay ( Collider other)
{
if (other.gameObject.CompareTag ("Player"))
{
dL.intensity -= 1 * Time.deltaTime;
color.a -= 1f * Time.deltaTime;
}
}
}
You are setting the color before you change the alpha in the Start function move that line to the start function so it looks like this and it should work.
void Start()
{
color.a = 0f;
cubeSkyBox.color = color;
}