Skip to content

Instantly share code, notes, and snippets.

Created March 9, 2014 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/9449297 to your computer and use it in GitHub Desktop.
Save anonymous/9449297 to your computer and use it in GitHub Desktop.
Unity 以Collider+Rigdbody達成攻擊物件偵測
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AttackColliderController : MonoBehaviour {
// 宣告公開變數 touchEnemy 為 TestEnemyHP List
public List<GameObject> touchEnemyObject;
public string targetEnemyTag = "Enemy";
// 委託監聽
public delegate void AttackEventHandler(GameObject go);
public event AttackEventHandler onAttackEnemy;
// 當 標籤為 目標敵人 物件 進入 碰撞區,將之加入 touchEnemy List
void OnTriggerEnter (Collider otherEnemy) {
if (otherEnemy.tag == targetEnemyTag) {
// 判斷List中是否已有重複元素
if (!touchEnemyObject.Contains(otherEnemy.gameObject) )
{
touchEnemyObject.Add( otherEnemy.gameObject );
OnAttackEnemy( otherEnemy.gameObject );
}
}
}
// 當 標籤為 目標敵人 物件 進入 碰撞區,將之移除 touchEnemy List
/*void OnTriggerExit(Collider otherEnemy) {
if (otherEnemy.tag == targetEnemyTag) {
touchEnemyUnderAttackScript.Remove(otherEnemy.GetComponent<TestEnemyHP>());
}
}*/
// 委託監聽的 攻擊函數,傳入要攻擊的敵人物件
void OnAttackEnemy (GameObject go)
{
if (onAttackEnemy != null){
onAttackEnemy (go);
}
}
void ClearEnemyList(){
touchEnemyObject.Clear ();
}
// 當 碰撞物件停用,清除 touchEnemy List
void OnDisable(){
ClearEnemyList ();
}
}
using UnityEngine;
using System.Collections;
public class ListenAttackEvent : MonoBehaviour {
public GameObject attackColliderController;
void Awake () {
// 註冊監聽並呼叫OnAttack
attackColliderController.GetComponent<AttackColliderController>().onAttackEnemy += OnAttack;
}
void OnAttack (GameObject go) {
print (go.name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment