Search Unity

How can I pause my decrementing within an if statement?

Discussion in 'Scripting' started by Lethn, Aug 29, 2015.

  1. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class VisitorAI : MonoBehaviour {
    5.  
    6.     NavMeshAgent agent;
    7.     public GameObject sleepRestorePrefab;
    8.     public float tiredness = 100;
    9.  
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.  
    14.         agent = GetComponent<NavMeshAgent> ();
    15.  
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update () {
    20.  
    21.         agent.SetDestination (Random.insideUnitSphere * 350);
    22.  
    23.         tiredness -= Time.deltaTime * 5;
    24.  
    25.         if (tiredness < 50f)
    26.         {
    27.          
    28.             agent.SetDestination (GameObject.FindGameObjectWithTag ("SleepPrefab").transform.position);
    29.  
    30.             tiredness += Time.deltaTime * 20;
    31.         }
    32.  
    33.         else if (tiredness > 50f)
    34.      
    35.         {
    36.             agent.SetDestination (Random.insideUnitSphere * 350);
    37.         }
    38.  
    39.     }
    40. }
    41.  
    So my code is working and I'm quite happy to see my agents go straight to a building while reacting to something ( or in this case a cube prefab ) but as you'll immediately see the decrementing of my sleep variable is interfering with my incrementing so the agents get stuck their as by my own rules they can't leave until the sleep variable is more than 50.

    Now this should be a simple fix but I just can't think of what to place to stop the decrementing as return isn't working, so either I'm just placing it wrong or using the wrong function altogether.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Consider researching finite state machines. They will be slightly overkill for this problem, but totally invaluable if you continue with AI.
     
  3. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Well I've partly solved it just now by increasing the amount incremented but I want something a bit more specific so I'll have a look at what you suggested. I would have thought it would be something simpler though like using some kind of function to just pause the variable.
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You can simply put the increment line inside an if statement. Set a bool when you want the code to stop processing.