Unity不显示精灵/纹理

时间:2014-10-24 17:40:55

标签: c# unity3d sprite texture2d

我开始使用Unity,但却遇到了最基本的操作问题 - 让图像显示在屏幕上。

我已经尝试过对此进行研究,但几乎所有关于Unity的教程/信息都是关于更高级的用法,并没有涵盖基础知识。关于基本图像加载和绘图的信息非常少。

我的项目有一个对象,附带了这个脚本:

public class Boxland_Main : MonoBehaviour
{
     Texture2D test_sprite;

     void Start ()
     {
       print ("STUFF");  // this works
       test_sprite = (Texture2D) Resources.Load ("richard_green.png");
     }

     void Update ()
     {
       GUI.DrawTexture (new Rect(0, 0, 50, 50), test_sprite);  // this doesn't work
     }
}

我的图像文件位于Resources目录中,但我得到的只是粉蓝色屏幕。

编辑:

为清楚起见,我对任何只能在屏幕上显示图像的解决方案感兴趣。我觉得我已经接近回到XNA或GameMaker。

更新:

这是我现在所拥有的(仍然没有画精灵):

public class Boxland_Main : MonoBehaviour
  {
  public Texture2D test_sprite;

  void Start ()
    {
    test_sprite = (Texture2D) Resources.Load ("richard_green");
    }

  void OnGui ()
    {
    if (test_sprite) GUI.DrawTexture (new Rect (0, 0, 50, 50), test_sprite);
    }
  }

更新:

我发现,如果我将图像直接从资源窗口拖到Unity UI中的场景窗口,它会将精灵添加到视图中,精灵会在编译时显示。但是,它渲染模糊和像素化,并且似乎没有任何方法可以在精灵表上指定特定的帧。

更新:

我在研究时遇到了一些可能指向部分答案的材料:

Unity 4.3 - 2D, how to assign programmatically sprites to an object http://docs.unity3d.com/ScriptReference/Resources.Load.html

这似乎涵盖了加载图像,但绝不会解释如何绘制图像。

4 个答案:

答案 0 :(得分:1)

你应该调用GUI函数insde OnGUI,而不是更新(http://docs.unity3d.com/Manual/gui-Basics.html

因此,请尝试将Update()更改为

void OnGUI() {
    if(test_sprite) {
        GUI.DrawTexture (new Rect(0, 0, 50, 50), test_sprite);
    }
}

答案 1 :(得分:0)

您没有为资源指定.png。只是名字。

test_sprite = (Texture2D) Resources.Load("richard_green", Texture2D);

答案 2 :(得分:0)

我从来没有让Unity使用任何技术绘制任何东西(不是模糊和压缩的外观),但我只是尝试了Monogame(http://www.monogame.net/)并且在上面看到了漂亮的精灵。屏幕在五分钟之内。 Monogame的缺点是缺乏Xbox One支持,但我现在愿意接受它。

看起来我的最终结论是:

A)Unity仍然不是制作2D游戏的好方法,或者

B)它与我使用的其他引擎有如此不同的动物,我只能用脑筋缠绕它。

然而,很明显,许多开发者已经在其中制作了精彩的游戏(使用图形)。有人真的需要以"步骤1:启动项目,第2步:加载图像,步骤3:绘制图像"。

的风格编写一个好的基本介绍教程。

我可能会在将来的某个时间回到这篇文章,当时我已经准备好给Unity第三次尝试了,看看是否有任何新的想法/技术。

答案 3 :(得分:0)

您是否尝试过统一示例? https://docs.unity3d.com/530/Documentation/ScriptReference/Texture2D.LoadImage.html

using UnityEngine;

public class ExampleClass : MonoBehaviour {
    // Load a .jpg or .png file by adding .bytes extensions to the file
    // and dragging it on the imageAsset variable.
    public TextAsset imageAsset;
    public void Start() {
        // Create a texture. Texture size does not matter, since
        // LoadImage will replace with with incoming image size.
        Texture2D tex = new Texture2D(2, 2);
        tex.LoadImage(imageAsset.bytes);
        GetComponent<Renderer>().material.mainTexture = tex;
    } }