团结.帮助为敌人创建了一个小脚本,其中所有挂着它的物体的hp都会减少



我正在制作一个团结射击游戏。任务是以自己的方式从每个敌人身上移除hp。我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class monster_animation : MonoBehaviour
{
public GameObject player;
public float dist;
NavMeshAgent nav;
public float Radius = 40f;
public static int health = 100;
// Start is called before the first frame update
void Start()
{
nav = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
if (GameObject.Find("HitEffect(Clone)") != null)
{
health -= 25;
Destroy(GameObject.Find("HitEffect(Clone)"));
}
dist = Vector3.Distance(player.transform.position, transform.position);
if(dist <= Radius)
{
if (dist <= 4)
{
nav.enabled = false;
if (health <= 0)
{
nav.enabled = false;
gameObject.GetComponent<Animator>().SetTrigger("dead");
}
else
{
gameObject.GetComponent<Animator>().SetTrigger("attack");
}
}
else
{
if (health <= 0)
{
nav.enabled = false;
gameObject.GetComponent<Animator>().SetTrigger("dead");
}
else
{
nav.enabled = true;
nav.SetDestination(player.transform.position);
gameObject.GetComponent<Animator>().SetTrigger("run");
}
}
}
if(dist > Radius)
{
nav.enabled = false;
gameObject.GetComponent<Animator>().SetTrigger("idle");

}
}
}

把这个脚本挂在不同的敌人身上,命中hp后应该从特定的敌人那里获取,而不是全部。我试着将健康转换为静态,但无济于事。我做了一个私有变量,它也没有帮助。我在网上搜索了这个答案。

由于这不是完整的代码,我假设了一些事情。如果我错了,请纠正我。当子弹击中敌人时,你似乎会创建一个HitEffect(克隆(,对吧?使用这种方法,敌人永远不知道创建的HitEffect是在它旁边还是在另一个玩家旁边。用物理学做这件事会更容易。请检查OnCollisionEnter函数。这个函数可以设置为敌人或子弹,(出于基于类的编程原因,我会对子弹进行设置(并检查另一部分是否是敌人。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet_collision : MonoBehaviour
{
public int damage = 25;
void OnCollisionEnter(Collision collision)
{
monster_animation m = collision.GetComponent<monster_animation>();
if (m != null)
{
m.health -= damage;
}
}
}

最新更新