【问题标题】:How to place a texture in a specific location (Unity)如何将纹理放置在特定位置(Unity)
【发布时间】:2014-06-04 19:30:33
【问题描述】:

我目前正在使用 Unity 游戏引擎开发游戏,现在我正在尝试做一个简单的 UI:在屏幕左上角放置一个纹理(心脏)以及代表生命数量的文本玩家拥有的。文本部分很简单,但我在纹理上苦苦挣扎,现在尝试了几种方法,但似乎无法让它发挥作用。我使用的代码如下:

using UnityEngine;

using System.Collections;

public class Health : MonoBehaviour {

    private int currentHealth;
    private int startHealth;
    private int maxHealth;
    private Vector2 topLeftCorner;

    public Texture2D heart;

    // Use this for initialization
    void Start () {
        startHealth = 3;
        maxHealth = 100;
        topLeftCorner = new Vector2 (0, 0);
        heart = new Texture2D (128,128);
        PlaceHeart (topLeftCorner, heart);
    }

    void PlaceHeart (Vector2 place, Texture2D img)
    {
        float x = place.x * Screen.width;
        float y = place.y * Screen.height;
        GUI.Label(new Rect (x, y, img.width, img.height), img);
    }

    public void modifyHealth(int amount) {
        currentHealth += amount;
        // Prevent health from being < 0 or > maxHealth
        currentHealth = Mathf.Clamp(currentHealth,0,maxHealth);

    }
}

我在 Unity 检查器中分配了与纹理(心脏)相对应的变量,但是我仍然收到一个(基本)错误:“NullReferenceException: Object reference not set to an instance of an object”我有很难理解。 任何帮助将不胜感激。

【问题讨论】:

    标签: unity3d textures placement


    【解决方案1】:

    这可能就像删除线一样简单

    heart = new Texture2D (128,128);
    

    来自您的代码。您在 Inspector 中设置的任何内容都不需要在脚本中创建。

    【讨论】:

    • 已经试过了,但是没用,不是这里的问题。
    • 问题是这一行实际上创建了一个 Empty Texture2D 并替换了您在编辑器中设置的那个。您能否指定发生错误的行?此外,您可能想使用我在文档中阅读的 GUITexture 而不是 Texture2D。
    【解决方案2】:

    您现在拥有的代码将无法工作,因为您试图在only work inside OnGui() 以外的地方使用GUI 方法@ 而不是OnGui()

    也就是说,你应该停止使用GUI方法并使用由精灵尘埃和梦想组成的the New Unity 4.6 UI

    基本上,您会转到 GameObject 菜单、UI、Image。画布将为您设置好,屏幕空间完美,只需缩小并进入 2D 视图,激活 RectTransform 工具(它是比例旁边的那个正方形)以定位白色框,然后在检查器中分配一个精灵(所以它看起来像一颗心,而不是白色)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2018-02-17
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多