Skip to content

Instantly share code, notes, and snippets.

@leducanhh
Last active March 26, 2017 07:26
Show Gist options
  • Save leducanhh/9a86da4b5fb365e181d98066d0e44afb to your computer and use it in GitHub Desktop.
Save leducanhh/9a86da4b5fb365e181d98066d0e44afb to your computer and use it in GitHub Desktop.
[Unity] use "Interface" for handling "Collision between game objects"
// Step 1: Create interface
// Bước 1: Tạo interface
public interface IHealth
{
void TakeDamage(int damage);
}
// Step 2: Implement in Victim
// Bước 2: nhét nó vào mồm thằng Player (Victim)
public class Player : IHealth
{
public void TakeDamage(int damage)
{
// handle when take damage
}
}
// Step 3: Implement in Attacker
// Bước 3: Khi có va chạm, check coi thằng col có được implement IHealth không. Nếu có thực thi làm TakeDamage()
public class Bullet
{
int damage = 10;
public void OnCollisionEnter(Collision2D col)
{
//check col => implement IHealth or not?
var hp = col.gameObject.GetComponent<IHealth>();
if (hp != null)
{
hp.TakeDamage(damage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment