Running Web Player Functions from Javascript in HTML page

Hi guys,

we’re trying to get a function in javascript in an html page to effect the embedded unityweb, by running a script attached to an object within it.

In My Web player I simply have a Game Object called ‘MyObject’, and that has a script attached to it also named ‘MyObject’. We also have a camera looking at said object, but that is all.

So firstly, here is my simple script called ‘MyObject.js’ -

function MyFunction(param : String)
{
	Destroy(gameObject);
}

Note that ‘param’ is redundant, but i’ve tried with and without it, and as the manual has a reference passing in a string, i’ve just passed a blank string to it from the html page, which you can see below.

The manual stuff on this, here -

http://unity3d.com/support/documentation/Manual/Unity%20Web%20Player%20and%20browser%20communication.html

…is sketchy and sorry UT guys but its hardly newbie friendly - this line for example vexes me -

"Inside of the Unity web player content you need to have a script attached to the GameObject named MyObject, and that script needs to implement a function named MyFunction "

Are you saying the Object should be named MyObject? or the script? If the object then what should the script be named?

So anyway, here is my HTML page and its javascript attempt at calling the function on the object ‘MyObject’ check out the function and tag near the bottom named ‘SaySomethingToUnity’ , thats the bit im talkin about, the rest is the standard unity html, but I think you’ll need to see it too -

<html>
	
	<head>
		<title>Unity Web Player - index</title>
		<script language='VBScript'>
		function DetectUnityWebPlayerActiveX
			on error resume next
			dim tControl
			dim res
			res = 0
			set tControl = CreateObject("UnityWebPlayer.UnityWebPlayer.1")
			if IsObject(tControl) then
				res = 1
			end if
			DetectUnityWebPlayerActiveX = res
		end function
		</script>
		<script language="javascript1.1" type="text/javascript">
		
			function GetUnity () {
				if (navigator.appVersion.indexOf("MSIE") != -1  navigator.appVersion.toLowerCase().indexOf("win") != -1)
					return document.getElementById("UnityObject");
				else if (navigator.appVersion.toLowerCase().indexOf("safari") != -1)
					return document.getElementById("UnityObject");
				else
					return document.getElementById("UnityEmbed");
			}
			
			function DetectUnityWebPlayer () {
        		var tInstalled = false;
        		if (navigator.appVersion.indexOf("MSIE") != -1  navigator.appVersion.toLowerCase().indexOf("win") != -1) {
					tInstalled = DetectUnityWebPlayerActiveX();
        		}
        		else {
            		if (navigator.mimeTypes  navigator.mimeTypes["application/vnd.unity"]) {
                		if (navigator.mimeTypes["application/vnd.unity"].enabledPlugin  navigator.plugins  navigator.plugins["Unity Player"]) {
                 			tInstalled = true;	
            			}
         			}	
        		}
        		return tInstalled;	
    		}
    		
    		function GetInstallerPath () {
    			var tDownloadURL = "";
	   			var hasXpi = navigator.userAgent.toLowerCase().indexOf( "firefox" ) != -1;
	   			
    			// Use standalone installer
    			if (1)
    			{
					if (navigator.platform == "MacIntel")
						tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-i386.dmg";
					else if (navigator.platform == "MacPPC")
						tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-ppc.dmg";
					else if (navigator.platform.toLowerCase().indexOf("win") != -1)
						tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.exe";
					return tDownloadURL;
    			}
    			// Use XPI installer
				else
				{
					if (navigator.platform == "MacIntel")
						tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
					else if (navigator.platform == "MacPPC")
						tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
					else if (navigator.platform.toLowerCase().indexOf("win") != -1)
						tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerWin32.xpi";
					return tDownloadURL;
				}    			
    		}
			
			function AutomaticReload () {
				navigator.plugins.refresh();
				if (DetectUnityWebPlayer())
					window.location.reload();

				setTimeout('AutomaticReload()', 500)
			}
			
		</script>
	</head>

	<body>
		<center>
        

            
            
            
      <script language="javascript1.1" type="text/javaScript">
				
				if (DetectUnityWebPlayer()) {
					
					document.write('<object id="UnityObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="400" height="300"> \n');
					document.write('  <param name="src" value="index.unity3d" /> \n');
					document.write('  <embed id="UnityEmbed" src="index.unity3d" width="400" height="300" type="application/vnd.unity" pluginspage="http://www.unity3d.com/unity-web-player-2.x" /> \n');
					document.write('</object>');
				}
				else {
				
					var installerPath = GetInstallerPath();
					if (installerPath != "") {
						// Place a link to the right installer depending on the platform we are on. The iframe is very important! Our goals are:
						// 1. Don't have to popup new page
						// 2. This page still remains active, so our automatic reload script will refresh the page when the plugin is installed
						document.write('<div align="center" id="UnityPrompt"> \n');
						document.write('  [url=""][img]http://webplayer.unity3d.com/installation/getunity.png[/img][/url] \n');
						document.write('</div> \n');
						
						// By default disable ActiveX cab installation, because we can't make a nice Install Now button
//						if (navigator.appVersion.indexOf("MSIE") != -1  navigator.appVersion.toLowerCase().indexOf("win") != -1)
						if (0)
						{	
							document.write('<div id="InnerUnityPrompt"> 

Title</p>');
							document.write('

 Contents</p>');
							document.write("</div>");

							var innerUnityPrompt = document.getElementById("InnerUnityPrompt");
							
							var innerHtmlDoc =
								'<object id="UnityInstallerObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="320" height="50" codebase="http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.cab#version=2,0,0,0">\n' + 
							    '</object>';
							    
							innerUnityPrompt.innerHTML = innerHtmlDoc;
						}

						document.write('<iframe name="InstallerFrame" height="0" width="0" frameborder="0">\n');
					}
					else {
						document.write('<div align="center" id="UnityPrompt"> \n');
						document.write('  [url="javascript: window.open("][img]http://webplayer.unity3d.com/installation/getunity.png[/img][/url] \n');
						document.write('</div> \n');
					}
					
					AutomaticReload();
				}
			
			</script>
			<noscript>
				<object id="UnityObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="400" height="300" codebase="http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.cab#version=2,0,0,0">
					<param name="src" value="index.unity3d" />
					<embed id="UnityEmbed" src="index.unity3d" width="400" height="300" type="application/vnd.unity" pluginspage="http://www.unity3d.com/unity-web-player-2.x" />
					<noembed>
						<div align="center">
							This content requires the Unity Web Player


							[url="http://www.unity3d.com/unity-web-player-2.x"]Install the Unity Web Player today![/url]
						</div>
					</noembed>
				</object>
			</noscript>
	
   
<script type="text/javascript" language="javascript">
<!--
function SaySomethingToUnity()
{
    document.getElementById("UnityObject").SendMessage("MyObject", "MyFunction", "");
}
-->
</script>
		
			<h2>Unity Web Player - index</h2>
			

[url="#"]Delete Object![/url]</p>
	
		</center>
	</body>
	
</html>

Any help much appreciated, I know its a big ask but its fairly important I get a grasp of this.

Cheers in advance

Will

The object. But not necessarily “MyObject” literally; the object name simply needs to match the first parameter in SendMessage.

Doesn’t matter (just like using SendMessage in Unity). Again, the “MyFunction” doesn’t have to be called that, it just has to match the second parameter in SendMessage. The docs only use those names because that’s what the code example is using.

–Eric

So does that mean it’ll just search scripts until it finds the name of the function specified? Havent really used SendMessage before in Unity scripting.

With all of that said, can you hazard a guess as to why it still does nothing? Is the html written correctly do you know?

Thanks for your reply!

Yep.

Not really sure…seems OK, but then web stuff makes my head hurt.

–Eric

Yeah, i´ve got the same problem.
I want to change the guiText.text attribute to the "hello… "-param…

The exported webplayer index.html:

StringOutPutWeb();
					
function StringOutPutWeb(){				alert("StringOutPutWeb");			document.getElementById("UnityObject").SendMessage("Test_GameObject", "StringOutput", "Hello from a web page!");
}

The Test.js:

function StringOutput(param : String){
		var go = gameObject.Find("stringDisplay");
		if(go) {
			go.guiText.text = param;
			Debug.Log("yeah: " + go.guiText.text);
		}
}

I also tried the other way - calling functions from unity:"Application.ExternalCall( "SayHello", "The game says hello!" );"
This works.
But if i change the string and export it again, the old string will be displayed. I found out that exporting the scene as a standalone and then exporting it again as a webplayer - then it works an the edited textstring will be displayed.

So then i thought it should be the workaround that the browser can communicate with the webplayer - but that doesn´t work.

Does anybody know about the bug?

Thanks for your help!

I have this working fine with a Unity->Facebook App. Unity calls out to a JavaScript function, which in turn calls a function in Unity (passing in some info).

If you haven’t solved this when I get home I’ll take another look at your script.

Oh, that would be fantastic! Thanks Tempest!
I´ve attached my test-files if you wanna look at it.
(Couldn´t upload a zip/rar file.damn. “file emtpy”…
Therefore here are the single files.)

Thanks a lot!

yosh

151294–5510–$unitytest_1_106.html (6.47 KB)
151294–5511–$export_example_package_webcommunication_201.unitypackage (1.32 MB)

After hours of search - it works if i´m using the unity embed-id, not the unity object-id!

That will depend on the os/browser combo that you’re currently using. The default HTML file should mask this from you but if you look at the GetUnity function you’ll see how that’s done.