The magic of making Game Objects appear and disappear.
I love magic shows. Penn and Teller, Criss Angel, and the Masked Magician have always fascinated me (I’ll admit to even practicing an illusion or two). But making games is a different type of magic, but one thing they do have in common is the appearance and disappearance of objects. Fortunately, making Game Objects in Unity appear and disappear are much easier to achieve.
Now before I go any further I’m not talking about having an Object in your scene and making it active or not (ie gameObject.SetActive(true)) but buy Instancating and Destroying.
Let’s start with Instantiation. in the snippet above I take the _myObject and use the Instantiate method to spawn in that object. Now, this has to have a Game Object attached to it in the Unity Editor.
This is done by using a Game Object Prefab. A Prefab is a Game Object that you create and then drag from the Scene into the assets folder. When you do this the game object in the Hierarchy will turn blue and will also appear as a blue asset in your Assets folder as well. Once you have your Game Object Prefabified (and yes, you have to say that in your best impression of Mater from Cars).
Now that we have our prefab we select the object that is asking for a Game Object and add it to the field. That is when you can call the spawning code in the snippet above. Somethings to point out are the other arguments in Vector3.zero and the Quaternion.identy. The second argument sets the object position in world space (in this case (0, 0, 0)) and the Quaternion.identy corresponds to “no rotation”.
Now that is the Appearance, but what about the disappearance you ask? Well, that can be done by a Simple Destroy(gameObject). Take the class to the left. this attached to our prefab as a component and when the y position is greater than 10 the Game Object destroys itself.
And Hey Presto with two commands (Insatiate and Destroy) you too can make Game objects Appear and Disappear and it’s faster to learn than palming a coin.