How do I execute a method in an array simultaneously?

I have an array containing refs to robot components.

Robots[] robots

I attempted:

foreach(Robot r in robots)
     r.Run();

But what I did call Run() sequentially, not simultaneously. Now my question is, how do I execute Run() of robot component simultaneously?

They all run sequentially, but all in the same single frame, isn't it "simultaneously" enough?

@g8minhquan I see a slight delay, very slight delay between them. One start slightly later than the other.

2 Answers

2

You can’t do this without multithreading. Unity generally doesn’t let any multithread stuff touch any Unity functionality. So its impossible to do on a component.

You can simulate the code running simultaneously using a coroutine. Its not truly simultaneous. But its close enough for games.

"Unity generally doesn't let any multithread stuff touch any Unity functionality" ... I've never heard of it before. Thanks.

Its one way to guarantee thread safety. Only the main thread can touch Unity objects. No other threads means no thread safety issues.

Even coroutine will do things one after the other. But though they are done sequentially, they are all done on the same frame, so they will all start to run at the same time on the next frame.

But, say each robot has an each-frame coroutine for it's run. They still happen one at a time, doing the same thing as that loop. Even multi-threading is likely to have many robots completely finish before some others start.

fafase: not sure I get that last part. Say you have 10 while(true) { ... yield return null;} coroutines started, one for each robot. During subsequent frames, AFAIK, the Unity engine runs those coroutines one at a time.

You often don’t need to run things “at once.” Sequentially during a single frame is the same thing as all at once.

But, in cases where they affect each other “all at once,” you make an old and new version of the variables. Suppose the robots shoot and kill each other. If robot3 kills robot4, R4 should still fire back. And it gets even worse if robot3 can stun robot4, or damage the laser, etc… .

In the “kill” case, give all the robot and extra HPnew variable. Copy HP into HPnew for all robots. Then the robots blast away one at a time, damaging HPnew. Then, go through them all again, copying HPnew into HP and killing as needed.

In that particular case, you could be clever, use no extra variables, reduce HP, but just not kill them yet. After they all shoot, check for HP<=0 and kill as needed (obviously, that only works if you have some other way of marking them as dead.)

In general, having two copies of the data, “old” and “new” is the only solution. “All at once” reads from old, and changes new.