Game Development Reference
In-Depth Information
Now, at the bottom part of the launchBullet method, let's give the timer a value
with the following code:
selfDestructTimer = Time.time + 1.0f;
Finally, add an Update method to PlayerBulletController and populate it with
the following code:
void Update()
{
if(selfDestructTimer> 0.0f)
{
if(selfDestructTimer<Time.time)
Destroy(gameObject);
}
}
Now when you play the game and fire bullets, they will automatically destroy
themselves after 1 second.
Next, let's set up some code so that bullets will also destroy themselves whenever
they collide with something. Create a new script called DestroyOnCollision ,
attach it to the Player Bullet Prefab, and make it look like the following code snippet:
using UnityEngine;
using System.Collections;
public class DestroyOnCollision : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D hitObj)
{
DestroyObject(gameObject);
}
}
Fire the bullets now into some platforms and watch them auto-destroy.
Summary
We now have an understanding of how to create a player object with which they
can interact. They can run, they can jump, and they can even collide with platforms.
You know what would be really cool to have next? Some baddies. With that in mind,
here's what we're going to do next in Unity 2D!
In the next chapter, we're going to create enemies, move them, attack them (ooo,
scary!), and so on. We're also going to learn about particle systems for a 2D world.
 
Search WWH ::




Custom Search