I’m new to Unity so I’m still struggling to understand how the inspector and scripts interact with each other. For instance, I have a button, and in the inspector, I set the image color to blue, and I want to fade that blue button to transparent using another script FadeScene.
My code:
public class ButtonFade : MonoBehaviour
{
private FadeScene fadescene;
private Color imagecolor;
private Image image;
private Button button;
// Start is called before the first frame update
void Start()
{
fadescene = FindObjectOfType<FadeScene>();
button = GetComponent<Button>();
image = button.GetComponent<Image>();
//imagecolor = image.color; I added this line to try and get it to set the color to itself, but it didn't change anything
}
// Update is called once per frame
void Update()
{
float alpha = fadescene.currentAlpha;
imagecolor.a = alpha;
image.color = imagecolor;
}
}
This code gives me a null reference exception at image.color = imagecolor
1. Identify what is null
The button.image.color property.
2. Identify why it is null
I don’t know, it has a value set in the inspector and when I run the game, it is blue, so it has an initialized value, but I don’t know how to access that value from a script.
3. Fix that.
I’ve also made sure that the script is attached the button object.