Last active
March 26, 2017 07:26
-
-
Save leducanhh/9a86da4b5fb365e181d98066d0e44afb to your computer and use it in GitHub Desktop.
[Unity] use "Interface" for handling "Collision between game objects"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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