I am trying to get sprite from Image in Unity but I am facing an issue. I am using this code:
void Start () {
Sprite sprite = this.gameObject.GetComponent<Image> ().sprite;
if (sprite == null) {
Debug.Log ("NULL");
} else {
Debug.Log ("NOT NULL");
}
}
If the sprite is empty, it does not recognize as "null". Why? and how to fix it?
CodePudding user response:
It works for me
I don't know your use case but I can suggest some solution
You shouldn't check references with ==
operator in Unity and you can read more about that here an here and there you can find a solution for your problem.
CodePudding user response:
It looks like the error is telling you exactly what's wrong: the m_Sprite variable of the Image script hasn't been assigned in the inspector. To fix this, you'll need to do the following:
- In the Unity editor, open the object that has the Image script attached to it.
- In the inspector, look for the Image script and expand it to view its properties.
- Find the m_Sprite property and click on the small circle to the right of it.
- In the pop-up window, select the sprite that you want to assign to the m_Sprite variable.
- Click "Apply" to save the changes and close the inspector.
After doing this, the m_Sprite variable should be properly assigned and you should be able to access it in your script without getting the UnassignedReferenceException error.
Another thing to check is that the Image script is actually attached to the correct object. If you're trying to get the sprite from an object that doesn't have the Image script attached to it, then you'll get this error. Make sure that you're calling GetComponent() on the correct object.