Example:
var spr = GetComponent();
How to check between two case:
spr.sprite = (None);
OR
spr.sprite = (Missing);
(None) is when you just create SpriteRenderer=> sprite will be (None)
(Missing) is when you create SpriteRenderer and assign a Sprite to SpriteRenderer.sprite then you delete that sprite. It will be (Missing). Please help me!
Thank you!
You can’t really distinguish between the two cases. In both cases GetComponent will return a fake null object. So your code can only tell that there is no sprite assigned.
The state “missing” only comes from the serialized state. That means in the serialized data there is an asset reference stored (the asset GUID). However when that referenced asset doesn’t exist / doesn’t exist anymore it will show up as “missing”. This is only a visual editor feature. From the engine’s point of view the sprite is simply null / not assigned.
Usually when the asset that has such a “missing” reference is actually saved / serialized in the editor it will simply turn into a normal “None” (i.e. null).
I can’t really imagine any situation where it would be necessary to distinguish those two cases. From the scripting point of view there simply is no object assigned.
I write a Editor script that can tell Missing from None.It is tested working fine with UnityEngine.UI.Image component.
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
/// <summary>
/// 检查GameObject上的Image组件是否引用了丢失的精灵资源。
/// </summary>
public class CheckMissingReferences : ScriptableObject
{
[MenuItem("Assets/检查UI界面是否引用了已丢失的精灵资源")]
static void CheckMissing()
{
var selectedGameObjects = Selection.GetFiltered(typeof(GameObject), SelectionMode.Editable | SelectionMode.TopLevel);
if (selectedGameObjects.Length <= 0)
{
Debug.LogError("请先选择GameObject,再执行此导出指令。");
return;
}
if (selectedGameObjects.Length > 1)
{
Debug.LogError("本指令一次只能处理一个GameObject根节点。");
return;
}
GameObject rootGameObject = selectedGameObjects[0] as GameObject;
bool includeInactive = true;
Image[] allImages = rootGameObject.GetComponentsInChildren<Image>(includeInactive);
int missingCount = 0;
for (int i = 0; i < allImages.Length; i++)
{
var image = allImages*;*