Home > Blockchain >  Is there a way to optimise this method for an Enemy AI Controller in unity?
Is there a way to optimise this method for an Enemy AI Controller in unity?

Time:04-17

private void Update()
{
    //Check for sight and attack range
    playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);


    if (!playerInSightRange)
    {
        Patroling();
        Debug.Log("Patroling");
    }
    if (playerInSightRange)
    {
        ChasePlayer();
        Debug.Log("Chasing");
    }
}
    
private void Patroling()
{
    if (!walkPointSet)
    {
        SearchWalkPoint();
    }

    if (walkPointSet)
    {
        agent.SetDestination(walkPoint);
    }

    Vector3 distanceToWalkPoint = transform.position - walkPoint;

    //Walkpoint reached
    if (distanceToWalkPoint.magnitude < 1f)
        walkPointSet = false;
}

private void SearchWalkPoint()
{
    //Calculate random point in range
    float randomZ = Random.Range(-walkPointRange, walkPointRange);
    float randomX = Random.Range(-walkPointRange, walkPointRange);

    walkPoint = new Vector3(transform.position.x   randomX, transform.position.y, transform.position.z   randomZ);

    if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
        walkPointSet = true;
}

private void ChasePlayer()
{
    agent.SetDestination(player.position);
}

The first method above checks whether or not a player is within a given sight range and then executes two other methods based on sight range. this script by far uses up the most resources out of any other script and I'm not entirely sure how (Or even if there is a way) to make it use less CPU, if someone can find a way to optimize the scripts it would be appreciated.

CodePudding user response:

Currently while patrolling this line will be executed every frame:

agent.SetDestination(walkPoint);

I’m guessing it only needs to be called when the destination (walkPoint) changes. If so you should be able to move it to the bottom of SearchWalkPoint().

From the question there’s no way to know which parts of the script are slowest but it’s plausible this could be one of them: playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);.

Currently it seems to be just checking for the player in a sphere around the enemy — if so, assuming there is only one player object, it may accomplish the same thing more simply to just check the distance between the player and the enemy position using Vector3.Distance().

Another possibility would be not to check the sight range for every enemy every frame, but instead spread the checks out over multiple frames, with each enemy only checking every few frames. Depending on the game, enemies not always reacting instantly may actually be more realistic.

  • Related