I want to detect image sprite is "Missing" or "None"


When I Get this sprite , They all got "null" like this ,
So How do I know it is "Missing" or "None" ?

PS : I want to know it is missing or none , it is different situations for me.
Unity throws different exceptions for different reasons why the reference is null when trying to access them!
This is also the reason why you should strongly avoid someObject == null checks. Unity has overwritten the behavior of == null for the type Object (basically the mother class of most Unity built-in types) and even if an object appears to be null it still stores some information like - as just mentioned - the reason why it is null.
So you could use a little "trick" and simply try to access a field and check which exception exactly you get within try - catch blocks:
public void CheckReference(Object reference)
{
try
{
var blarf = reference.name;
}
catch (MissingReferenceException) // General Object like GameObject/Sprite etc
{
Debug.LogError("The provided reference is missing!");
}
catch (MissingComponentException) // Specific for objects of type Component
{
Debug.LogError("The provided reference is missing!");
}
catch (UnassignedReferenceException) // Specific for unassigned fields
{
Debug.LogWarning("The provided reference is null!");
}
catch (NullReferenceException) // Any other null reference like for local variables
{
Debug.LogWarning("The provided reference is null!");
}
}
Example
public class Example : MonoBehaviour
{
public Renderer renderer;
public Collider collider;
private void Awake()
{
renderer = GetComponent<Renderer>();
Destroy(renderer);
}
private void Update()
{
if (!Input.GetKeyDown(KeyCode.Space)) return;
CheckReference(renderer); // MissingComponentException
CheckReference(collider); // UnassignedReferenceException
Sprite sprite = null;
CheckReference(sprite); // NullReferenceException
sprite = Sprite.Create(new Texture2D(1, 1), new Rect(0, 0, 1, 1), Vector2.zero);
DestroyImmediate(sprite);
CheckReference(sprite); // MissingReferenceException
}
public void CheckReference(Object reference)
{
try
{
var blarf = reference.name;
}
catch (MissingReferenceException) // General Object like GameObject/Sprite etc
{
Debug.LogError("The provided reference is missing!");
}
catch (MissingComponentException) // Specific for objects of type Component
{
Debug.LogError("The provided reference is missing!");
}
catch (UnassignedReferenceException) // Specific for unassigned fields
{
Debug.LogWarning("The provided reference is null!");
}
catch (NullReferenceException) // Any other null reference like for local variables
{
Debug.LogWarning("The provided reference is null!");
}
}
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With