- Home /
Click button on html page to spawn an object into unity webplayer game
I'm a bit new to webplayer games so the interaction between the game and the html page is foreign to me. I have a webserver with an .obj object stored inside of it and my html page has a button.
When I click on the page button I want to spawn the furniture object into the game, the better option would be drag and dropping it into the webplayer game but I've read that it's not possible yet (Can someone confirm this?)
I want to know if it's possible to do so and what are the steps to go about doing this. I have already done something similar in unity, using directory urls to load .obj objects and in-game buttons to spawn them. Thanks for any advice!
Answer by Moshe Leibovich · Jul 06, 2016 at 02:25 PM
I am not absolutely sure what you meant but try this:
Add a singleton game object in the first scene (add DontDestroyOnLoad() if you have more than one scene). Give that object a method that gets a json string, that json will contain the required data for spawning the furniture. The method should parse the object and use it to spawn the furniture.
public class Communicator : MonoBehaviour
{
// Singeltone:
public static Communicator Instance;
// Memebrs:
public FurnitureInfo info;
void Awake()
{
if (Instance == null)
{
DontDestroyOnLoad(gameObject);
Instance = this;
}
else if (Instance != this)
{
Destroy(gameObject);
}
}
// Communication functionalities:
void Method(string infoJson)
{
info = JsonUtility.FromJson<FurnitureInfo>(infoJson);
// spawn the furniture however you want
}
}
On the webpage, create a js function that stringify the furniture data and uses SendMessage to send it to Unity (`SendMessage('gameObject', 'method', jsonString)`). run this function onclick of the button.
<button onclick="Spawn()">Click</button>
<script type='text/javascript'>
function Spawn() {
var info = {
/* add the info you need */
};
SendMessage('Communicator', 'Method', JSON.stringify(info));
}
</script>
Try spawning a constant furniture first and add the info later. Good Luck
Your answer
