2017-04-16 38 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;)