2017-04-16 39 views
0

我有一個玩家對象和一個敵方物體,兩邊都有碰撞體,還有那裏的武器,但是這會讓他們在走進對方時造成傷害。我想要的是,如果「isAttacking」動畫正在運行,他們只會造成傷害。我的代碼連接到播放機和敵人的目的,是下面:Unity 5檢查動畫

using System.Collections; 
using UnityEngine; 
using UnityEngine.UI; 

public class detectHit : MonoBehaviour 
{ 

public Slider healthbar; 
Animator anim; 
public string opponent; 
public Collider ecollider; 

// Use this for initialization 
void Start() 
{ 
    anim = GetComponent<Animator>(); 
} 

void OnTriggerEnter(Collider other) 
{ 
    if (other.gameObject.tag != opponent) return; 

     healthbar.value -= 20; 

    if (healthbar.value <= 0) 
    { 
     anim.SetBool("isDead", true); 
     ecollider.gameObject.SetActive(false); 
    } 

} 

// Update is called once per frame 
void Update() 
{ 

} 
} 

我試過網上找,但大部分的東西是過時我覺得我需要做這樣的事情:

if(anim.GetCurrentAnimatorStateInfo(0).IsName("isAttacking")){ 
healthbar.value -= 20; 
} 

但這不起作用,也許因爲我沒有看它看對手動畫?如果是這樣的話,我只是不知道如何尋找敵人的動畫。

任何幫助將不勝感激。

回答

0

爲孩子中的角色添加攻擊對象和碰撞器。默認情況下關閉此碰撞器的活動狀態。 如果角色開始攻擊動畫,請在第一幀打開此碰撞器。並在最後一幀關閉。 你可以捕捉到攻擊動作。

0

所以首先,如果你想檢查其他腳本中的某些東西,你需要引用它。您可以在存儲公共屬性的槽中拖動enmemy GameObject/Prefab。您只需要擁有GameObject類型的公共字段,或者您甚至可以將類型設置爲Script。

public GameObject myEnemyReference; 

當你沒有在現場的hirarchy你的敵人,當你開始和通過腳本還必須存儲參考實例它創建了敵人。

GameObject toInstantiate = myEnemyPrefab; 
GameObject myEnemyReference = Instantiate (toInstantiate, new Vector3 (0f, 0f, 0f), Quaternion.identity) as GameObject; 

當你有你的參考,你可以叫你得到像這樣的腳本的公共職能:我只是認爲劇本有一個名爲checkForHitable公共函數

detectHit enemyScript = (detectHit) myEnemyReference.GetComponent (typeof(detectHit)); 
bool isAttackState = enemyScript.checkForHitable(); 

這裏,當對手被允許造成傷害時,這返回真實。

我不明白你希望你的戰鬥系統如何工作,但是由於你的代碼工作不正常,你可能想檢查玩家和敵人的動畫狀態,下面是你的建議可以檢查敵人的狀態,甚至可以進一步調用敵人腳本的功能,這可能會在稍後有所幫助。

PS:類名通常以大寫字母開頭:DetectHit;)