Game Development Reference
In-Depth Information
It's important to understand when you should tightly couple objects and when you
shouldn't using the appropriate pattern as required.
Basically, if a parent needs to manage its children, then you should tightly couple them so
they can communicate effectively. If the two objects have no direct relationship, then
either of them uses static functions, central state classes, or messaging to route informa-
tion between them.
Next, we'll add the Init function that we called earlier to the CreateButton function:
public void Init(CommandBar commandBar)
{
this.commandBar = commandBar;
gameObject.layer = commandBar.Layer;
var collider = gameObject.GetComponent<BoxCollider2D>();
collider.size = new Vector2(1f, 1f);
var renderer = gameObject.GetComponent<SpriteRenderer>();
renderer.sprite = commandBar.DefaultButtonImage;
renderer.sortingLayerName = "GUI";
renderer.sortingOrder = 5;
}
When initializing the button's contents, we are setting up all the components this object
has assigned to it; they are as follows:
• We define a tight reference for the CommandBar class itself because each button
is managed by the CommandBar class.
• We set the layer of the new button to be the same as the command bar.
• We get the BoxCollider2D game object and set its size appropriately. (The de-
fault is actually the same as we are setting it, but it is worth being prudent and en-
suring it is the size we want; don't assume!)
• We get SpriteRenderer , give it the default button image, and set its sorting
parameters as required; if this is not the case, you won't see it because it will be
drawn behind everything else.
Search WWH ::




Custom Search