So I was making a really simple script which takes two alpha values and “blends” them since I sometimes need objects/entities to be invisible but still want to control the default alpha value.
This is the script:
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class DoubleAlphaSetter : MonoBehaviour
{
public SpriteRenderer sr;
public float mainAlpha;
public float invisibleAlpha;
public Color color
{
get => sr.color;
set
{
Color col = value;
mainAlpha = col.a;
sr.color = new Color(col.r, col.g, col.b, mainAlpha * invisibleAlpha);
}
}
void Start()
{
Debug.Log("Start");
sr = GetComponent<SpriteRenderer>();
mainAlpha = sr.color.a;
invisibleAlpha = 1;
}
public void SetInvisibleAlpha(float alpha)
{
invisibleAlpha = alpha;
Color col = color;
sr.color = new Color(col.r, col.g, col.b, mainAlpha * invisibleAlpha);
}
}
I made the variables public so that I can look at them in the inspector (Edit: I do not assign any variables in the inspector and as soon as this works, they will be made private again). When I run this script, I get a NullReferenceException that sr is not assigned (color gets called from another script, and with the line which creates the error is sr.color = new Color(col.r, col.g, col.b, mainAlpha * invisibleAlpha);
), even though start got called (and sr got set):
If I look at the inspector, the sprite renderer is actually assigned:
Setting the SpriteRenderer in the inspector after getting the error doesn’t stop it.
Before using two floats, I had a float array which had the same problem: It got initialized in Start() (and was visible in the inspector when setting it to public) but somehow returned null when using it.
When using Debug.Log to log the variables, it seems that the three variables get stored twice, once in the inspector/the start function and once in the other cases.
Is this a bug or am I doing something wrong? I tried creating a new script and copy-pasting the code there, restarting Unity or my computer, but none of it seems to work.