CloudL
CloudL

Reputation: 211

How to use multithread in Unity3D for AI

I'm making a Unity3D chess game with AI in it.

My game screen stuck while AI is searching for a good move.

It will take about 5~30 seconds normally for AI to think.

I know that is because my CPU resource are dedicate to calculating the AI.

but I open task manager, I found that my game is only used 50% of CPU, probably because my computer is intel core 2, and have 2 threads.

so what I'm thinking is :

Is it possible for Unity(or C#) to do the AI calculate in one thread, and hold the gameplay in another thread ?

so the the player won't see the stuck screen while AI is calculating.

I've heard Delegate or Event, but I still don't know the relation between multithread.

Upvotes: 1

Views: 6564

Answers (2)

Qi Haoyan
Qi Haoyan

Reputation: 1

The Unity's API is not thread safe, you have to execute them in main thread. Well you can try this package on Asset Store will help you to using threading easier. http://u3d.as/wQg You can simply use only one line of code to start a thread and execute Unity API safely.

Upvotes: 0

Malcolm Smith
Malcolm Smith

Reputation: 3580

You should create a model that represents the state of your game using classes (that you write) that do not reference the Unity API. These classes should just represent your pieces, and their positions on the board. You can then pass this model to your AI code running in a separate thread, where it can evaluate it and modify it to represent the new game state. You then write some controller code that will map the model into calls to GameObjects (the view in Unity's case).

By splitting your model from your view in this way you get all kinds of advantages, see: MVC

You can use the .Net threads API to create your thread to do the AI processing and you will probably want to use a Latch to control synchronization between your game code and the AI thread. See: NET Framework System.Threading

Upvotes: 5

Related Questions