- Home /
Why isn't my script changing the sprite's transparency?
Good evening, fellow developers,
basically I have a script for changing the transparency of an object but it is not working on a new object that I have attached it to (although it was working just fine for a previous object). The code is below
#pragma strict
var sprite : Renderer;
var i : float;
var rate : float;
var trans : boolean;
function Start () {
i = 1;
sprite = gameObject.GetComponent("Renderer");
}
function Awake () {
i = 1;
sprite = gameObject.GetComponent("Renderer");
}
function Update ()
{
if (trans == false)
{
sprite.material.color = new Color(1, 1, 1, i);
i -= rate;
if (i < 0)
{
trans = true;
}
}
if (trans == true)
{
sprite.material.color = new Color(1, 1, 1, i);
i += rate;
if (i > 1)
{
trans = false;
}
}
}
This is the modified code for my second object:
#pragma strict
var blackout : boolean;
var sprite : Renderer;
var i : float;
var rate : float;
function Start ()
{
i = 0;
sprite = gameObject.GetComponent("Renderer");
}
function Update ()
{
if (blackout == true)
{
FullBlackOut();
}
}
function StartBlackout()
{
blackout = true;
}
function FullBlackOut()
{
sprite.material.color = new Color(1, 1, 1, i);
i += rate;
if (i > 1)
{
blackout = false;
}
}
Before I forget, it is worth mentioning that my first script is to make an object appear to be blinking whereas in my second script the object is a black sprite that covers most of the screen and the alpha layer is preset to zero. Therefore in the second script I am trying to raise the alpha layer so that the screen becomes dark for the player. What am I doing wrong? I've tried googling my problem and have not found a solution that works (most solutions or just rearranged versions of the code I currently have but I tried them anyways) and looking at the script it looks right. Is there a setting in the Unity Editor that I have wrong?
Answer by Eric5h5 · Oct 27, 2014 at 11:13 PM
You should use GetComponent(SpriteRenderer).color rather than the material. Also, there's no reason to have the same code in Start and Awake (get rid of one of those), don't use strings with GetComponent, and your code won't work right because it's framerate-dependent; you need to use Time.deltaTime. Since you're using Unityscript there's no point writing out the entire color when changing the alpha value; just do GetComponent(SpriteRenderer).color.a = .5 (or whatever).