UnityNativeTool icon indicating copy to clipboard operation
UnityNativeTool copied to clipboard

DllManipulatorScript is not the last GameObject calling OnDestroy when scene is being destroyed.

Open zhmt opened this issue 5 years ago • 5 comments

The order of OnDestroy is not guaranteed, because the order of script excution doesn't work when calling OnDestroy.

class OneObj : MonoBehavior {
  void OnDestroy() { NativeApi.test(); }
}

The code above will raise IndexOutofBoundException randomly when stopping game in editor.

I dont know how to solve this problem.

I am using a stupid solution:

  1. invoke DllManipulatorScript.Reinitialize in Awake(){} when game started.
  2. manually invoke DllManipulatorScript.Reset via menu item before building cpp dll.

Is there better way?

zhmt avatar Jul 07 '20 05:07 zhmt

How about initializing dll when game started, and reset befor DllManipulatorScript's destructor is called?

If My NativeApi object hold an refercence of DllManipulatorScript , it will stop DllManipulatorScript being GCed before all my GameObjects are destoryed.

zhmt avatar Jul 07 '20 05:07 zhmt

Something like this:

class DllManipulatorScript {
  void Awake() { Reinitialize(); }
  ~DllManipulatorScript () { Reset(); }
}

class MyNative {
  object dllScriptRef;
  Awake() { dllScriptRef = GameObject.Find("DllManipulatorScript"); } 

  [DllImport]
  static extern void test();
}

zhmt avatar Jul 07 '20 05:07 zhmt

The problem is, at least when I last tested it, destructor is not called in editor when you just stop the game (or maybe only when it's the selected object in the scene, something of that nature). But if it turns out I'm wrong about that and it's gonna work fine, then yeah, I can change that.

mcpiroman avatar Jul 07 '20 07:07 mcpiroman

I tested, you are right. It is pretty tough to clean up at right time.

zhmt avatar Jul 07 '20 08:07 zhmt

Luckly, mannally dll unloading works fine.

zhmt avatar Jul 07 '20 08:07 zhmt