Game Development Reference
In-Depth Information
Note
In an odd peculiarity (that can leave you scratching your head for hours), if you try setting
up the preceding code in line with where you are using it (in the
CommandBar
script) in-
stead of within the class script (as in the preceding code), it will not actually work. It will
create the new game object, but anything else just gets forgotten when used. Try it for
yourself if you wish.
So now we can manage what the
InventoryItem
button is managing; we'll add anoth-
er function to do this in a controlled way. This is because there is a fair amount of setup
required in order for us to display the item on top of the button:
public void AddInventoryItem(InventoryItem item)
{
this.Item = item;
var childGO = new GameObject("InventoryItemDisplayImage");
var renderer = childGO.AddComponent<SpriteRenderer>();
renderer.sprite = item.Sprite;
renderer.sortingLayerName = "GUI";
renderer.sortingOrder = 10;
renderer.transform.parent = this.transform;
renderer.transform.localScale *= 4;
}
So when the
CommandBar
class requests to put
InventoryItem
in a button, it creates
a new empty game object and adds a sprite renderer to it with the relevant settings for it to
display. We also keep a reference for the item being displayed so that we can reuse its
properties later (like how much damage our sword would bring about).
Adding the command bar to the scene
Open up the
Battle
scene if you haven't done so already so that we can add the new com-
mand bar to the
Battle
scene. The command bar we have built is part of the battle control-
ler, so we will add the new script to the
BattleManager
game object as a second
script.
So, select the
BattleManager
game object and either drag the
CommandBar
script to
it, or click on
Add Component
and navigate to
Scripts
|
Command Bar
; the inspector
should now look as follows: