Search Unity

Simple Traffic System

Discussion in 'Assets and Asset Store' started by Stephen_O, Dec 15, 2019.

  1. Exi-G

    Exi-G

    Joined:
    Sep 5, 2012
    Posts:
    9
    Is the AI vehicles gonna have engine sounds? I haven't had time to experiment with the package properly but I notice that the vehicles don't have engine sound so i just want to know if there are any plan for that.
     
  2. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Version 1.0.7 will expose the CurrentSpeed to AITrafficCar for reading, this will allow you to setup a custom sound script using CurrentSpeed to control your audio; I'll try to make a simple sound script that can be added to the cars that can utilize this in one of the next updates.
     
    combatsheep and Exi-G like this.
  3. Exi-G

    Exi-G

    Joined:
    Sep 5, 2012
    Posts:
    9
    Ok nice
     
  4. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Hello, Version 1.0.7 is being prepared for submission to the store.

    I wanted to take a moment to say thank you to everyone for the initial support of my work and any feedback that you have provided. This asset was originally developed for my own personal use, I did not expect it to recieve the amount of interest that it has. If it wasn't for the people who reached out to me, I would have never published this asset. Because of this interest, I've been working on making the asset as easy and intuitive to use as possible since placing it on the asset store. Please continue to provide feedback and requests - there's no promise that I will add requests, but they can be useful to help me understand how you use the asset, plan for future developments, or improvements to consider.

    This update provides improvements to all of the editor utility tools that have been added since version 1.0 was released. The utility windows have been combined and overhauled to provide a more intuitive, fast and enjoyable experience when configuring your routes.

    Version 1.0.7 change log:
    • Moved all editor tools to a single window named STS Tools.
    • Moved all editor menu bar commands to STS Tools window.
    • Added Undo/Redo support for all actions in STS Tools Window.
    • Added Undo/Redo support for AITrafficWaypointRoute click to add/insert waypoints.
    • Added Undo/Redo support for Spline Route Creator click to add/insert waypoints.
    • Added disconnect light from route option in Signal Connector window.
    • Added handle draw distance option to editor window tools.
    • Added handle color customization options to editor window tools.
    • Added BrakeLight script. Add it to AITrafficCar prefab, assign Lights into an array, they'll get toggled on/off.
    • Improved scene view handle buttons, they are now scaled based on distance to camera
    • Improved Route Connector handle buttons, selecting a currently selected To or From handle will now deselect it.
    • Improved Lane Connector handle buttons, selecting a currently selected Route handle will now deselect it.
    • Improved Signal Connector handle buttons, selecting a currently selected Route or Light handle will now deselect it.
    • Fixed Spawn Points window handle buttons, a button is now only drawn if the waypoint does not have a spawn point.
    • Fixed a bug where using the Signal Connector window with a prefab would not properly mark the prefab as changed resulting in changes not being saved.
    • Fixed a bug where using pooling would not spawn startup traffic as expected, most noticeable in small road networks.
    • Fixed a bug where using pooling the initial spawn amount would not match the pool density.
    • Fixed a bug where the car brake light would not be enabled when StopDriving is called.
    • Changed AITrafficWaypointRoute add waypoint function from Alt+LeftClick to Shift+LeftClick.
    • Changed AITrafficWaypointRoute insert waypoint function from Alt+Ctrl+LeftClick to Shift+Ctrl+LeftClick.
    • Changed SplineRouteCreator add waypoint function from Alt+LeftClick to Shift+LeftClick.
    • Changed SplineRouteCreator insert waypoint function from Alt+Ctrl+LeftClick to Shift+Ctrl+LeftClick.
    • Exposed CurrentSpeed to AITrafficCar for reading
    • Exposed IsBraking to AITrafficCar for reading
     
  5. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Some new tutorials for 1.0.7

    1. Getting Started:


    2. Connecting Routes:


    3. Traffic Lights:


    4. Spline Route Creator:
     
    Freznosis likes this.
  6. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    More new tutorials for 1.0.7

    5. Spawn points:


    6. Lane Changing:


    7. Traffic Pooling:


    8. Change Car Model:
     
    Freznosis likes this.
  7. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Version 1.0.7 has been submitted.
     
  8. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Version 1.0.7 is now available.
     
    Freznosis and MK1_Dev like this.
  9. Necka_

    Necka_

    Joined:
    Jan 22, 2018
    Posts:
    488
    Hi Stephen,
    Hope you are doing fine :)

    I have a question regarding a use case and would like to know if something's possible.
    As you might remember I'm using STS to put some life around in my city. The player is not going to drive on the roads.

    I am using the pooling system.
    I'd like to know if there is a way to force cars to "reset" on a non-ending road such as this example:
    upload_2020-3-31_14-27-11.png

    Basically most of my roads are connected but here for efficiency reasons I'd like to avoid looping that road part. It will be hidden with a building on top, so basically I just want that the player see cars going in the tunnel and we don't really care if the car ever comes out :)

    I was thinking as it is using pooling that I could call a method on reaching the last waypoint so the car returns to the pool.

    Is that possible and if yes, what method should I be calling (and any other thing I need to take care off so car life still goes on of course)

    thanks by advance!
     
    Stephen_O likes this.
  10. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Hi Necka_,

    Yes, you can do this with a simple script.

    The idea is get a reference to the AITrafficCar script to get the car's assignedIndex, then use that to call AITrafficController.MoveCarToPool(assignedIndex).

    As an example, you can create a Cube, set BoxCollider IsTrigger to true, and attach this script. Then use it as a trigger zone to return the cars to the pool.

    I used a tag in this example, so you'd need to add it and mark your AITrafficCar prefabs with the tag AITrafficCar for the script to work. I believe you're using custom physics layers in your project settings, so you can likely setup a more optimized check.

    Code (CSharp):
    1. using UnityEngine;
    2. using TurnTheGameOn.SimpleTrafficSystem;
    3.  
    4. public class ReturnToPool : MonoBehaviour
    5. {
    6.     private void OnTriggerEnter(Collider other)
    7.     {
    8.         if (other.tag == "AITrafficCar")
    9.         {
    10.             AITrafficCar _AITrafficCar = other.GetComponent<AITrafficCar>();
    11.             int _assignedIndex = _AITrafficCar.assignedIndex;
    12.             AITrafficController.Instance.MoveCarToPool(_assignedIndex);
    13.         }
    14.     }
    15. }
     
    Necka_ likes this.
  11. Necka_

    Necka_

    Joined:
    Jan 22, 2018
    Posts:
    488
    Awesome!

    Thank you very much it's more than I wished for :)
     
    Stephen_O likes this.
  12. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    1.0.7 allows you to read the current speed by calling AITrafficCar.CurrentSpeed()

    I used that to write an example script that I'll include in the next update.

    You can attach this script to an AITrafficCar prefab, assign a simple audio sample to the AudioSource and the pitch will be dynamically adjusted based on the current speed.

    Code (CSharp):
    1.  
    2. namespace TurnTheGameOn.SimpleTrafficSystem
    3. {
    4.     using UnityEngine;
    5.  
    6.     [RequireComponent(typeof(AudioSource))]
    7.     public class EngineSound : MonoBehaviour
    8.     {
    9.         private AudioSource _audioSource;
    10.         private AITrafficCar _AITrafficCar;
    11.         private float topSpeed;
    12.         private float currentSpeed;
    13.         public float idlePitch = 0.2f;
    14.  
    15.         private void OnEnable()
    16.         {
    17.             _audioSource = GetComponent<AudioSource>();
    18.             _audioSource.playOnAwake = false;
    19.             _audioSource.spatialBlend = 0.7f;
    20.             _audioSource.loop = true;
    21.             _audioSource.Play();
    22.         }
    23.  
    24.         private void Start()
    25.         {
    26.             _AITrafficCar = GetComponent<AITrafficCar>();
    27.             topSpeed = _AITrafficCar.topSpeed;
    28.         }
    29.  
    30.         void Update()
    31.         {
    32.             currentSpeed = _AITrafficCar.CurrentSpeed();
    33.             _audioSource.pitch = currentSpeed <= 3 ? idlePitch : currentSpeed / topSpeed;
    34.         }
    35.     }
    36. }
    Feel free to email me for a Unity package with this script and an audio sample.
     
  13. Exi-G

    Exi-G

    Joined:
    Sep 5, 2012
    Posts:
    9
    Great i am gonna try it and if i need any help i will message you
     
  14. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Simple Traffic System is 50% OFF for the Spring Sale.
     
    hunter-baun likes this.
  15. mzylak

    mzylak

    Joined:
    Jan 14, 2016
    Posts:
    8
    Hi Stephen,

    Do you plan to automate the creation of waypoints, e.g. by using data from OpenStreetMap? Or maybe you could integrate with the Traffic AI option from the latest version of the most popular road add-on - EasyRoad3D?
     
  16. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Hello,

    I'm not sure, I might tinker with it when I get time, but it's not something I currently have planned. I know there's interest in this type of feature and I do think it would be awesome to press a button and have waypoint routes auto generated.

    I've had a fair number of people ask about Easy Roads, so it's in the back of my mind. I also really like what I see from CityGen3D using OSM data, I'm particularly looking forward to seeing it released on the store and giving it a spin.
     
  17. hunter-baun

    hunter-baun

    Joined:
    Feb 10, 2019
    Posts:
    5
    I'm having a hell of a time getting the right combination of these packages installed. At the moment, if you ask package manager to install these, you'll get:
    • Burst v1.2.3
    • Collections: preview.3 v0.7.1
    • Jobs: preview.3 v0.2.8
    • Mathematics: 1.1.0
    and that doesn't seem to be the right combination.

    I see that the 1.0.7 release was on March 29th, so I tried the most recent versions just prior to that, and I don't think that's correct either. Long story short, I get some compilation errors because of version mismatches. Which versions of these four packages are you working with?
     
    hopeful likes this.
  18. hunter-baun

    hunter-baun

    Joined:
    Feb 10, 2019
    Posts:
    5
    I managed to get what looks like a good combination of packages that install:
    • Unity 2019.3.8f1
    • Burst v1.2.2
    • Collections: preview.3 v0.6.0
    • Jobs: preview.3 v0.2.5
    • Mathematics: 1.1.0
    Is this correct? Things compile, but some other things happen when I open the demo scene:
    1. The AITrafficController starts throwing null reference exceptions in the scene view because it doesn't have an AI Traffic Debug reference. If I set that reference to the AI Traffic Debug object in the Assets/TurnTheGameOn/SimpleTrafficSystem/Data/ folder:
    2. Same issue, but because of a missing AI Traffic Pool reference. Setting this to the pool object in the same Data folder stops the exceptions in the scene view.
    3. When I run, I get pairs of exceptions on every frame:
      Code (CSharp):
      1. IndexOutOfRangeException: Index was outside the bounds of the array.
      2. TurnTheGameOn.SimpleTrafficSystem.AITrafficCarRandomMaterial.OnEnable () (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficCarRandomMaterial.cs:13)
      3. UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion)
      4. TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypointRoute:SpawnTrafficVehicles() (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficWaypointRoute.cs:56)
      5. TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypointRoute:Start() (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficWaypointRoute.cs:31)
      and
      Code (CSharp):
      1. IndexOutOfRangeException: Index was outside the bounds of the array.
      2. TurnTheGameOn.SimpleTrafficSystem.AITrafficController.RegisterCarAI (TurnTheGameOn.SimpleTrafficSystem.AITrafficCar carAI, TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypointRoute route) (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficController.cs:803)
      3. TurnTheGameOn.SimpleTrafficSystem.AITrafficCar.RegisterCar (TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypointRoute route) (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficCar.cs:45)
      4. TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypointRoute.SpawnTrafficVehicles () (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficWaypointRoute.cs:57)
      5. TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypointRoute.Start () (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficWaypointRoute.cs:31)
    4. And I get:
      Code (CSharp):
      1. NullReferenceException: Object reference not set to an instance of an object
      2. Unity.Collections.NativeArray`1[T].CheckElementWriteAccess (System.Int32 index) (at <1245d947a91b4a14b7c7e2c7335512b2>:0)
      3. Unity.Collections.NativeArray`1[T].set_Item (System.Int32 index, T value) (at <1245d947a91b4a14b7c7e2c7335512b2>:0)
      4. TurnTheGameOn.SimpleTrafficSystem.AITrafficController.Set_SpeedLimitArray (System.Int32 _index, System.Single _value) (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficController.cs:733)
      5. TurnTheGameOn.SimpleTrafficSystem.AITrafficCar.OnReachedWaypoint (TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypoint+AITrafficCarOnReachWaypointInfo onReachWaypointSettings) (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficCar.cs:54)
      6. UnityEngine.Component:SendMessage(String, Object, SendMessageOptions)
      7. TurnTheGameOn.SimpleTrafficSystem.AITrafficWaypoint:OnTriggerEnter(Collider) (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficWaypoint.cs:35)
      and
      Code (CSharp):
      1. NullReferenceException: Object reference not set to an instance of an object
      2. Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckWriteAndThrow (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <1245d947a91b4a14b7c7e2c7335512b2>:0)
      3. UnityEngine.Jobs.TransformAccessArray.GetTransformAccessArrayForSchedule () (at <1245d947a91b4a14b7c7e2c7335512b2>:0)
      4. UnityEngine.Jobs.IJobParallelForTransformExtensions.Schedule[T] (T jobData, UnityEngine.Jobs.TransformAccessArray transforms, Unity.Jobs.JobHandle dependsOn) (at <1245d947a91b4a14b7c7e2c7335512b2>:0)
      5. TurnTheGameOn.SimpleTrafficSystem.AITrafficController.FixedUpdate () (at Assets/TurnTheGameOn/SimpleTrafficSystem/Scripts/AITrafficController.cs:261)
      as well.
    I once thought that I had something working, where I created a route with waypoints, and added a car to the Spawn Traffic Vehicles array on the object, and can play the scene. A car is spawned, but does not start moving.

    So I'm having a little bit of a slow start, here, but I have high hopes! Any idea what I can do to resolve these exceptions and get things moving?
     
  19. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Hmm.. I see what's happening there when testing with 2019.3. You can use:

    Burst 1.2.3
    Collections 0.1.1
    Jobs 0.1.1
    Mathematics 1.1.0

    I'll look into why package manager is giving that problem, sounds like it was a Unity package dependency bug so might be like that until they fix it.
     
  20. hunter-baun

    hunter-baun

    Joined:
    Feb 10, 2019
    Posts:
    5
    Great! I'll give that a shot and see how it goes. Thanks for getting back to me so quickly!
     
    Stephen_O likes this.
  21. hunter-baun

    hunter-baun

    Joined:
    Feb 10, 2019
    Posts:
    5
    Yes, that did it! Burst 1.2.3, Collections 0.1.1, Jobs 0.1.1, and Mathematics 0.1.1 is the (or at least, a) good combination! I'm able to load the demo scene (and then update the materials in the three folders for URP), and run the demos successfully. Thank you for the guidance! I've put in some screen shots if that helps you out with docs or anyone else who happens to come across this thread.

    upload_2020-4-18_19-27-50.png

    A couple of other notes: Unity 2019 removed the "Scripting Runtime Version" project configuration option in favor of "API Compatibility Level", so the instructions could note that for clarity. Within the Project Settings -> Player pane, they're within the Other Settings section in the Configuration sub-section.

    upload_2020-4-18_19-19-50.png

    The documentation mentions:
    Standalone Builds
    To use the burst compiler in standalone builds, you need to install the Windows SDK and VC++ toolkit from the
    Visual Studio Installer.

    I have the Windows 10 SDK installed (both 10.0.17134.0 and 10.0.17763.0), and I have a handful of things labeled Visual C++ and VC++, though none of them are explicitly the "VC++ toolkit". Do I have the right Windows SDK, and which of these million items is the VC++ toolkit?

    upload_2020-4-18_19-15-29.png
     

    Attached Files:

    Stephen_O likes this.
  22. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    I appreciate your feedback, i had a hard time installing VS requirements my first time doing so.

    I'm hoping Unity package compatibility becomes a bigger priority for them (to me it's obvious that latest versions should support each other); I'm not sure why it's allowed to be like this. Also hoping that Unity and Microsoft automate visual studio install requirements to reduce ambiguity. My guess is that it will eventually be sorted out.

    This is what I've got installed on my system, I'll probably add this image to the docs. My system has been going for a few years, so I might have some extras that are not required.

    Unity Visual Studio Requirements.jpg
     
    hunter-baun likes this.
  23. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    I posted a free city package download (might be useful for some), it's a higher quality version of the city from the STS demo scenes. If you're just tinkering around it might be fun to have a more detailed scene to drop a player controller in and do some prototyping. I don't include with the STS package to keep file size down.

    Download Link: https://drive.google.com/file/d/1dpjCTkPlSfD_FhGgKMhulaT7rOrf7SuU/view?usp=sharing

     
    MK1_Dev and hunter-baun like this.
  24. hunter-baun

    hunter-baun

    Joined:
    Feb 10, 2019
    Posts:
    5
    I managed to get a standalone build without any changes from my VS installed components, so I guess I had the right stuff installed already! Thanks again for supporting us so well! It's been a very easy process between the help in the thread here and the excellent YouTube tutorial videos.
     
    Stephen_O likes this.
  25. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    You're very much welcome. Thank you too, for your questions and comments, they're helpful for me to understand pain points. My high hopes are that this new tech stack gets sorted out with future Unity releases, my fingers are crossed for Unity 2019.4 LTS release to resolve much of ambiguity with this setup process for the required packages.
     
    hunter-baun likes this.
  26. dpham

    dpham

    Joined:
    Jun 6, 2015
    Posts:
    6
    Hi Stephen,
    I just bought your Traffic System. Trying to adapt it into my project. Can you give me some pointers on how to implement a 2/3/4 way stop sign system (time tracker, first comes, first goes)? And how can I have a bus stops at a bus stop for few seconds before driving again?
    Thank you,
     
  27. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Hello,

    Stop signs and bus stops are not a feature that I have available (maybe in the future).

    The Waypoints have an OnReachWaypointEvent and StopDriving toggle. You can use these to build up custom logic.

    WaypointTriggers.jpg

    In general, you can do something like:
    - trigger stop driving
    - call a custom script event that handles required logic (timer, checks, etc)
    - have a reference to the AITrafficCar and call AITrafficCar.StartDriving()
     
    dpham likes this.
  28. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Really interesting tool! Bought it and I'm figuring things out. Let me ask you something - is there a way to enable/disable a route once it's running? For example, I want to turn off a route when an object covers part of my road so I don't want traffic using a certain route if that happens.
     
    Stephen_O likes this.
  29. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Yes, you can connect/disconnect route waypoint connections at runtime.

    When you use the route connector to connect route points, it populates a reference into the NewRoutePoint array on the AITrafficWaypoint script.

    New Route Points.jpg

    Removing the point from this array will remove the route connection.
     
  30. PixelTama

    PixelTama

    Joined:
    Sep 26, 2019
    Posts:
    2
    Hello Stephen,
    I am trying to scale the route/car prefabs to fit my map.
    I tried to change the AITrafficWaypointRoute's transform scale, cars prefab scale, also the detection sensor size, then the car moving strange.

    Would you please advise me on how to do this?
     
  31. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Thanks! So, is there also a way to turn off/on the whole traffic system programmatically as well? What about disabling an entire route? Is there an easier way to do this via code?
     
    Last edited: Apr 23, 2020
  32. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Hello,

    Changing the scale of physics objects is not recommended, it makes physics calculations unpredictable in Unity and is best if physics objects have a scale of 1,1,1. Honestly, I would recommend building your scene to real world scale for best result, the objects in this asset are built to real world scale.

    If you can't use the default scale, instead I would recommend to increase the size of colliders. There are 3 main colliders that you would want to look at adjusting (waypoint, car, wheels). Also, adjust the FrontSensorTransform, LeftSensorTransform, and RightSensorTransform positions as needed, they'll likely need to be moved out a bit to match the bounds of the model. To increase sensor size, you can adjust the AITrafficController Detection Sensor sizes and lengths.

    When you create your car prefab, scale the car's box collider size to match model scale. Adjust wheel collider radius to match wheel model scale.

    The waypoint prefab is located at Assets\TurnTheGameOn\SimpleTrafficSystem\Resources\AITrafficWaypoint adjust this prefab to have your spawned waypoints come in with a larger box collider size.
     
  33. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    I'll be working on setting up a proper scripting API when I get some more free time. For now here are some examples of how to do what you need.

    You can toggle all cars on/off using something like this:

    Code (CSharp):
    1. using UnityEngine;
    2. using TurnTheGameOn.SimpleTrafficSystem;
    3.  
    4. public class ExampleToggleCars : MonoBehaviour
    5. {
    6.     /// for this script to work you need to edit line 41 of AITrafficController script
    7.     /// the variable carAIList needs to be public
    8.  
    9.     [ContextMenu("DisableAllCars")]
    10.     public void DisableAllCars()
    11.     {
    12.         for (int i = 0; i < AITrafficController.Instance.carAIList.Count; i++)
    13.         {
    14.             AITrafficController.Instance.carAIList[i].StopDriving();
    15.             AITrafficController.Instance.carAIList[i].gameObject.SetActive(false);
    16.         }
    17.     }
    18.  
    19.     [ContextMenu("EnableAllCars")]
    20.     public void EnableAllCars()
    21.     {
    22.         for (int i = 0; i < AITrafficController.Instance.carAIList.Count; i++)
    23.         {
    24.             AITrafficController.Instance.carAIList[i].StartDriving();
    25.             AITrafficController.Instance.carAIList[i].gameObject.SetActive(true);
    26.         }
    27.     }
    28. }

    You can use a script like this and call the following function to dynamically update the array through code while also having the ability to re-enable it.

    Code (CSharp):
    1. UpdateAvailability(int _index, bool _active);
    Code (CSharp):
    1. using UnityEngine;
    2. using TurnTheGameOn.SimpleTrafficSystem;
    3. using System.Collections.Generic;
    4.  
    5. [RequireComponent(typeof (AITrafficWaypoint))]
    6. public class Example2 : MonoBehaviour
    7. {
    8.    /// for this script to work you need to attach it to the AITrafficWaypoint that has the connections you want to modify
    9.  
    10.     private AITrafficWaypoint _AITrafficWaypoint;           // waypoint reference
    11.     private List<bool> isActiveList = new List<bool>();     // is connection active control list
    12.     private AITrafficWaypoint[] initialConnectionsPoints;   // default reference to connection points
    13.  
    14.     private void Awake()
    15.     {
    16.         _AITrafficWaypoint = GetComponent<AITrafficWaypoint>();
    17.         /// reference array of new route points
    18.         initialConnectionsPoints = GetComponent<AITrafficWaypoint>().onReachWaypointSettings.newRoutePoints;
    19.         /// list of bools to keep track of what's active or disabled. all true/active by default
    20.         for (int i = 0; i < initialConnectionsPoints.Length; i++)
    21.         {
    22.             isActiveList.Add(true);
    23.         }
    24.     }
    25.  
    26.     /// toggle on/off any route index
    27.     public void UpdateAvailability(int _index, bool _isActive)
    28.     {
    29.         isActiveList[_index] = _isActive; // update isActiveList
    30.         List<AITrafficWaypoint> activePoints = new List<AITrafficWaypoint>(); // create a new connection points list to use
    31.         /// loop through initial connection points list
    32.         /// checking against active list to populate the updated active points list
    33.         for (int i = 0; i < initialConnectionsPoints.Length; i++)
    34.         {
    35.             if (isActiveList[i] == true)
    36.                 activePoints.Add(initialConnectionsPoints[i]);
    37.         }
    38.         // assign updated array
    39.         _AITrafficWaypoint.onReachWaypointSettings.newRoutePoints = activePoints.ToArray();
    40.     }
    41.  
    42.  
    43.     public int testIndex;
    44.     public bool testBool;
    45.     [ContextMenu("Test")]
    46.     public void Test()
    47.     {
    48.         UpdateAvailability(testIndex, testBool);
    49.     }
    50. }
     
  34. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Nice! I'll take a look at this. I need one more piece of help - when I create a set of routes, connect them via the route connector and then delete one, I get a whole bunch of "NullReferenceException: Object reference not set to an instance of an object" errors in my console. Do I need to delete the route connector when I delete a connected route? If so, how do I do this because I must be missing where to do this in the tool? Thanks!
     
  35. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Oh, I see now... It looks like I need to go into the waypoint that was connected and reduce the NewRoutePoints list to just 1 and then re-assign it to the next waypoint in the existing route... Unless you have a better way...
     
    Stephen_O likes this.
  36. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    You can't leave the NewRoutePoint array element empty after removing the reference, you need to adjust the array manually and resize it so all element fields are populated.
     
  37. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Yep, that's it.

    The next feature I'm working on is a tool for the STS window to be able to more easily perform this task.
     
  38. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Good stuff! So I'm using pooling and it's mostly doing the trick but there are a few route ending points where I need the car to be moved back into the pool when it hits that point. Since the active area is a circle, I have some areas where I need to dispose/repool the car when it hits the final waypoint in the route. What script would I assign to the waypoint "OnReachWayPointEvent" when the car gets to it?
     
  39. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    So, when I try to use DisableAllCars and then EnableAllCars, it just creates a giant pile of them at 0,0,0.
     
  40. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    You can call AITrafficController.Instance.MoveCarToPool() to send the car back to the pool.

    Example with OnTriggerEnter:

    Code (CSharp):
    1. namespace TurnTheGameOn.SimpleTrafficSystem
    2. {
    3.     /// Gets a reference to the AITrafficCar script to get the car's assignedIndex
    4.     /// then use that to call AITrafficController.MoveCarToPool(assignedIndex)
    5.  
    6.     /// Create a cube
    7.     /// Set BoxCollider IsTrigger to true
    8.     /// Attach this script
    9.     /// Then use it as a trigger zone that returns cars to the pool
    10.     using UnityEngine;
    11.  
    12.     public class ReturnToPoolOnTriggerEnter : MonoBehaviour
    13.     {
    14.         private void OnTriggerEnter(Collider other)
    15.         {
    16.             if (other.tag == "AITrafficCar")
    17.             {
    18.                 AITrafficCar _AITrafficCar = other.GetComponent<AITrafficCar>();
    19.                 int _assignedIndex = _AITrafficCar.assignedIndex;
    20.                 AITrafficController.Instance.MoveCarToPool(_assignedIndex);
    21.             }
    22.         }
    23.     }
    24. }
     
  41. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    If you're using pooling you can call AITrafficCar.MoveCarToPool() and let the pooling system handle enabling since it should already be doing that. Just call

    Code (CSharp):
    1. AITrafficController.Instance.carAIList[i].MoveCarToPool();
    instead of

    Code (CSharp):
    1. AITrafficController.Instance.carAIList[i].StopDriving();
    2. AITrafficController.Instance.carAIList[i].gameObject.SetActive(false);
     
  42. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Wouldn't they just keep respawning if I did that? Is there a way to pause or turn off or on the whole traffic system? For example, in my game, when I show my main menu if would like to remove all the active cars (or send them back to the pool I guess) and pause all spawning of cars in the scene. Also, when I reset a scene, I'd like to reset all spawned cars. Thanks for the help. There seem to be a lot of useful functions in your script - just need clarity on how to best use them! Thanks!
     
  43. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    So, just so I understand that UpdateAvailability function, say I have two AITrafficWaypointRoutes (call them #1 with 6 assigned waypoints and #2 with 7 assigned waypoints) and waypoint 6 from #1 connects to waypoint 1 from #2. Do I apply this function to waypoint 1 in AITrafficWaypointRoute #2 or do I apply this function to waypoint 6 in #1? What is the index value that I would apply to this function call in that situation? Thanks!
     
  44. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    You can simply toggle the usePooling off to stop processing pooling updates

    Code (CSharp):
    1. public void DisableAllCars()
    2.     {
    3.         AITrafficController.Instance.usePooling = false;
    4.         for (int i = 0; i < AITrafficController.Instance.carAIList.Count; i++)
    5.         {
    6.             AITrafficController.Instance.carAIList[i].MoveCarToPool();
    7.         }
    8.     }
    9.  
    10.     public void EnableAllCars()
    11.     {
    12.         AITrafficController.Instance.usePooling = true;
    13.     }
     
  45. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Add the script to the waypoint that has connections. And call the script to add/remove connections based on the default array elements.

    ToggleWaypoints.gif
     
  46. pistoleta

    pistoleta

    Joined:
    Sep 14, 2017
    Posts:
    539
    Would it be possible to add this system to a city tycoon game? where the roads and hence the waypoints would be constantly changed by the player?
    Thanks
     
  47. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    There's not a fully defined API, so without some custom coding it's not possible out-of-the-box without creating custom functions to handle the scenarios you'd create.
     
  48. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    So, I believe I have just about everything worked out, but it appears that when using Pooling, cars are spawning at my marked Spawn Points while inside the Active Zone, so they are "popping up" in front of my player. Did I do anything wrong or how can I fix this? I have a pretty big Spawn Zone (410) and Active Zone (400) and a pretty small Min Spawn Zone (23) so I'm not sure if that's causing issues. Thoughts?
     
  49. ZolnierGames

    ZolnierGames

    Joined:
    Feb 19, 2018
    Posts:
    88
    Also, some of the cars randomly turn too wide on certain turns and run into other oncoming cars. If that's the case, is there a way to check if a car has been stopped for too long and then push it back to the pool or something to help clear an accident in the scene?
     
  50. Stephen_O

    Stephen_O

    Joined:
    Jun 8, 2013
    Posts:
    1,510
    Did you disable your spawn point objects by mistake? These are required to be on, they become fully transparent on scene start and are still rendered by the camera to determine if the camera can see them or not using OnBecameInvisible/OnBecameVisible callbacks. If the camera can't see them cars are allowed to spawn.