I have this problem, that I draw a new Rect with a GUI: it only draws now on screen. What I want to do is to make this drawing a child of an object, so I can hide this with SetActive(false)
. This will be only available when players will pause and open Inventory. The game is 2D for Android.
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"));
}
}
}
}
To set the parent of a GameObject in Unity programmatically , simply use this: childGameObject.transform.SetParent(parentGameObject);
EDIT: Turns out it isn't this simple with OnGUI. Follow Draco18s's advice and use the new GUI system.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.