Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug Finite state machine not working as planned

Discussion in 'Scripting' started by macacuu, Sep 18, 2023.

  1. macacuu

    macacuu

    Joined:
    Sep 18, 2023
    Posts:
    1
    Hi everyone, I have a tiny training project I' ve done some time ago where I tried to simulate a couple of states just to get to know how a FSM works. The only problem is that some states don't work as they should. For example when generating some children instead of creating one instance of the prefab, sometimes it creates like a bunch at once. even though it should only create one.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class MakeLove : State
    7. {
    8.     // Reference type leitet von eine Klasse ab (Unity)
    9.     // Object kann man refernzieren (grün angezeigt), value type (blau angezeigt) nicht.
    10.     private CowFSM target = null;
    11.     private NavMeshAgent agent = null;
    12.     float minMakeLoveDistance;
    13.  
    14.     public MakeLove(CowFSM _cowFSM, float _minMakeLoveDistance) : base(_cowFSM)
    15.     {
    16.         if (agent == null)
    17.         {
    18.             // out for value type, ref for reference type
    19.             if (cowFSM.TryGetComponent(out NavMeshAgent _agent))
    20.             {
    21.                 agent = _agent;
    22.             }
    23. {
    24. }
    25.         }
    26.         minMakeLoveDistance = _minMakeLoveDistance;
    27.         cowFSM.CurrentCowState = CowFSM.CowState.MAKELOVE;
    28.         OnEnter();
    29.     }
    30.  
    31.     public override void OnEnter()
    32.     {
    33.         base.OnEnter();
    34.         target = FindBestCow();
    35.     }
    36.  
    37.     public override void OnUpdate()
    38.     {
    39.         if (target == null)
    40.         {
    41.             target = FindBestCow();
    42.             return;
    43.         }
    44.  
    45.         if(Vector3.Distance(target.transform.position, cowFSM.transform.position) <= minMakeLoveDistance)
    46.         {
    47.             cowFSM.MakeLove(target);
    48.             target = null;
    49.             return;
    50.         }
    51.  
    52.         if (agent.isActiveAndEnabled && !agent.hasPath && !agent.pathPending)
    53.         {
    54.             if (agent.isActiveAndEnabled && !agent.SetDestination(target.transform.position))
    55.             {
    56.                 if (NavMesh.SamplePosition(target.transform.position, out NavMeshHit hit, float.PositiveInfinity,
    57.                      NavMesh.AllAreas))
    58.                 {
    59.                     _ = agent.SetDestination(hit.position);
    60.                 }
    61.             }
    62.         }
    63.     }
    64.  
    65.     public override void CheckTransition()
    66.     {
    67.         if (cowFSM.Hunger > 20)
    68.         {
    69.             cowFSM.ChangeState(new Eat(cowFSM, cowFSM.feedDistance, 10));
    70.         }
    71.     }
    72.  
    73.     private CowFSM FindBestCow()
    74.     {
    75.         List<CowFSM> allCows = CowFSM.AllCows;
    76.         float closestDistance = float.PositiveInfinity;
    77.         CowFSM closestCow = null;
    78.         float temp;
    79.  
    80.         foreach (var cow in allCows)
    81.         {
    82.             if (cow == cowFSM || !(cow.CurrentState is MakeLove))
    83.             {
    84.                 continue;
    85.             }
    86.  
    87.             temp = Vector3.SqrMagnitude(cow.transform.position - cowFSM.transform.position);
    88.             if (temp < closestDistance)
    89.             {
    90.                 closestDistance = temp;
    91.                 closestCow = cow;
    92.             }
    93.         }
    94.  
    95.         return closestCow;
    96.     }
    97.  
    98. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CowFSM : MonoBehaviour
    6. {
    7.     // Für Debug.
    8.     public CowState CurrentCowState;
    9.     public enum CowState
    10.     {
    11.         IDLE, HUNGRY, MAKELOVE
    12.     }
    13.  
    14.     public static List<CowFSM> AllCows = new List<CowFSM>();
    15.  
    16.     [Header("General")]
    17.     [SerializeField] private float maxHunger;
    18.     [SerializeField] private float hungerRate;
    19.     [SerializeField] private GameObject cowPrefab;
    20.     [SerializeField] private float hunger;
    21.     // Hier ändert sich die aktive State dauerhaft in der Update.
    22.     private State currentState;
    23.  
    24.     [Header("Idle")]
    25.     [SerializeField] private float rotateSpeed;
    26.  
    27.     [Header("Eat")]
    28.     public float feedDistance;
    29.  
    30.     [Header("MakeLove")]
    31.     public float mateDistance;
    32.  
    33.     public float Hunger
    34.     {
    35.         get => hunger;
    36.         set
    37.         {
    38.             hunger = value;
    39.  
    40.             if (hunger >= maxHunger)
    41.             {
    42.                 Debug.Log(cowPrefab.gameObject.name + " is dead.");
    43.                 //Destroy(gameObject);
    44.                 gameObject.SetActive(false);
    45.             }
    46.         }
    47.     }
    48.  
    49.     public State CurrentState => currentState;
    50.  
    51.  
    52.     private void Awake()
    53.     {
    54.         AllCows.Add(this);
    55.         currentState = new Idle(this, rotateSpeed);
    56.     }
    57.  
    58.     private void OnDestroy()
    59.     {
    60.         AllCows.Remove(this);
    61.     }
    62.  
    63.     private void Update()
    64.     {
    65.         // Every second cowFSM gets 2 points of hunger.
    66.         Hunger += hungerRate * Time.deltaTime;
    67.  
    68.         currentState.CheckTransition();
    69.         currentState.OnUpdate();
    70.     }
    71.  
    72.     public void ChangeState(State _state)
    73.     {
    74.         currentState.OnExit();
    75.         currentState = _state;
    76.         currentState.OnEnter();
    77.     }
    78.  
    79.     public void EatFood(Food _food)
    80.     {
    81.         Debug.Log(cowPrefab.gameObject.name + " Has eaten the food");
    82.         // hunger -= _food.RefillFood(Hunger);
    83.         Hunger -= _food.RefillFood(Hunger);
    84.     }
    85.  
    86.     public void MakeLove(CowFSM _cow)
    87.     {
    88.         Hunger += 5;
    89.         _cow.Hunger += 5;
    90.  
    91.         // To solve a problem where the children would spawn frozen till death.
    92.         CowFSM child = Instantiate(cowPrefab, transform.position, transform.rotation).GetComponent<CowFSM>();
    93.  
    94.         if (!AllCows.Contains(child))
    95.         {
    96.             AllCows.Add(child);
    97.         }
    98.         child.currentState = new Idle(child, child.rotateSpeed);
    99.         // This fixes a problem where the children would spawn with Hunger at 10 and stay frozen till death.
    100.         child.Hunger = 15;
    101.     }
    102.  
    103.     private void OnDrawGizmos()
    104.     {
    105.         Gizmos.color = Color.red;
    106.         Gizmos.DrawWireSphere(transform.transform.position, mateDistance);
    107.         Gizmos.color = Color.blue;
    108.         Gizmos.DrawWireSphere(transform.transform.position, feedDistance);
    109.     }
    110. }
    111.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    (See bottom for general FSM notes)

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.




    FSM finite state machines:

    I suggest never using the term "state machine." Instead, just think:

    - I have to keep track of some THING(s)
    - That THING might change due to reasons
    - Depending on that THING, my code might act differently

    That's it. That's all it is. Really!! The classic example is a door:

    - track if it is open or closed
    - if it is open, you could close it
    - if it is closed, you could open it
    - if it is open you could walk through it
    - if it is closed you could bump into it

    Wanna make it more complex? Put a latch on one side of the door.

    This is my position on finite state machines (FSMs) and coding with them:

    https://forum.unity.com/threads/state-machine-help.1080983/#post-6970016

    I'm kind of more of a "get it working first" guy.

    Ask yourself, "WHY would I use FSM solution XYZ when I just need a variable and a switch statement?"

    All generic FSM solutions I have seen do not actually improve the problem space.

    Your mileage may vary.

    "I strongly suggest to make it as simple as possible. No classes, no interfaces, no needless OOP." - Zajoman on the Unity3D forums.
     
  3. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,917
    Some of the fancy OOP ways of making state machines can be tricky to figure out. My guess is you're forgetting to change state after giving birth.

    If it helps, I used state machines in my master's thesis, know how to convert an NFA into a DFA (the A stands for automata, which is the technical term for State Machine), ... tutored that stuff for a 300-level course ... know how the StateMachine Design Pattern is supposed to work ... ; and I still write my game state machines as simple "
    if(curState==State.Sleeping) { ... } else if(curState==State.Dancing) { ... } else ...
    ". I always figure I'll rewrite it as something slick when that crude method becomes cumbersome, but so far it never has.
     
    Kurt-Dekker likes this.