#58 - Unity AI Follower script

Data: 2019-04-27 12:00 - c#

Simple script for a AI character with follows a target.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

[Serializable]
public class Follower : NPCAbility {
    public Transform followTarget;
    private NavMeshAgent navMeshAgent;
    private Animator animator;
    private Vector3 previousForward;
    public override void OnStart() {
        navMeshAgent = character.GetComponent<NavMeshAgent>();
        npc.Role = "Follower";
        animator = character.GetComponentInChildren<Animator>();
        previousForward = character.transform.forward;
    }

    public override void Update() {
        if (followTarget != null && Vector3.Distance(navMeshAgent.destination, followTarget.position) > 1) {
            navMeshAgent.SetDestination(followTarget.position);
        }

        animator.SetFloat("Turn", Vector3.SignedAngle(previousForward, character.transform.forward, character.transform.up), 0.1f, Time.fixedDeltaTime);
        UpdateAnimatorMovement(navMeshAgent.velocity.sqrMagnitude > 0);
        previousForward = character.transform.forward;
    }

    void UpdateAnimatorMovement(bool isMoving) {
        float movementForward = isMoving ? 4.5f : 0.0f;
        animator.SetFloat("Forward", movementForward, 0.05f, Time.fixedDeltaTime);

        float forwardValue = animator.GetFloat("Forward");
        if (forwardValue != 0.0f && Mathf.Abs(forwardValue) < 0.05f)
            animator.SetFloat("Forward", 0.0f);
    }

    public override bool CanInteract(GameObject other) {
        return true;
    }

    public override void OnInteract(GameObject other) {
        if (followTarget == null)
            followTarget = other.transform;
        else
            followTarget = null;
    }
    public override bool CanStartAbility() {
        return followTarget != null;
    }

    public override bool CanStopAbility() {
        return followTarget == null;
    }
}

Previous snippet | Next snippet