Game Development Reference
In-Depth Information
public class TakeDamageFromPlayerBullet : MonoBehaviour
{
public delegate void hitByPlayerBullet();
public event hitByPlayerBullethitByBullet;
void OnTriggerEnter2D( Collider2D collidedObject )
{
if(collidedObject.tag == "Player Bullet")
{
if(hitByBullet != null)
hitByBullet();
}
}
}
Attach the script to the
Defense Collider
object inside the
Enemy
parent object. Now
we can accept weapon shots from the player and call the
hitByBullet
event when it
occurs. Let's modify the
EnemyControllerScript
to listen to these events.
First, at the beginning of
EnemyControllerScript
, add an object reference to
TakeDamageFromPlayerBullet
using the following line of code:
public TakeDamageFromPlayerBullet bulletColliderListener = null;
Make sure that you assign the
Defense Collider
object to this field in the
Inspector
panel. Next, add the following functions above the
Start
function in
EnemyControllerScript
:
void OnEnable()
{
// Subscribe to events from the bullet collider
bulletColliderListener.hitByBullet += hitByPlayerBullet;
}
void OnDisable()
{
// Unsubscribe from events
bulletColliderListener.hitByBullet -= hitByPlayerBullet;
}
Finally, add a function called
Destroy
to manage what happens when the enemy is
hit by a bullet, as shown in the following code snippet. This code could technically
go anywhere, but let's place it at the bottom of the
EnemyControllerScript
.
public void hitByPlayerBullet()