Hi, I’m trying to change the color of the a sprite if the player types, but it doesn’t work any ideas? And Unity displays this message :
Object reference not set to an instance of an object
SpriteChanging.Update ()
SpriteRenderer Spritecolor;
public bool gameOver;
// Start is called before the first frame update
void Start()
{
Spritecolor.color = Color.white;
}
// Update is called once per frame
void Update()
{
if (!gameOver)
{
if (BGChanging.current.coloreBianco)
{
Spritecolor.color = Color.black;
}
else if (!BGChanging.current.coloreBianco)
{
Spritecolor.color = Color.white;
}
}
}
}
This error basically means you are trying to change color of nothing. You declared Spritecolor variable, but never assigned any value to it.
So how I can fix it cause I have no idea
You need to assign valid sprite renderer to that variable in your script or via inspector.
Like this :
Spritecolor = GetComponent();
cause it still doesn’t work
this must be done before any line what accesses Spritecolor
also check if BGChanging.current is assigned
GetComponent looks at the same Gameobject the script is on and says, hey, is there a component of this type on there. If it doesn’t find it, the value is null.
So unless this script is on the sprite as well, it isn’t going to work.
It also will not work if the value of gameOver never changes. Though honestly, I think you should just change the sprite color instead of doing an update check like this. If you are already changing the value of gameOver, you could instead just change the sprite color.
Otherwise, take a look at the learn section of Unity. Your question should easily be solved once you learn how things are connected.
1 Like