Tim*_*ang 1 c# unity-game-engine
我想检测图像精灵是“缺失”还是“无”
当我得到这个精灵时,他们都得到了这样的“空”,那么我怎么知道它是“缺失”还是“无”?

PS:我想知道它是缺少还是没有,这对我来说是不同的情况。
Unity 会因为不同的原因抛出不同的异常,为什么引用是null在尝试访问它们时!
这也是您应该强烈避免someObject == null检查的原因。Unity 已经覆盖了== nullfor 类型的行为Object(基本上是大多数 Unity 内置类型的母类),即使一个对象看起来是null它,它仍然存储一些信息,比如 - 正如刚才提到的 - 它的原因null。
因此,您可以使用一个小“技巧”,然后简单地尝试访问一个字段并检查您在try - catch块中到底遇到了哪个异常:
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!");
}
}
Run Code Online (Sandbox Code Playgroud)
例子
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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1707 次 |
| 最近记录: |