多个敌人不跟随玩家 - Unity C#

时间:2021-04-22 08:53:04

标签: c# unity3d

我做了一个敌人跟随玩家的角色扮演游戏。当我复制敌人时,只有一个跟随他。

所有敌人都做奔跑的动作(他们移动他的手臂和腿),但不要移动他的目的地(只有一个跟随玩家)。

我认为问题出在 navMeshAgent 上,所有敌人只共享一个。

public float lookRadius = 10f;

Transform target;
static NavMeshAgent agent;
CharacterCombat combat;

public float timeLlegadaE = 10f;

public float velocidadAtaque;
private float attackCooldown = 0f;

bool ataque = false;

void Start()
{
    target = PlayerManager.instance.player.transform;
    agent = GetComponent<NavMeshAgent>();
    combat = GetComponent<CharacterCombat>();
    attackCooldown = velocidadAtaque;

}

// Update is called once per frame
void Update()
{
    attackCooldown -= Time.deltaTime;
    if (timeLlegadaE < 0)
    {
        ataqueFalse();

        float distance = Vector3.Distance(target.position, transform.position);

        if (distance <= lookRadius)
        {
            if(agent != null)
            {
                agent.SetDestination(target.position);

                avanzarTrue();

                if (distance <= (agent.stoppingDistance) && attackCooldown <= 0)
                {

                    ataqueTrue();

                    //anim.SetBool("Atack", false);
                    //Debug.Log("Interacting with " + transform.name);

                    FaceTarget();

                    attackCooldown = velocidadAtaque;
                }
                else if (distance <= (agent.stoppingDistance) && attackCooldown > 0)
                {
                    avanzarFalse();
                }
            }

        }

        lookRadius = 150f;
        gameObject.GetComponent<NavMeshAgent>().enabled = true;

    }
    else
    {
        timeLlegadaE -= Time.deltaTime;
    }
}

Image

1 个答案:

答案 0 :(得分:2)

你的

static NavMeshAgent agent;

static => 基本上在此脚本的所有实例之间“共享”,因此在

agent = GetComponent<NavMeshAgent>();

您为所有实例覆盖此值。

为什么是 static?简单制作

[SerializeField] private NavMeshAgent agent;

private void Start()
{
    if(!agent) agent = GetComponent<NavMeshAgent>();
    ...
}

如果可能的话,已经通过检查员分配了它。