Reputation: 6469
I am trying to develop a game using Unity, and I am in the step of developing some UI. I am going to need a player frame (to show the avatar of the active player in my turn based game), an inventory, and a settings button, with its setting screen.
The player frame thing was easy: I placed a Canvas, and an image. But, I want the inventory screen to appear when that frame is clicked. So, I created another Canvas, placed a plane inside, set a background for the inventory and a button to close it. The inventory panel is shown, but when I click the close button I receive an error. My code:
private void Awake()
{
canvas = GameObject.Find("Canvas");
inventoryPanel = GameObject.Find("InventoryPanel");
inventoryPanel.gameObject.SetActive(false);
this.raycaster = canvas.GetComponent<GraphicRaycaster>();
}
When I detect a click in UI component:
if (Input.GetMouseButtonDown(0))
{
PointerEventData pointerData = new PointerEventData(EventSystem.current);
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
pointerData.position = Input.mousePosition;
this.raycaster.Raycast(pointerData, results);
for(int i = 0; i < results.Count; i++)
{
print("Pulsada UI: "+results[i].gameObject.name);
if (results[i].gameObject.name.Equals("Playerframe"))
{
inventoryPanel.SetActive(true);
}
if(results[i].gameObject.name.Equals("Closeinventorybutton"))
{
inventoryPanel.SetActive(false);
}
}
}
Of course, the raycaster is cast from the first canvas, where the player frame is, the inventory is in ANOTHER canvas, and raycaster is null.
I tried to put the inventory screen in the first canvas, and get its reference this way:
inventoryPanel=canvas.gameObject.Find("InventoryPanel");
But seems like I cannot do that.
Do I need to create a separate canvas for any UI object in my screen, and get a separate raycaster from every canvas? The same canvas for all the UI components? if so, how can I get references to the different components?
I am having trouble finding tutorials that go further than "A button and a health bar". In other words, how to create a complex UI? A good tutorial would be fine.
Upvotes: 1
Views: 164
Reputation: 2586
You just need one canvas, you can use panels if you want to visually/hierarchically section off parts of your UI.
Edit: easiest way to get a reference to an object
public GameObject inventoryPanel;
in the inspector, you can drag and drop from the top left hierarchy into the script the inventory panel. Other options
GameObject.FindWithTag("TagName");
is a good one when you want to reference a component use
inventoryPanel.GetComponent<componentType>().variableofcomponent..
Upvotes: 3