using System.Collections;
public class TowerAttack : MonoBehaviour {
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
GameObject player;
PlayerHealth playerHealth;
bool playerInRange;
float timer;
void Awake()
{
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent<PlayerHealth> ();
}
void OnTriggerEnter(Collider other)
{
print (other);
if (other.gameObject == player)
playerInRange = true;
}
void OnTriggerExit(Collider other)
{
if (other.gameObject == player)
playerInRange = false;
}
// Update is called once per frame
void Update () {
timer += Time.deltaTime;
if (timer >= timeBetweenAttacks && playerInRange)
Attack ();
if (playerHealth.currentHealth <= 0)
print ("Player's dead");
}
void Attack()
{
timer = 0f;
print (playerHealth);
if (playerHealth.currentHealth > 0)
playerHealth.TakeDamage (attackDamage);
}
}
我在名为tower的对象上使用此代码,它与istrigger活动的盒式对撞机。在场上产生了多个对象&#34; PlayerHealth&#34;脚本附加并标记为&#34;播放器&#34;。但是只有第一个&#34;播放器&#34;进入箱式对撞机后,它的健康状况将被移除,而其余的&#34; Player&#34;物品保持健康。
答案 0 :(得分:0)
使用“PlayerHealth”在字段上生成多个对象 脚本附加并标记为“播放器”。然而只有第一个 进入箱式对撞机的“玩家”得到它的健康移除和 其余的“玩家”物品保持健康。
playerHealth = player.GetComponent<PlayerHealth> ();
代码行只能从一个对象获取PlayerHealth
。
要消除多个敌人的健康状况,您需要在每次调用other.GetComponent<PlayerHealth> ()
时执行OnTriggerEnter
。
void OnTriggerEnter(Collider other)
{
print(other);
//Remove health only if the Object is tagged as Player
if (other.CompareTag("Player"))
{
other.GetComponent<PlayerHealth>().TakeDamage(attackDamage);
playerInRange = true;
}
}
答案 1 :(得分:0)
player = GameObject.FindGameObjectWithTag ("Player");
这是为了设置一个玩家。如果有多个玩家,则其中一个玩家被设置为该变量。 playerHealth = player.GetComponent<PlayerHealth> ();
也只是玩家。你应该这样做。
using System.Collections;
public class TowerAttack : MonoBehaviour
{
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
GameObject[] players;
bool playerInRange;
float timer;
void Awake()
{
players = GameObject.FindGameObjectsWithTag ("Player");
// FindGameObjectWithTag => FindGameObjectsWithTag
}
void OnTriggerEnter(Collider other)
{
print (other);
if (other.tag == "Player")
playerInRange = true;
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
playerInRange = false;
}
void Update ()
{
timer += Time.deltaTime;
if (timer >= timeBetweenAttacks && playerInRange)
Attack ();
for (int i = 0; i < players.Length; i++)
{
if (players [i].GetComponent<PlayerHealth> ().currentHealth <= 0)
print ("Player's dead")
}
}
void Attack()
{
timer = 0f;
print (playerHealth);
if (playerHealth.currentHealth > 0)
playerHealth.TakeDamage (attackDamage);
}
}
如果您想同时在范围内设置TowerAttack
Attack()
所有玩家,您可以应用上述代码。但是,如果您想要一个接一个地攻击玩家,请将Update()
中的函数移动到OnTrigger*
方法。那么您可能需要这种方法OnTriggerStay。