我正在使用团结构建多人游戏。主播放器是使用网络管理器生成的预制件,包含播放器标签和。下面是搜索玩家标签的敌人攻击脚本,但在多人游戏中只返回一个玩家。我如何改变它以便Gameobject玩家是一个数组并且playerHealth可以获得组件PlayerHealth。
public class EnemyAttack : MonoBehaviour
{
public float timeBetweenAttacks = 0.5f; // The time in seconds between each attack.
public int attackDamage = 10; // The amount of health taken away per attack.
Animator anim; // Reference to the animator component.
GameObject player; // Reference to the player GameObject.
PlayerHealth playerHealth; // Reference to the player's health.
EnemyHealth enemyHealth; // Reference to this enemy's health.
bool playerInRange; // Whether player is within the trigger collider and can be attacked.
float timer; // Timer for counting up to the next attack.
void Awake ()
{
// Setting up the references.
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent<EnemyHealth>();
anim = GetComponent <Animator> ();
}
void OnTriggerEnter (Collider other)
{
// If the entering collider is the player...
if(other.gameObject == player)
{
// ... the player is in range.
playerInRange = true;
}
}
void OnTriggerExit (Collider other)
{
// If the exiting collider is the player...
if(other.gameObject == player)
{
// ... the player is no longer in range.
playerInRange = false;
}
}
void Update ()
{
// Add the time since Update was last called to the timer.
timer += Time.deltaTime;
// If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
{
// ... attack.
Attack ();
}
// If the player has zero or less health...
if(playerHealth.currentHealth <= 0)
{
// ... tell the animator the player is dead.
anim.SetTrigger ("PlayerDead");
}
}
void Attack ()
{
// Reset the timer.
timer = 0f;
// If the player has health to lose...
if(playerHealth.currentHealth > 0)
{
// ... damage the player.
playerHealth.TakeDamage (attackDamage);
}
}
}
答案 0 :(得分:0)
您应该将FindGameObjectsWithTag与invoke repeating一起使用。下面给出了一个未经测试的代码段:
public GameObject [] playersList;
void Start() {
//Invokes the method methodName in time seconds,
//then repeatedly every repeatRate seconds.
InvokeRepeating("CheckPlayers", 2.0f, 0.3f);
}
public void CheckPlayers(){
//assign player in the player list
playersList= GameObject.FindGameObjectsWithTag ("Player");
//now playersList contains all player, do what you want with it
}