Answer the question
In order to leave comments, you need to log in
Why are variables not cached?
I'm doing something like a state machine. Here is one of the states (the player's pursuit state):
public class EnemyPursuingState : StateBase
{
[SerializeField] private float speed = 6.0f;
private NavMeshAgent agent;
private Transform aim;
protected override void Init()
{
agent = GetComponentInParent<NavMeshAgent>();
Debug.Log(agent);
agent.speed = speed;
}
public override IEnumerator Action()
{
Debug.Log(agent);
Vector3 aimPos = CharacterControl.Instance.playerTransform.position;
float distToAim = Vector3.SqrMagnitude(aimPos - transform.position);
while (true)
{
agent.SetDestination(aimPos);
yield return new WaitForFixedUpdate();
}
}
}
public class StateHandler : MonoBehaviour
{
[SerializeField] private float detectionRadius;
[SerializeField] private float attackRadius;
[SerializeField] private StateBase idleState;
[SerializeField] private StateBase persecutionState;
[SerializeField] private StateBase attackState;
[SerializeField] private StateBase deadState;
private enum States
{
IDLE,
PERSECUTION,
ATTACK,
DEAD
}
private States currentState;
private StateBase[] states;
private Transform aim;
private void Start()
{
aim = CharacterControl.Instance.playerTransform;
states = GetComponentsInChildren<StateBase>();
currentState = States.IDLE;
StartCoroutine(idleState.Action());
}
private void Update()
{
float distanceToAim = CountMagnitude();
if (distanceToAim < detectionRadius & distanceToAim > attackRadius & currentState != States.PERSECUTION)
{
SwitchToState(persecutionState);
currentState = States.PERSECUTION;
}
else if (distanceToAim <= attackRadius & currentState != States.ATTACK)
{
SwitchToState(attackState);
currentState = States.ATTACK;
}
else if (currentState != States.IDLE)
{
currentState = States.IDLE;
SwitchToState(idleState);
}
}
private float CountMagnitude()
{
return Vector3.SqrMagnitude(aim.position - transform.position);
}
public void SwitchToState(IState nextState)
{
foreach (var state in states)
state.StopAllCoroutines();
StartCoroutine(nextState.Action());
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question