Is it safe to read a mesh assigned to a game object from another thread as long as the game object are not changed?
No, the Unity API isn't thread safe. You can read the mesh from the main thread and use the data in another thread, though. --Eric
Well ... I was not thinking of using of using the API itself , but passing reference to the mesh arrays. Did not think that the arrays moved around if noting changed. Or are they stored in a different format internal ? /Thomas
So your questions should be are Arrays thread safe, short answer no, long answer depends if you understand what thread safe actually means...from MSDN: Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. This implementation does not provide a synchronized (thread safe) wrapper for an Array; however, .NET Framework classes based on Array provide their own synchronized version of the collection using the SyncRoot property. Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. -------------- So in short for what you want to do, you will be fine, just make sure you use a flag to identify if the mesh is being modified by the child thread is probably the best way, as locking will lead to performance delays potentially...again depending on your exact architecture.
The arrays you get out of Mesh.triangles and Mesh.verticies are copies of the mesh data, not the mesh data itself. So you can manipulate these arrays to your hearts content on other threads. Following normal thread safe rules of course. The key is you have to get and set them on the main thread.
OK... Can't say I really understood all of that... I was only thinking of reading the mesh in the child thread. All feedback from the child thread to the game engine will be through a thread safe cue. What I was afraid of was that GC will make some sort of de-fragmentation of the memory, like Java seems to do. ( and ... NO, I don't really know what I'm doing ) Thanks to all of you !
Well, put simply: 1) Read the mesh data in the parent thread 2) Pass this to child thread for work 3) Work on it 4) Pass data back to main thread 5) Write mesh data back to mesh 6) Repeat Easy
I don't know that much about thread-safe stuff but if you have to loop through it and are worried about threads then just copy it to a local variable, do your work, then replace the original. I feel your pain though, i had a mess of dictionary sharing stuff to sort out recently.