Класс базового состояния наследуется каждым состоянием, т. е. состояние AirPatrol наследуется от «EnemyState». Однако в классе AirPatrol есть такие переменные, как «moveSpeed», «aggroDistance» и т. д. (которых нет у EnemyState), к которым я хочу получить доступ извне класса, поэтому я сделал их общедоступными. В классе конечного автомата противника (где управляется переключение состояний и т. д.) у меня есть общедоступная переменная currentState, которая сохраняет текущее состояние.
Но если я попытаюсь ссылаться на currentState.moveSpeed, я получите ошибку «не содержит определения». Я понимаю, почему это не работает, поскольку не каждый EnemyState будет иметь переменную «moveSpeed», но существует ли простой/надежный способ внесения таких изменений в переменные без необходимости добавления переменной скорости в базовый класс EnemyState?
Вот скрипты:
ОХРАННЫЙ ДРОН AI КЛАСС (ЗДЕСЬ МОЯ ПРОБЛЕМА)
Код: Выделить всё
public class SecurityDroneAI : EnemyController
{
[Header("Movement")]
public float patrolSpeed = 3.0f;
public float aggroSpeed = 5.0f;
[SerializeField] float aggroDistance = 20f;
public float acceleration = 2f;
[Header("Pathfinding")]
public float pathUpdateDelay = 1.0f;
public List patrolPositions = new List();
public float nextWaypointDistance = 2;
Animator anim;
Rigidbody2D rb;
private void Start()
{
rb = GetComponent();
anim = GetComponent();
SetNextState(new AirPatrol());
nextState.speed = 1; // HERE IS MY PROBLEM >:(
}
private void Update()
{
anim.SetBool("seeking", currentState.GetType() == typeof(AirPatrol));
float rot = -rb.velocity.x * 3;
}
}
Код: Выделить всё
public class EnemyState
{
public Rigidbody2D rb;
public Animator anim;
public Transform transform;
public EnemyController controller;
public virtual void OnEnter(EnemyController parentController)
{
controller = parentController;
rb = controller.GetComponent();
anim = controller.GetComponentInChildren();
transform = controller.transform;
}
public virtual void OnUpdate()
{
}
public virtual void OnFixedUpdate()
{
}
public virtual void OnLateUpdate()
{
}
public virtual void OnExit()
{
}
}
Код: Выделить всё
public class AirPatrol : EnemyState
{
public List patrolPositions = new List(); // List of positions to patrol between
public float speed = 3.0f; // Movement speed
public float acceleration = 2f; // Acceleration
public float pathUpdateDelay = 1.0f; // How often to update the path
public float nextWaypointDistance = 1.5f; // How far the patroller should check for the next waypoint
int positionIndex; // Index of the target position in patrolPositions
int currentWaypoint = 0; // Index of the current target waypoint on the current path
float timeSinceUpdatedPath; // Time since last generated path
Path path; // Current path
public Seeker seeker; // Seeker component for A* pathfinding
public override void OnEnter(EnemyController parentController)
{
base.OnEnter(parentController);
positionIndex = 0;
timeSinceUpdatedPath = 0;
}
public override void OnUpdate()
{
base.OnUpdate();
if (timeSinceUpdatedPath = path.vectorPath.Count) // At end of the path
{
positionIndex = positionIndex + 1 >= patrolPositions.Count ? 0 : positionIndex + 1; // Iterate to next patrol point
UpdatePath();
return;
}
MoveAlongPath();
}
private void MoveAlongPath()
{
Vector2 direction = (path.vectorPath[currentWaypoint] - transform.position).normalized;
rb.velocity = Vector3.Lerp(rb.velocity, direction * speed, acceleration * Time.deltaTime);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
}
private void UpdatePath()
{
if (!seeker.IsDone()) { return; }
seeker.StartPath(transform.position, patrolPositions[positionIndex], SetPath);
}
private void SetPath(Path p)
{
if (p.error) { return; }
path = p;
currentWaypoint = 0;
}
}
Код: Выделить всё
public class EnemyController : MonoBehaviour
{
public EnemyState mainStateType;
public EnemyState currentState;
public EnemyState nextState;
private void Update()
{
if (nextState != null)
{
SetState(nextState);
}
if (currentState != null) { currentState.OnUpdate(); }
}
private void LateUpdate()
{
if (currentState != null) { currentState.OnLateUpdate(); }
}
private void FixedUpdate()
{
if (currentState != null) { currentState.OnFixedUpdate(); }
}
private void SetState(EnemyState newState)
{
nextState = null;
if (currentState != null)
{
currentState.OnExit();
}
currentState = newState;
currentState.OnEnter(this);
}
public void SetNextState(EnemyState newState)
{
if (newState != null)
{
nextState = newState;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... ited-class