Search Unity

How can i decide if the cloned gameobjects will be Targets(patrolPoints) or not ?

Discussion in 'Scripting' started by Chocolade, May 29, 2017.

  1. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933
    I messed it all with too many bool variables and code.

    The first script Instantiate Objects.
    The script is attached to 3 different GameObjects and creating different cloned objects.


    On the left the Hierarchy the script is attached now to only two GameObjects and create children cloned gameobjects. On the right the script inspector.

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. //[ExecuteInEditMode]
    7. public class InstantiateObjects : MonoBehaviour
    8. {
    9.     public GameObject objectToInstantiate;
    10.     public Terrain terrain;
    11.     public float yOffset = 0.5f;
    12.     public int objectsToInstantiate;
    13.     public bool parent = true;
    14.     public bool randomScale = false;
    15.     public bool patrolPoints = false;
    16.    
    17.     public Vector3 RandScaleMin;
    18.     public Vector3 RandScaleMax;
    19.  
    20.     private float terrainWidth;
    21.     private float terrainLength;
    22.     private float xTerrainPos;
    23.     private float zTerrainPos;
    24.     private int numberOfObjectsToCreate;
    25.     private GameObject objInstance;
    26.     private GameObject[] createdObjects;
    27.     private string objname;
    28.     private bool destroyObjects = false;
    29.     private bool listUpdated = false;
    30.  
    31.     public void Start()
    32.     {
    33.         //Get terrain size
    34.         terrainWidth = terrain.terrainData.size.x;
    35.         terrainLength = terrain.terrainData.size.z;
    36.  
    37.         //Get terrain position
    38.         xTerrainPos = terrain.transform.position.x;
    39.         zTerrainPos = terrain.transform.position.z;
    40.  
    41.         numberOfObjectsToCreate = objectsToInstantiate;
    42.  
    43.         objname = objectToInstantiate.name;
    44.         MyCustomEditor.TagsAndLayers.AddTag(objname);
    45.  
    46.         generateObjectOnTerrain();
    47.     }
    48.  
    49.     public void Update()
    50.     {
    51.         if (patrolPoints == true && destroyObjects == true
    52.             && listUpdated == false)
    53.         {
    54.             UpdateList(true, objname);
    55.         }
    56.         if (patrolPoints == true && destroyObjects == false
    57.             && listUpdated == false)
    58.         {
    59.             UpdateList(false, objname);
    60.         }
    61.  
    62.         if (patrolPoints == false)
    63.         {
    64.             listUpdated = false;
    65.             RemovePatrols(objname, true);
    66.         }
    67.     }
    68.  
    69.     public void DestroyObjects()
    70.     {
    71.         UpdateList(true, objname);
    72.  
    73.         if (createdObjects != null && createdObjects.Length > 0)
    74.         {
    75.             for (int i = 0; i < createdObjects.Length; i++)
    76.             {
    77.                 DestroyImmediate(createdObjects[i]);
    78.             }
    79.             createdObjects = new GameObject[0];
    80.         }
    81.     }
    82.  
    83.     public void generateObjectOnTerrain()
    84.     {
    85.         for (int i = 0; i < objectsToInstantiate; i++)
    86.         {
    87.             //Generate random x,z,y position on the terrain
    88.             float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
    89.             float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
    90.  
    91.             float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));
    92.  
    93.             var randScaleX = Random.Range(RandScaleMin.x, RandScaleMax.x);
    94.             var randScaleY = Random.Range(RandScaleMin.y, RandScaleMax.y);
    95.             var randScaleZ = Random.Range(RandScaleMin.z, RandScaleMax.z);
    96.             var randVector3 = new Vector3(randScaleX, randScaleY, randScaleZ);
    97.  
    98.             //Apply Offset if needed
    99.             yVal = yVal + yOffset;
    100.  
    101.             //Generate the Prefab on the generated position        
    102.             objInstance = Instantiate(objectToInstantiate, new Vector3(randX, yVal, randZ), Quaternion.identity);
    103.  
    104.             if (randomScale == true)
    105.                 objInstance.transform.localScale = randVector3;//new Vector3(randScaleX, randScaleY, randScaleZ);
    106.  
    107.             if (parent)
    108.                 objInstance.transform.parent = this.transform;
    109.  
    110.             objInstance.tag = objname;
    111.         }
    112.  
    113.         createdObjects = GameObject.FindGameObjectsWithTag(objname);
    114.  
    115.         if (patrolPoints == true)
    116.             UpdateList(false, objname);
    117.     }
    118.  
    119.     private void UpdateList(bool destroy, string tagname)
    120.     {
    121.         listUpdated = false;
    122.         destroyObjects = destroy;
    123.         GameObject go = GameObject.Find("Main Camera");
    124.         var list = go.GetComponent<PatrolOverTerrain>().Targets;
    125.         if (destroy == false)
    126.         {
    127.             list.AddRange(createdObjects);
    128.             go.GetComponent<PatrolOverTerrain>().Targets = list;
    129.             go.GetComponent<PatrolOverTerrain>().tagName = tagname;
    130.             go.GetComponent<PatrolOverTerrain>().removedTargets = false;
    131.             listUpdated = true;
    132.         }
    133.  
    134.         if (destroy == true)
    135.         {
    136.             list.Clear();
    137.             go.GetComponent<PatrolOverTerrain>().Targets.Clear();
    138.             go.GetComponent<PatrolOverTerrain>().tagName = tagname;
    139.             go.GetComponent<PatrolOverTerrain>().removedTargets = false;
    140.             listUpdated = true;
    141.         }
    142.     }
    143.  
    144.     private void RemovePatrols(string tagname, bool removed)
    145.     {
    146.         GameObject go = GameObject.Find("Main Camera");
    147.         var list = go.GetComponent<PatrolOverTerrain>().Targets;
    148.         list.Clear();
    149.         go.GetComponent<PatrolOverTerrain>().Targets.Clear();
    150.         go.GetComponent<PatrolOverTerrain>().tagName = tagname;
    151.         go.GetComponent<PatrolOverTerrain>().removedTargets = removed;
    152.     }
    153. }
    154.  
    Then i have a script of a ui button and ui toggle i'm using it to decide if to destroy and create new cloned gameobjects or without destroying and only to create new cloned gameobjects.
    So if i the toggle is checked it will destroy first and will create new objects. If not checked it will just add new gameobjects to the already exists.

    For example if in the inspector i set to 20 and then uncheck the toggle and click the ui button it will add more new 20 gameobjects. If checked and clicked the button it will destroy first and then will add new 20 clones.

    This is the game window when the game is not running showing the button and the ui:



    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class GenerateObjectsButton : MonoBehaviour
    8. {
    9.     [SerializeField]
    10.     private InstantiateObjects[] instantiateobjects;
    11.     private bool toggleOnOf;
    12.     public Toggle toggle;
    13.     public bool destroyed = false;
    14.  
    15.     private void Start()
    16.     {
    17.         toggle.onValueChanged.AddListener((value) =>
    18.             {
    19.                 MyListener(value);
    20.             });
    21.     }
    22.  
    23.     public void MyListener(bool value)
    24.     {
    25.         if (value)
    26.         {
    27.             //do the stuff when the toggle is on
    28.             toggleOnOf = true;
    29.         }
    30.         else
    31.         {
    32.             //do the stuff when the toggle is off
    33.             toggleOnOf = false;
    34.         }
    35.     }
    36.  
    37.     public void OnButton()
    38.     {
    39.         for (int i = 0; i < instantiateobjects.Length; i++)
    40.         {
    41.             if (toggleOnOf == false)
    42.             {
    43.                 if (instantiateobjects[i] != null)
    44.                     instantiateobjects[i].generateObjectOnTerrain();
    45.             }
    46.             else
    47.             {
    48.                 if (instantiateobjects[i] != null)
    49.                 {
    50.                     instantiateobjects[i].DestroyObjects();
    51.                     instantiateobjects[i].generateObjectOnTerrain();
    52.                     destroyed = true;
    53.                 }
    54.             }
    55.         }
    56.     }
    57. }
    58.  
    And the last script create the patrolPoints array (like waypoints).
    I'm using a public List name Targets and updating the list also in the InstantiateObjects script to decide if to destroy or not to destroy first when creating new cloned gameobjects.

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. [System.Serializable]
    7. public class PatrolData
    8. {
    9.     public Transform target = null;
    10.     public float minDistance = 5f;
    11.     public float lingerDuration = 5f;
    12.  
    13.     public float desiredHeight = 10f;
    14.  
    15.     public float flightSmoothTime = 10f;
    16.     public float maxFlightspeed = 10f;
    17.     public float flightAcceleration = 1f;
    18.  
    19.     public float levelingSmoothTime = 0.5f;
    20.     public float maxLevelingSpeed = 10000f;
    21.     public float levelingAcceleration = 2f;
    22. }
    23.  
    24. public class PatrolOverTerrain : MonoBehaviour
    25. {
    26.     public FlyToOverTerrain flyOverTerrain;
    27.     public LookAtCamera lookAtCamera;
    28.     public enum PatrolMode { Clamp, Wrap, PingPong };
    29.     public PatrolData[] patrolPoints;
    30.     public PatrolMode mode = PatrolMode.Wrap;
    31.  
    32.     private int iterator = 0;
    33.     private int index = 0;
    34.     private float lingerDuration = 0f;
    35.     private int oldLength = 0;
    36.  
    37.     public bool autoFreedomPatrol = false;
    38.     public List<GameObject> Targets = new List<GameObject>();
    39.     public string tagName;
    40.     public bool removedTargets;
    41.     public Vector3 distanceFromTarget;
    42.  
    43.     private void Start()
    44.     {
    45.         if (tagName != "")
    46.         {
    47.             GameObject[] tempObj = GameObject.FindGameObjectsWithTag(tagName);
    48.  
    49.             for (int i = 0; i < tempObj.Length; i++)
    50.             {
    51.                 //Add to list only if it does not exist
    52.                 if (!Targets.Contains(tempObj[i]))
    53.                 {
    54.                     Targets.Add(tempObj[i]);
    55.                 }
    56.             }
    57.  
    58.             //Get the current Size
    59.             if (tempObj != null)
    60.             {
    61.                 oldLength = tempObj.Length;
    62.             }
    63.  
    64.             GeneratePatrolPoints();
    65.         }
    66.     }
    67.  
    68.     private void OnEnable()
    69.     {
    70.         if (patrolPoints.Length > 0)
    71.         {
    72.             lingerDuration = patrolPoints[index].lingerDuration;
    73.         }
    74.     }
    75.  
    76.     private void Update()
    77.     {
    78.         if (tagName != "")
    79.         {
    80.             if (removedTargets == false)
    81.             {
    82.                 GameObject[] tempObj = GameObject.FindGameObjectsWithTag(tagName);
    83.  
    84.                 for (int i = 0; i < tempObj.Length; i++)
    85.                 {
    86.                     //Add to list only if it does not exist
    87.                     if (!Targets.Contains(tempObj[i]))
    88.                     {
    89.                         Targets.Add(tempObj[i]);
    90.                     }
    91.                 }
    92.             }
    93.  
    94.             //Check if oldLength has changed
    95.             if (oldLength != Targets.Count)
    96.             {
    97.                 //Update oldLength
    98.                 oldLength = Targets.Count;
    99.  
    100.                 //Call your the function
    101.                 GeneratePatrolPoints();
    102.             }
    103.  
    104.             GameObject go = GameObject.Find("Button");
    105.             var destroyed = go.GetComponent<GenerateObjectsButton>().destroyed;
    106.             if (destroyed)
    107.             {
    108.                 GeneratePatrolPoints();
    109.             }
    110.  
    111.             int length = patrolPoints.Length;
    112.             if (!flyOverTerrain) return;
    113.             if (patrolPoints.Length < 1) return;
    114.             if (index < 0) return;
    115.  
    116.             // Getting exception out of index on line 89.
    117.             // Need to make a list also for the Cubes(buildings).
    118.  
    119.             var patrol = patrolPoints[index];
    120.             if (lingerDuration <= 0)
    121.             {
    122.                 iterator++;
    123.                 switch (mode)
    124.                 {
    125.                     case PatrolMode.Clamp:
    126.                         index = (iterator >= length) ? -1 : iterator;
    127.                         break;
    128.                     case PatrolMode.Wrap:
    129.                         iterator = Modulus(iterator, length);
    130.                         index = iterator;
    131.                         break;
    132.                     case PatrolMode.PingPong:
    133.                         index = PingPong(iterator, length);
    134.                         break;
    135.                 }
    136.                 if (index < 0) return;
    137.  
    138.                 patrol = patrolPoints[index];
    139.  
    140.                 flyOverTerrain.target = patrol.target;
    141.                 flyOverTerrain.desiredHeight = patrol.desiredHeight;
    142.                 flyOverTerrain.flightSmoothTime = patrol.flightSmoothTime;
    143.                 flyOverTerrain.maxFlightspeed = patrol.maxFlightspeed;
    144.                 flyOverTerrain.flightAcceleration = patrol.flightAcceleration;
    145.                 flyOverTerrain.levelingSmoothTime = patrol.levelingSmoothTime;
    146.                 flyOverTerrain.maxLevelingSpeed = patrol.maxLevelingSpeed;
    147.                 flyOverTerrain.levelingAcceleration = patrol.levelingAcceleration;
    148.  
    149.                 lookAtCamera.target = patrol.target;
    150.                 lookAtCamera.RotationSpeed = 3;
    151.  
    152.                 lingerDuration = patrolPoints[index].lingerDuration;
    153.             }
    154.  
    155.  
    156.             Vector3 targetOffset = Vector3.zero;
    157.             if ((bool)patrol.target)
    158.             {
    159.                 targetOffset = transform.position - patrol.target.position;
    160.             }
    161.  
    162.             float sqrDistance = patrol.minDistance * patrol.minDistance;
    163.             if (targetOffset.sqrMagnitude <= sqrDistance)
    164.             {
    165.                 flyOverTerrain.target = null;
    166.                 lookAtCamera.target = null;
    167.                 lingerDuration -= Time.deltaTime;
    168.             }
    169.             else
    170.             {
    171.                 flyOverTerrain.target = patrol.target;
    172.                 lookAtCamera.target = patrol.target;
    173.             }
    174.             distanceFromTarget = transform.position - patrol.target.position;
    175.         }
    176.     }
    177.  
    178.     private int PingPong(int baseNumber, int limit)
    179.     {
    180.         if (limit < 2) return 0;
    181.         return limit - Mathf.Abs(limit - Modulus(baseNumber, limit + (limit - 2)) - 1) - 1;
    182.     }
    183.  
    184.     private int Modulus(int baseNumber, int modulus)
    185.     {
    186.         return (modulus == 0) ? baseNumber : baseNumber - modulus * (int)Mathf.Floor(baseNumber / (float)modulus);
    187.     }
    188.  
    189.     public void GeneratePatrolPoints()
    190.     {
    191.         patrolPoints = new PatrolData[Targets.Count];
    192.         for (int i = 0; i < patrolPoints.Length; i++)
    193.         {
    194.             patrolPoints[i] = new PatrolData();
    195.             patrolPoints[i].target = Targets[i].transform;
    196.             patrolPoints[i].minDistance = 30f;
    197.             patrolPoints[i].lingerDuration = 3f;
    198.             patrolPoints[i].desiredHeight = 20f;
    199.             patrolPoints[i].flightSmoothTime = 10f;
    200.             patrolPoints[i].maxFlightspeed = 10f;
    201.             patrolPoints[i].flightAcceleration = 3f;
    202.             patrolPoints[i].levelingSmoothTime = 0.5f;
    203.             patrolPoints[i].maxLevelingSpeed = 10000f;
    204.             patrolPoints[i].levelingAcceleration = 2f;
    205.         }
    206.     }
    207. }
    208.  
    My logic of how it should work with all 3 scripts is:

    When running the game if in one GameObject in the inspector the property Patrol Points is checked/unchecked add or not the cloned objects only for this children clones to the Targets list and to the patrolPoints.

    Same thing if the game is already running and i check/uncheck the Patrol Points cool variable update and remove/add the cloned gameobjects from the Targets list and the patrolPoints.

    Back to the first screenshot if for example in the Teleportation Booths inspector i check the Patrol Points add all the cloned Teleportation Booth(clone) children to the Targets list and to the patrolPoints and if unchecked remove them.

    The part with the ui button and ui toggle script was working fine and still working fine.
    But then i tried to make the part with the Patrol Points bool and messed it all up in the InstantiateObjects script with the Update function and the UpdateList and the RemovePatrols and then in the PatrolOverTerrain i messed it all also in the Update function with that:

    Code (csharp):
    1.  
    2. if (tagName != "")
    3.         {
    4.             if (removedTargets == false)
    5.             {
    6.                 GameObject[] tempObj = GameObject.FindGameObjectsWithTag(tagName);
    7.  
    8.                 for (int i = 0; i < tempObj.Length; i++)
    9.                 {
    10.                     //Add to list only if it does not exist
    11.                     if (!Targets.Contains(tempObj[i]))
    12.                     {
    13.                         Targets.Add(tempObj[i]);
    14.                     }
    15.                 }
    16.             }
    17.  
    In general the goal is to make it possible to add/remove the cloned objects to/from the Targets list and update the patrolPoints array.
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    So, after at least 5 mins of reviewing your post here...
    Is it safe to say that you're looking for a way to update your targets and patrol points -- that's it? :)

    I think targets is a list, already.. but patrolpoints is an array. It might be easier to change patrolpoints to a list, also (can be done without the change, but maybe easier with).

    Now, because your post was pretty long, I nodded off a few times reading it over lol heh.
    But I think that when you generate your new objects, you should just update the lists at that time (avoid Update() , again).
    I mean, if the bool is to remove old ones, just clear the list.
    If it's to add, just '.Add()' to the list.
    You might have to change a few bits of code to replace the array with a list, but not too much.

    Please write back if there's something I overlooked/missed. (Please just relevant parts, though.:))
     
  3. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933

    I tried for long time now but can't make it work right yet.
    I have problems with only doing the part with the ui button and ui toggle to decide when to destroy and create new gameobjects or without destroying first and create only new cloned gameobjects and add them to the already existing ones.

    I'm not yet in the part to decide if the new/old cloned gameobjects should be patrolPoints when running the game and while the game is running.

    I changed the code a bit.

    The script with the ui button is still the same not changed.
    The script InstantiateObjects i remove all the Update code part and changed the UpdateList part:

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. //[ExecuteInEditMode]
    7. public class InstantiateObjects : MonoBehaviour
    8. {
    9.     public GameObject objectToInstantiate;
    10.     public Terrain terrain;
    11.     public float yOffset = 0.5f;
    12.     public int objectsToInstantiate;
    13.     public bool parent = true;
    14.     public bool randomScale = false;
    15.     public bool patrolPoints = false;
    16.    
    17.     public Vector3 RandScaleMin;
    18.     public Vector3 RandScaleMax;
    19.  
    20.     private float terrainWidth;
    21.     private float terrainLength;
    22.     private float xTerrainPos;
    23.     private float zTerrainPos;
    24.     private int numberOfObjectsToCreate;
    25.     private GameObject objInstance;
    26.     private GameObject[] createdObjects;
    27.     private string objname;
    28.     private bool destroyObjects = false;
    29.     private bool listUpdated = false;
    30.  
    31.     public void Start()
    32.     {
    33.         //Get terrain size
    34.         terrainWidth = terrain.terrainData.size.x;
    35.         terrainLength = terrain.terrainData.size.z;
    36.  
    37.         //Get terrain position
    38.         xTerrainPos = terrain.transform.position.x;
    39.         zTerrainPos = terrain.transform.position.z;
    40.  
    41.         numberOfObjectsToCreate = objectsToInstantiate;
    42.  
    43.         objname = objectToInstantiate.name;
    44.         MyCustomEditor.TagsAndLayers.AddTag(objname);
    45.  
    46.         generateObjectOnTerrain();
    47.     }
    48.  
    49.     public void Update()
    50.     {
    51.        
    52.     }
    53.  
    54.     public void DestroyObjects()
    55.     {
    56.         UpdateList(true, objname);
    57.  
    58.         if (createdObjects != null && createdObjects.Length > 0)
    59.         {
    60.             for (int i = 0; i < createdObjects.Length; i++)
    61.             {
    62.                 DestroyImmediate(createdObjects[i]);
    63.             }
    64.             createdObjects = new GameObject[0];
    65.         }
    66.     }
    67.  
    68.     public void generateObjectOnTerrain()
    69.     {
    70.         for (int i = 0; i < objectsToInstantiate; i++)
    71.         {
    72.             //Generate random x,z,y position on the terrain
    73.             float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
    74.             float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
    75.  
    76.             float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));
    77.  
    78.             var randScaleX = Random.Range(RandScaleMin.x, RandScaleMax.x);
    79.             var randScaleY = Random.Range(RandScaleMin.y, RandScaleMax.y);
    80.             var randScaleZ = Random.Range(RandScaleMin.z, RandScaleMax.z);
    81.             var randVector3 = new Vector3(randScaleX, randScaleY, randScaleZ);
    82.  
    83.             //Apply Offset if needed
    84.             yVal = yVal + yOffset;
    85.  
    86.             //Generate the Prefab on the generated position        
    87.             objInstance = Instantiate(objectToInstantiate, new Vector3(randX, yVal, randZ), Quaternion.identity);
    88.  
    89.             if (randomScale == true)
    90.                 objInstance.transform.localScale = randVector3;//new Vector3(randScaleX, randScaleY, randScaleZ);
    91.  
    92.             if (parent)
    93.                 objInstance.transform.parent = this.transform;
    94.  
    95.             objInstance.tag = objname;
    96.         }
    97.  
    98.         createdObjects = GameObject.FindGameObjectsWithTag(objname);
    99.  
    100.         //if (patrolPoints == true)
    101.             UpdateList(false, objname);
    102.     }
    103.  
    104.     private void UpdateList(bool destroy, string tagname)
    105.     {
    106.         GameObject go = GameObject.Find("Main Camera");
    107.         var list = go.GetComponent<PatrolOverTerrain>().Targets;
    108.         if (destroy == false)
    109.         {
    110.             list.AddRange(createdObjects);
    111.             go.GetComponent<PatrolOverTerrain>().Targets = list;
    112.             go.GetComponent<PatrolOverTerrain>().tagName = tagname;
    113.         }
    114.  
    115.         if (destroy == true)
    116.         {
    117.             list.Clear();
    118.             go.GetComponent<PatrolOverTerrain>().Targets.Clear();
    119.             go.GetComponent<PatrolOverTerrain>().tagName = tagname;
    120.         }
    121.     }
    122. }
    123.  
    And the last script the PatrolOverTerrain i removed all the Start() code part and leave only the Update part changes:
    The code in the Start() still exist but i marked not to use it:


    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. [System.Serializable]
    7. public class PatrolData
    8. {
    9.     public Transform target = null;
    10.     public float minDistance = 5f;
    11.     public float lingerDuration = 5f;
    12.  
    13.     public float desiredHeight = 10f;
    14.  
    15.     public float flightSmoothTime = 10f;
    16.     public float maxFlightspeed = 10f;
    17.     public float flightAcceleration = 1f;
    18.  
    19.     public float levelingSmoothTime = 0.5f;
    20.     public float maxLevelingSpeed = 10000f;
    21.     public float levelingAcceleration = 2f;
    22. }
    23.  
    24. public class PatrolOverTerrain : MonoBehaviour
    25. {
    26.     public FlyToOverTerrain flyOverTerrain;
    27.     public LookAtCamera lookAtCamera;
    28.     public enum PatrolMode { Clamp, Wrap, PingPong };
    29.     public PatrolData[] patrolPoints;
    30.     public PatrolMode mode = PatrolMode.Wrap;
    31.  
    32.     private int iterator = 0;
    33.     private int index = 0;
    34.     private float lingerDuration = 0f;
    35.     private int oldLength = 0;
    36.  
    37.     public bool autoFreedomPatrol = false;
    38.     public List<GameObject> Targets = new List<GameObject>();
    39.     public string tagName;
    40.     public Vector3 distanceFromTarget;
    41.  
    42.     private void Start()
    43.     {
    44.         /*if (tagName != "")
    45.         {
    46.             GameObject[] tempObj = GameObject.FindGameObjectsWithTag(tagName);
    47.  
    48.             for (int i = 0; i < tempObj.Length; i++)
    49.             {
    50.                 //Add to list only if it does not exist
    51.                 if (!Targets.Contains(tempObj[i]))
    52.                 {
    53.                     Targets.Add(tempObj[i]);
    54.                 }
    55.             }
    56.  
    57.             //Get the current Size
    58.             if (tempObj != null)
    59.             {
    60.                 oldLength = tempObj.Length;
    61.             }
    62.  
    63.             GeneratePatrolPoints();
    64.         }*/
    65.     }
    66.  
    67.     private void OnEnable()
    68.     {
    69.         if (patrolPoints.Length > 0)
    70.         {
    71.             lingerDuration = patrolPoints[index].lingerDuration;
    72.         }
    73.     }
    74.  
    75.     private void Update()
    76.     {
    77.         if (tagName != "")
    78.         {
    79.             //Check if oldLength has changed
    80.             if (oldLength != Targets.Count)
    81.             {
    82.                 //Update oldLength
    83.                 oldLength = Targets.Count;
    84.  
    85.                 //Call your the function
    86.                 GeneratePatrolPoints();
    87.             }
    88.  
    89.             GameObject go = GameObject.Find("Button");
    90.             var destroyed = go.GetComponent<GenerateObjectsButton>().destroyed;
    91.             if (destroyed)
    92.             {
    93.                 GeneratePatrolPoints();
    94.             }
    95.  
    96.             int length = patrolPoints.Length;
    97.             if (!flyOverTerrain) return;
    98.             if (patrolPoints.Length < 1) return;
    99.             if (index < 0) return;
    100.  
    101.             // Getting exception out of index on line 89.
    102.             // Need to make a list also for the Cubes(buildings).
    103.  
    104.             var patrol = patrolPoints[index];
    105.             if (lingerDuration <= 0)
    106.             {
    107.                 iterator++;
    108.                 switch (mode)
    109.                 {
    110.                     case PatrolMode.Clamp:
    111.                         index = (iterator >= length) ? -1 : iterator;
    112.                         break;
    113.                     case PatrolMode.Wrap:
    114.                         iterator = Modulus(iterator, length);
    115.                         index = iterator;
    116.                         break;
    117.                     case PatrolMode.PingPong:
    118.                         index = PingPong(iterator, length);
    119.                         break;
    120.                 }
    121.                 if (index < 0) return;
    122.  
    123.                 patrol = patrolPoints[index];
    124.  
    125.                 flyOverTerrain.target = patrol.target;
    126.                 flyOverTerrain.desiredHeight = patrol.desiredHeight;
    127.                 flyOverTerrain.flightSmoothTime = patrol.flightSmoothTime;
    128.                 flyOverTerrain.maxFlightspeed = patrol.maxFlightspeed;
    129.                 flyOverTerrain.flightAcceleration = patrol.flightAcceleration;
    130.                 flyOverTerrain.levelingSmoothTime = patrol.levelingSmoothTime;
    131.                 flyOverTerrain.maxLevelingSpeed = patrol.maxLevelingSpeed;
    132.                 flyOverTerrain.levelingAcceleration = patrol.levelingAcceleration;
    133.  
    134.                 lookAtCamera.target = patrol.target;
    135.                 lookAtCamera.RotationSpeed = 3;
    136.  
    137.                 lingerDuration = patrolPoints[index].lingerDuration;
    138.             }
    139.  
    140.  
    141.             Vector3 targetOffset = Vector3.zero;
    142.             if ((bool)patrol.target)
    143.             {
    144.                 targetOffset = transform.position - patrol.target.position;
    145.             }
    146.  
    147.             float sqrDistance = patrol.minDistance * patrol.minDistance;
    148.             if (targetOffset.sqrMagnitude <= sqrDistance)
    149.             {
    150.                 flyOverTerrain.target = null;
    151.                 lookAtCamera.target = null;
    152.                 lingerDuration -= Time.deltaTime;
    153.             }
    154.             else
    155.             {
    156.                 flyOverTerrain.target = patrol.target;
    157.                 lookAtCamera.target = patrol.target;
    158.             }
    159.             distanceFromTarget = transform.position - patrol.target.position;
    160.         }
    161.     }
    162.  
    163.     private int PingPong(int baseNumber, int limit)
    164.     {
    165.         if (limit < 2) return 0;
    166.         return limit - Mathf.Abs(limit - Modulus(baseNumber, limit + (limit - 2)) - 1) - 1;
    167.     }
    168.  
    169.     private int Modulus(int baseNumber, int modulus)
    170.     {
    171.         return (modulus == 0) ? baseNumber : baseNumber - modulus * (int)Mathf.Floor(baseNumber / (float)modulus);
    172.     }
    173.  
    174.     public void GeneratePatrolPoints()
    175.     {
    176.         patrolPoints = new PatrolData[Targets.Count];
    177.         for (int i = 0; i < patrolPoints.Length; i++)
    178.         {
    179.             patrolPoints[i] = new PatrolData();
    180.             patrolPoints[i].target = Targets[i].transform;
    181.             patrolPoints[i].minDistance = 30f;
    182.             patrolPoints[i].lingerDuration = 3f;
    183.             patrolPoints[i].desiredHeight = 20f;
    184.             patrolPoints[i].flightSmoothTime = 10f;
    185.             patrolPoints[i].maxFlightspeed = 10f;
    186.             patrolPoints[i].flightAcceleration = 3f;
    187.             patrolPoints[i].levelingSmoothTime = 0.5f;
    188.             patrolPoints[i].maxLevelingSpeed = 10000f;
    189.             patrolPoints[i].levelingAcceleration = 2f;
    190.         }
    191.     }
    192. }
    193.  
    My logic i think of how this 3 scripts should be working:

    Case 1: Destroy > Create new > patrolPoints
    Case 2: Create new > patrolPoints
    Case 3: Destroy > Create new
    Case 4: Create new

    So if for example the InstantiateObjects is attached to 5 different gameobjects in the hierarchy on 1 i have 20 cloned gameobjects on the 2 i have 5 cloned gameobjects on 3 there are 70 cloned gameobjects on 4 there are 4 cloned gameobjects on 5 there 55 cloned gameobjects.

    Now apply this cases to each one of the children cloned objects of each gameobject the InstantiateObjects is attached to.

    But i can't figure out yet how to do it all.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I don't know how others might read your post, but could you shorten your immediate question a bit, in case I"m the next person to read it? :) I get the impression that you have a lot on your mind, but I feel swamped when I read your post that's very long and I might be getting a little lost as to your question.
    From your first post, I thought you wanted to keep the list updated when you add/remove items from it..
    Is that the case (still)?
     
  5. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933
    LOL :) Sorry for that.

    What i want is with the ui button and toggle to create new objects. If the toggle is on first destroy the objects then create new. So if i have 20 objects cloned i first destroy them then create new so there will be new 20 objects. But if the toggle is off and i click the button and i have 20 objects now there will be 60 objects. the old 20 + new 40.

    The other part the problem is with the patrolPoints.
    I want that if i check the patrolPoints bool make the cloned objects patrolPoints in the array in the script PatrolOverTerrain.
    If the patrolPoints bool is unchecked don't make them patrolPoints in the array remove this objects from the array.
    This is what i'm trying to do with the UpdateList.

    "I thought you wanted to keep the list updated when you add/remove items from it..
    Is that the case (still) ?"

    Yes this is still the case updating the patrolPoints array according to the patrolPoints bool state.

    The whole updating part between the InstantiateObjects script and the PatrolOverTerrain script is the problem.
     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I thought we already got the part with the UI button and toggle working??

    Okay, one last question. Does setting that bool change your current patrolpoints or just the new ones (or both)?

    PS. That was much easier to understand that time!