blog games developers documentation portfolio gallery


DropOnUnity Prefab

You drag this prefab in your scene and select it to look at the properties. It has a component called DropOnUnityCtrl.
This component takes care of the drag and drop interface between the browser and Unity. It has properties that you can see in the Editor:
- Max file size in MB: This is the maximum size of the files the user can drop onto Unity (default 4)
- Plain Text File Extensions: An array of file extenstion string that always need to be treated as plain text files and result in sending a string to the targetObject instead of a byte array
- Drag drop JavaScript: The JavaScript text file that contains the code to be executed to enable Drag & drop. (Don't mess with this)
- Target object: You can drag any gameObject here. It will receive the dragged files
- Target object under cursor: If checked on, the gameObject (with collider) that is under the cursor when the user drops a file will receive it.

What happens is this:
Upon startup, the DropOnUnityCtrl orders the embedding webpage to execute some JavaScript code. This code turns the entire Unity object in the browser into a drag & drop target.
The user drags some file over to the webbrowser and moves the cursor over the Unity screen.
With every change in cursor position, the cursor position is taken, converted back to Unity coordinates and send from the browser to the DropOnUnityCtrl inside Unity.
The Controller checks which objects are under that new cursor position (if "Target object under cursor" is checked on) and broadcasts a message to that object.
When the user drop the file, it's contents is read by the JavaScript in the browser, converted into a base64 string, cut into chunks and those chunks are send to the DropOnUnityCtrl in Unity.
The DropOnUnityCtrl collects the chunks, translates the string back to bytes and instantiates a texture (if the file was a jpg or png) or converts the bytes into a string (if type = text/plain or file extension is in the array or plain text file extensions).
Finally the DropOnUnityCtrl broadcasts the texture, string or the raw bytes to the targetObject which an be the gameObject under the cursor and/or the manually set targetObject.

When the cursor leaves the unity screen without dropping the file, the drag operation is canceled by the JavaScript in the browser, passed on to the DropOnUnityCtrl and passed on the to the last know targetObject.

follow us