【问题标题】:Loading Texture in Unity always throws NullReferenceExpection在 Unity 中加载纹理总是抛出 NullReferenceExpection
【发布时间】:2015-06-28 03:12:05
【问题描述】:

我正在使用 Unity 4.3.3f1 并尝试在运行时加载纹理,但我不断收到 NullReferenceExpection。我的.png 位于this question 指定的资产/资源中。

我的实际代码是

  Texture tex = Resources.Load("lava_pic", typeof(Texture)) as Texture;
  Rect pos = new Rect(transform.position.x - 50, 
        transform.position.y - 50, 100, 100);

  GUI.DrawTexture(pos, tex);

我也尝试过.png 扩展

错误是

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUI.DrawTexture (Rect position, UnityEngine.Texture image, ScaleMode  
  scaleMode, Boolean alphaBlend, Single imageAspect) (at     
C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:208)
UnityEngine.GUI.DrawTexture (Rect position, UnityEngine.Texture image) (at 
 C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:204)
LavaScript.FixedUpdate () (at Assets/Scripts/LavaScript.cs:35)'

如果我输入Debug.Log(tex);,它也会打印出null,这就是问题所在。

我真的不知道为什么会这样。它在资源文件夹中,因为that's where it needs to be 并且我相当肯定它可以是.png 文件。我做错了什么?

【问题讨论】:

    标签: c# null unity3d textures nullreferenceexception


    【解决方案1】:

    尝试删除文件扩展名,使其变成lava_pic。

    来自Resourcesdocs的相关信息:

    ...扩展名必须省略

    更新

    我机器上的工作示例。如果您的原始代码位于OnGUI 之外,则可能空对象是 GUI 而不是纹理。

    我的纹理位于Assets/Resources/galaxy_example.png

    public class DrawTexture : MonoBehaviour {
    Texture tex;
    Rect pos;
    void Start () {
        tex = Resources.Load("galaxy_example", typeof(Texture)) as Texture;
        pos = new Rect(transform.position.x - 50, 
                       transform.position.y - 50, 100, 100);
    }
    void OnGUI(){
        Debug.Log (tex);
        GUI.DrawTexture(pos, tex);
    }
    }
    

    【讨论】:

    • 试过了,结果一样:/
    • @Daniel 您从哪里调用此代码?如果你在OnGUI之外测试你的代码,请查看我的更新
    • 预制件的行为脚本,FixedUpdate()。该脚本继承自 Monobehavior
    • 啊,好的,我试试
    【解决方案2】:

    如果您尝试在 Asset/Resource 文件夹中加载图像,请使用:Resoure.Load("image",typeof(texture)) 作为纹理。

    如果要从其他文件夹加载图像,请加载完整路径: Texture2D Txt= Resources.LoadAssetAtPath<Texture2D> ("Assets/Sprites/Scene1.png");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2011-07-21
      • 2013-06-28
      • 1970-01-01
      相关资源
      最近更新 更多