Okay approach for TrafficAI?

I’ve written my traffic logic this way:

  • Each car uses a waypoint script that reads from a path/waypoint container.
  • When the car reaches the end of the path(at an intersection or T-junction) it access a script in the waypoint container object, which contains an array with 3 new paths/waypointcontainers.
  • It uses a random number (between 1 and 3)to get a new waypoint container from this array.

It works great right now but, when I have “mapped” my city model this way, there will be lots of scripts “linked” together.
I’m worried that this is a bad way to do it(performance wise).

Thanks in advance:)

It sounds like a decent way to do it. It mainly depends how you are doing the car/node interaction. Doing tonnes of distance checks will be a huge overload, using Unity’s trigger system would be the best way. I.e. put a trigger on the intersection and in the car script it will have OnTriggerEnter which will call when it’s collider enters the trigger.

Id also recommend using Gizmos to draw lines between your intersection points so you can quickly make sure all your roads link up. They’re pretty easy to use, like if you have a list of nodes in each node, loop through them and use Gizmos.DrawLine to draw a line between them, maybe a little of the ground too so you can actually see it.

That’s a very basic system… your cars don’t go anywhere… they just drive around randomly. But if that’s all you need, it can be implemented very high performance.

The number of scripts doesn’t matter if you do it right, because you don’t need to do work per link, but only work per car.
So I could have a street network with one million nodes, but every car just knows the node it’s coming from and the node it’s going to and maybe some values it calculated once when it decided which node to target next, so it doesn’t need to calculate it every time, like: startTime, completeDrivingTime.
So every time it decided which node it needs to go next, it does:

distance = (target-origin).Magnitude;
completeDrivingTime = distance/drivingSpeed;
startTime = Time.time;

and then in each frame you just do this:

drivingTime = Time.time-startTime;
if (drivingTime>=completeDrivingTime) pickNewTargetAndTurnCarInDirection();
  Vector3 newpos = origin + (target-origin) * (drivingTime/completeDrivingTime);
  transform.position = newpos;

when it reached the destination, it picks the next node. It doesn’t matter how many nodes you have, besides from memory, because just the cars are the active parts.
There’s also no kind of Physics or the likes involved.

thanks for the answers so far.