【问题标题】:Unity get sprite from ImageUnity 从图像中获取精灵
【发布时间】:2022-12-05 18:41:05
【问题描述】:

我正在尝试从 Unity 中的图像获取精灵,但我遇到了一个问题。我正在使用这段代码:

void Start () {
     Sprite sprite = this.gameObject.GetComponent<Image> ().sprite;

     if (sprite == null) {
            Debug.Log ("NULL");
        } else {
            Debug.Log ("NOT NULL");
        }
}

如果精灵是空的,它不会识别为“空”。为什么?以及如何解决?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我使用了一个函数来绕过它。基本上这个函数检查“Source Image”是否为空,然后抛出“UnassignedReferenceException”。如果有人需要:

    public int CheckReference (Object reference) {
            int myRef = 1;
    
            try {
                var blarf = reference.name;
            } catch (MissingReferenceException) // General Object like GameObject/Sprite etc
            {
                myRef = 0;
                Debug.LogError ("The provided reference is missing!");
            } catch (MissingComponentException) // Specific for objects of type Component
            {
                myRef = 0;
                Debug.LogError ("The provided reference is missing!");
            } catch (UnassignedReferenceException) // Specific for unassigned fields
            {
                Debug.LogWarning ("The provided reference is null!");
                myRef = 0; //My image is null
            }
    
            return myRef;
        }
    

    【讨论】:

      【解决方案2】:

      这个对我有用

      我不知道你的用例,但我可以建议一些解决方案

      您不应该在 Unity 中使用 == 运算符检查引用,您可以阅读有关 herehere 的更多信息,在那里您可以找到解决问题的方法。

      【讨论】:

      • 这不是真的(不再)。 implicit operator bool 在内部使用与 == 运算符完全相同的方法。仍然正确的是,您不应该使用 ?.?? 等运算符,因为它们直接在 System.Object 级别上工作并跳过 Unity 实现
      【解决方案3】:

      如果您的组件是Image,则正确的属性是Source Image,但如果您使用的是Sprite Renderer组件,则该属性是Sprite

      这两个组件的区别很简单,Image 组件用于 UI 元素,SpriteRenderer 用于世界空间环境。

      您可以通过那里的文档阅读有关这 2 个组件的更多信息。

      【讨论】:

      • 如果 OP 使用 SpriteRenderer 那么 OP 已经抛出异常,因为 GetComponent&lt;Image&gt; 已经返回 null ...
      • 如果他缓存组件然后尝试获取 sprite 属性作为最佳实践也不会更好吗?
      • 它会,但在这种情况下,它只完成一次
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多