Quick note: I’ve been doing a terrible job updating this page, but have been consistently updating the Facebook Page. It’s a lot of work to maintain and update the games, social media and websites. Not complaining, just saying how things are. I do my best to maintain everything possible.

The below code looks deceptively simple but is the result of too many hours of refining. The end result is clean code that is simple, elegant and gets the job done. Granted I could have also put in an “if null” after instantiate. But if that fails, there are bigger issues and I’d prefer an exception error.

Code Snippet

This code started out as a switch statement to pick the “Pet prefab” for the level of the pet that follows the player. The switch took up 4 lines per Pet Level and was just too many hardcoded items. Also as I work on the game and tweaked things, the structure changed. Originally this was built from an array of each individual pet level object. Imagine dragging in 8*3 objects into each main player character… UGH no. It was brutal.

Shown below, the pet gameObject contains an empty parent transform, then 3 tiers of different pet looks.

May be an image of text that says '1-Bunkins 1-Bunkins level1 level2 level3'
Pet object structure.

Originally I used “transform.Find(“level” + petLevel). But this threw nasty exceptions my way because I had not instantiated the main object to get the child object. Now I first instantiate the main pet object, then run a “for loop” on the transform.childcount. It’s mostly future proofing just in case 10 more pet levels are added…

The flip is just a Boolean test “is this child object the level we want?”. All others of flipped off except the match. While I try to avoid for loops in most of my programming, this most likely has a 0.1ms performance hit.

An alternative to the above for loop is to directly access and flip the gameobject on as needed (shown below). The two main issues with this is accidentally leaving one of the gameObjects on in the Prefab. The other doesn’t turn the prefabs off if say the pet is upgraded. The second issue is not really a problem since pets are upgraded in their own screen back at the home interface.

The one line alternative that wouldn’t work in reality.

One of the beauties of Unity3D is the ability to access child gameObjects directly via an array style index. If I’m working with prefabs I can just access what I am looking for down the chain. I have something exactly like this that traverses 7 layers or so down. Thanks to prefabs, the structure never changes.