【问题标题】:Why does Resources.Load <Sprite> return null?为什么 Resources.Load <Sprite> 返回 null?
【发布时间】:2014-07-27 04:45:34
【问题描述】:

我的项目在 Assets\Sprites 中有多个精灵,我想使用 C# 脚本加载它们。

我已经测试过了:

Sprite myFruit = Resources.Load <Sprite> ("Graphics_3");

myFruit 仍然为空。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    Resources.Load 将在Assets/Resources 中搜索目录。

    如果你想把它放到Sprites 目录然后把它放到Resources 里面(例如Assets/Resources/Sprites)。

    然后你可以像这样加载它:

    Sprite myFruit = Resources.Load <Sprite> ("Sprites/Graphics_3");
    

    还要确保您已在检查器中将图像类型设置为 Sprite。

    如果你想加载多个精灵,使用这个:

    Sprite[] myFruit = Resources.LoadAll <Sprite> ("Sprites/Graphics_3");  
    

    更多详情请见this

    【讨论】:

    • 如果我加载一个精灵,它就可以了!但是我用多个精灵进行了测试,它并没有很好地工作,并且场景被暂停了!!
    • 我已经编辑了我的答案,也许这就是你想要的
    • 请记住,Resources.Load() 不仅会在 Assets/Resources 中搜索,还会在任何其他目录下名为 Resources 的任何目录中搜索,例如Assets/Sprites/ResourcesAssets/Foobar/Plugin/Resources
    • 谢谢。搜索了很多,但这个答案就像一个魅力。
    • ..这个答案在 2019 年拯救了其他人 :) 非常感谢老兄
    【解决方案2】:

    awesome.png 放入Assets/Resources/(可以有子文件夹),然后使用:

    GetComponent<SpriteRenderer>().sprite = 
        Resources.Load<Sprite>("awesome");  // No file extension.
    

    http://docs.unity3d.com/ScriptReference/Resources.html

    还有LoadAll “将所有资源加载到文件夹或资源文件夹路径中的文件中。”

    【讨论】:

      【解决方案3】:

      我知道这是一篇旧帖子,但是如果仅通过加载资源仍然无法正常工作,那么我们还必须添加纹理。我就是这样做的。

      Texture2D texture = Resources.Load<Texture2D>("Sprites/imageName");
      Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
      btnImage.image.sprite = sprite;
      

      【讨论】:

        【解决方案4】:

        您需要输入资产的完整路径。在这种情况下,请尝试使用路径“Sprites/Graphics_3”。

        【讨论】:

          【解决方案5】:
              Sprite sp = Resources.LoadAll<Sprite> ("Sprites/AI-Avtar") [2] as Sprite;
          

          【讨论】:

          • 因为 Sprite 在这里是多余的,因为您已经按类型加载:(LoadAll)
          【解决方案6】:

          Resources.Load 正在“资产/资源”目录中搜索 这就是为什么你需要这样做

          _sprites = Resources.LoadAll<Sprite>(spritesPath);
          

          _sprites = Resources.Load<Sprite>(spritesPath);
          

          以 spritesPath 作为相对路径。 如果您需要从文件夹“Assets/Resources/Sprites”中加载所有内容,则只需编写“Sprites”即可。

          在此之后,您可以执行以下操作:

          var sprite = sprites[0];
          

          var sprite = _sprites.Where(a => a.name == "Sprite_Name_Needed").First();
          

          【讨论】:

            【解决方案7】:

            Unity 的脚本参考并没有说你需要在Load 之后写&lt;Sprite&gt;。所以我在加载精灵时遇到了问题,尽管我的精灵在资源目录中。

            【讨论】:

              【解决方案8】:

              我刚刚使用 Resources.Load 加载我的精灵,发现结果是 Texture2D。所以我使用 Sprite.Create 创建一个带有 Textur2D 的新精灵来解决这个问题。

              【讨论】:

              • 您可以在导入设置中将图像类型更改为Sprite,您不需要每次都创建一个新的
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-12-26
              • 1970-01-01
              • 2016-12-28
              • 2015-11-25
              相关资源
              最近更新 更多