我想检测图像 Sprite 是“缺失”还是“无”
当我得到这个 Sprite 时,他们都像这样得到“null”, 那么我怎么知道它是“Missing”还是“None”呢?
PS : 我想知道它是 missing 还是 none ,这对我来说是不同的情况。
最佳答案
当尝试访问它们时,Unity 会因引用为 null
的不同原因抛出不同的异常!
这也是你应该strongly avoid someObject == null
的原因检查。 Unity 有 overwritten == null
类型 Object
的行为(基本上是大多数 Unity 内置类型的母类),即使一个对象看起来是 null
它仍然存储一些信息,比如 - 正如刚才提到的 - 为什么它是 null
的原因。
所以你可以使用一个小“技巧”并简单地尝试访问一个字段并检查你在 try - catch
block 中到底得到了哪个异常:
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!");
}
}
例子
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!");
}
}
}
关于c# - Unity 如何检测 Sprite 丢失?还是空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58055025/