【问题标题】:How to make GUI Rect child of an object?如何使对象的 GUI Rect 子对象?
【发布时间】:2017-09-17 22:39:44
【问题描述】:

我有这个问题,我用 GUI 绘制了一个新的 Rect:它现在只在屏幕上绘制。我想做的是让这个绘图成为一个对象的子对象,所以我可以用SetActive(false) 隐藏它。这仅在玩家暂停并打开库存时可用。该游戏是 Android 的 2D 游戏。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    public int SlotsX, SlotsY;

    public GUISkin Skin;

    public List<Item> inventory = new List<Item>();
    public List<Item> slots = new List<Item>();

    private ItemDatabase database;

    void Start()
    {
        for (int i = 0; i < (SlotsX * SlotsY); i++)
        {
            slots.Add(new Item());
        }

        database = GameObject.FindGameObjectWithTag("Item Database").GetComponent<ItemDatabase>();
        inventory.Add(database.Items[0]);
        inventory.Add(database.Items[1]);
        inventory.Add(database.Items[3]);
        inventory.Add(database.Items[4]);
        inventory.Add(database.Items[5]);
        inventory.Add(database.Items[6]);
    }

    void OnGUI()
    {
        GUI.skin = Skin;
        DrawInventory();
        for (int i = 0; i < inventory.Count; i++)
        {
            GUI.Label(new Rect(10, i * 40, 200, 50), inventory[i].itemName);
        }
    }

    void DrawInventory()
    {
        for (int x = 0; x < SlotsX; x++)
        {
            for (int y = 0; y < SlotsY; y++)
            {
                GUI.Box(new Rect(x * 180, y * 180, 160, 160), "", Skin.GetStyle("Slot"));
            }
        }
    }
}

【问题讨论】:

标签: c# user-interface unity3d rect unity2d


【解决方案1】:

要在 Unity 中以编程方式设置 GameObject 的父级,只需使用以下命令: childGameObject.transform.SetParent(parentGameObject);

编辑: 事实证明,使用 OnGUI 并没有这么简单。听从 Draco18s 的建议,使用新的 GUI 系统。

【讨论】:

  • 这...很遗憾不适用于使用 OnGui 创建的 GUI 元素。
猜你喜欢
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 2022-08-21
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多