I need to communicate Unity WebAssemly with page in both directions.
This is how I execute Unity functions from page:
<script>
var gameInstance = UnityLoader.instantiate("gameContainer", "https://propper_url/Build/_Builds.json", {onProgress: UnityProgress});
function unityObjectFun(index)
{
gameInstance.SendMessage ("ObjectInstance", "objectFunctionName", index);
}
</script>
<a onclick="unityObjectFun(1)">invoke</a>
<div class="webgl-content">
<div id="gameContainer" myValue="need this to read from Unity"></div>
</div>
But how can I do in reverse. Is it possible to retrieve myValue from Unity.
Alternatively is it possible to notify page that Unity loaded scene and started playing it so I could send to it myValue?
To perform any JavaScript code on a page from the Unity WebAssembly there are two things required:
Create the Javascript code as plugin.
Import the code in Unity script.
The whole procedure is described in this guide: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html.
The plugin code must reside in Assets/Plugins/pluginname.jslib path (the extension is important) and have similar structure:
mergeInto(LibraryManager.library, {
Hello: function () {
window.alert("Hello, world!");
},
HelloReturn: function () {
return "Hello, world!";
}
}
To use it there is required import:
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
[DllImport("__Internal")]
private static extern void Hello();
[DllImport("__Internal")]
private static extern string HelloReturn();
void Start() {
Hello();
Debug.log(HelloReturn());
}
}
Related
I would like to display a html page that uses D3 in an SWT Browser.
If I load a URL like www.google.com it loads correctly and allows me to search etc. If I try loading a page that contains D3 I find that nothing gets displayed and no errors are output.
Example
public class D3BrowserExample {
public static void main(String args[]) {
Display display = new Display();
final Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
browser.addTitleListener(new TitleListener() {
#Override
public void changed(TitleEvent event) {
shell.setText(event.title);
}
});
browser.setBounds(0, 0, 1200, 900);
shell.pack();
shell.open();
browser.setJavascriptEnabled(true);
browser.setUrl("https://observablehq.com/#d3/force-directed-graph");
browser.addProgressListener(new ProgressListener() {
#Override
public void completed(ProgressEvent event) {
System.out.println("Page loaded");
}
#Override
public void changed(ProgressEvent event) {
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
Is it possible to execute D3 using an SWT Browser? Also how can I get the Javascript output to debug the issue?
Update
I've tried this on another Windows 10 PC with version 4.3 of SWT. The complete method is called for the progress listener but nothing displays.
Eclipse Bugzilla
https://bugs.eclipse.org/bugs/show_bug.cgi?id=568789
Two Scenes in Unity. Have to write a script for controlling unity scenes(2) in native iOS app, suppose 2 buttons in a native app when I click 1st button have to show scene1 and the 2nd button for scene2 like so. I found a script for android but need to write it for iOS.
Attached Script for Android,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.VR;
using System;
public class AnimatorScript : MonoBehaviour
{
public Animator animation;
AndroidJavaObject intent , currentActivity , extras;
bool hasExtra;
string arguments;
// Use this for initialization
void Start ()
{
try
{
AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
intent = currentActivity.Call<AndroidJavaObject>("getIntent");
hasExtra = intent.Call<bool> ("hasExtra", "test_val");
Debug.Log(hasExtra);
Debug.Log("start");
}
catch(Exception e)
{
Debug.Log(e);
}
}
public void loadScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
// Update is called once per frame
void Update ()
{
if (hasExtra)
{
Debug.Log("has extra");
extras = intent.Call<AndroidJavaObject>("getExtras");
arguments = extras.Call<string> ("getString", "test_val");
if(string.Equals(arguments,"scene1"))
{
animation.Play("dancing_warrior_sun-001");
}
if(string.Equals(arguments,"scene2"))
{
// animation.Play("seating_poses-001");
SceneManager.LoadScene(1);
}
else Debug.Log("No Animation Found");
Debug.Log(arguments);
}
else
{
Debug.Log("no extra");
}
}
}
There are two ways of Scene change/switch you can do,
1) In Unity place button by UI, and write script for scene change as follows,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuActions : MonoBehaviour {
public void MENU_ACTION_NextButton(string sceneName)
{
Application.LoadLevel(sceneName);
}
}
Drag this script to Main camera and click button, at the bottom of inspector click to add this main camera and name your scene name that have to be changed.Do this for scene 2 with same script and name the scene as well.
2) If you have button in your native app then write scripts as follows and try to write script for void update as well,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.SceneManagement;
public class SceneChanger : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//SceneManager.LoadScene(scene);
// try your script................
}
public void ChangeScene( string scene ) {
// Application.LoadLevel(scene);
SceneManager.LoadScene(scene);
}
}
Hope this will give you the concept..
Building an application with a native plugin for iOS
You can follow the official document, use UnitySendMessage from iOS to call the scene-control script at Unity.
I have a very basic application, that shows website content within the WPF app. Everything works fine, except TitleChangedEvent. Here is the code sample (XAML):
<Window xmlns:awe="http://schemas.awesomium.com/winfx" x:Class="ShopChat.Desktop.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:webControls="clr-namespace:System.Web.UI.WebControls;assembly=System.Web"
Title="{Binding ElementName=WebControl, Path=Title}" MinHeight="480" MinWidth="640">
<Grid>
<awe:WebControl x:Name="WebControl"/>
</Grid>
And this is main window code-behind:
public MainWindow()
{
InitializeComponent();
string url = #"http://shopchat.dev";
try
{
url = ConfigurationManager.AppSettings.Get("Url");
}
catch (Exception)
{
}
WebControl.Source = new Uri(url);
WebControl.TitleChanged += WebControl_OnTitleChanged;
this.WindowTitle = "Quickchat";
}
public string WindowTitle
{
get { return (string)GetValue(WindowTitleProperty); }
set { SetValue(WindowTitleProperty, value); }
}
// Using a DependencyProperty as the backing store for WindowTitle. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WindowTitleProperty =
DependencyProperty.Register("WindowTitle", typeof(string), typeof(MainWindow), new PropertyMetadata(null));
private void WebControl_OnTitleChanged(object sender, TitleChangedEventArgs e)
{
this.WindowTitle = e.Title;
}
I've also tried to bind to window title directly using Binding ElementName=WebControl. That didn't help me either.
JavaScript client code is very simple: it changes the document title on timer (setInterval).
What am I doing wrong?
try like this code
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyTitle = "Title";
}
Then you just need in the XAML
Title="{Binding MyTitle}"
Then you don't need the dependency property.
Then I would like to use this INotifyPropertyChanged with a standard property.
The issue was solved. TitleChanged event seemed to be insufficient. I've incorporated the usage of global js object to get the necessary behavior.
I have the viewPager component which is containing the several webviews with HTML content from remote server.
Is it simple HTML code without possibility to change the HTMl output on the server side.
I would like to ask, how can i catch the click(tap) event on the specified element with the given ID in Android?
ViewPager
private void initViewPager() {
pager = (ViewPager) findViewById(R.id.my_pager);
adapter = new FragmentStatePagerAdapter(
getSupportFragmentManager()
) {
#Override
public int getCount() {
// This makes sure getItem doesn't use a position
// that is out of bounds of our array of URLs
Logger.d(String.valueOf(mWelcomeController.loadedPagesToDisplay.size()));
return mWelcomeController.loadedPagesToDisplay.size();
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
Logger.d(mWelcomeController.loadedPagesToDisplay.toString());
return BrowserFragment.newInstance(
mWelcomeController.loadedPagesToDisplay.get(position)
);
}
};
//Let the pager know which adapter it is supposed to use
pager.setAdapter(adapter);
}
Because I cannot modify the HTML output on the server side (maybe inject some attributes into DOM on device ?) I cannot use something like that:
http://www.scriptscoop.com/t/21b53b896c9e/javascript-how-to-detect-button-click-in-webview-android.html
Detect click on HTML button through javascript in Android WebView.
I would like just something like this:
Find the given element in the HTML code
Update the HTML code (add
onclick event)
Catch this event in native code
For that you need to parse the html, a good html parser for Java (and therefor also Android) is Jsoup.
You can do something like:
// Connect to the web site
Document doc = Jsoup.connect(url).get();
Element button = doc.select("#buttonid");
button.html("new stuff here");
//parse back and put in webview
String finaloutput = doc.html();
1.
// setting
wv.addJavascriptInterface(new MyJsToAndroid(),"my");
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
2.
// JsCallBack
class MyJsToAndroid extends Object{
#JavascriptInterface
public void myClick(String idOrClass) {
Log.d(TAG, "myClick-> " + idOrClass);
}
}
3.
// JS--
public static String addMyClickCallBackJs() {
String js = "javascript:";
js += "function myClick(event){" +
"if(event.target.className == null){my.myClick(event.target.id)}" +
"else{my.myClick(event.target.className)}}";
js += "document.addEventListener(\"click\",myClick,true);";
return js;
}
4.
#Override
public void onPageFinished(WebView wv, String url) {
//...
wv.evaluateJavascript(addMyClickCallBackJs(),null);
//...
}
So, look at the 2 log.
I'm having trouble getting the SignalR demo Move Shape working on IIS 7.5. It works for me on my development PC under IIS express and Visual Studio 2013.
I'm currently copying the Move.html file and /scripts from the project to the wwwroot directory on the IIS 7.5 PC.
When I load the Move.html on the IIS PC from http:// localhost/Move.html, I get the following error in the javascript:
Uncaught TypeError: Cannot read property 'client' of undefined
which is the result of my previous line var moveShapeHub = $.connection.moveShapeHub, returning moveShapeHub as undefined.
Move.html:
<!DOCTYPE html>
<html>
<head>
<title>SignalR MoveShape Demo</title>
<style>
#shape {
width: 100px;
height: 100px;
background-color: #FF0000;
}
</style>
</head>
<body>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery-ui-1.10.3.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="/signalr/hubs"></script>
<script>
$(function () {
var moveShapeHub = $.connection.moveShapeHub,
$shape = $("#shape"),
// Send a maximum of 10 messages per second
// (mouse movements trigger a lot of messages)
messageFrequency = 10,
// Determine how often to send messages in
// time to abide by the messageFrequency
updateRate = 1000 / messageFrequency,
shapeModel = {
left: 0,
top: 0
},
moved = false;
moveShapeHub.client.updateShape = function (model) {
shapeModel = model;
// Gradually move the shape towards the new location (interpolate)
// The updateRate is used as the duration because by the time
// we get to the next location we want to be at the "last" location
// We also clear the animation queue so that we start a new
// animation and don't lag behind.
$shape.animate(shapeModel, { duration: updateRate, queue: false });
};
$.connection.hub.start().done(function () {
$shape.draggable({
drag: function () {
shapeModel = $shape.offset();
moved = true;
}
});
// Start the client side server update interval
setInterval(updateServerModel, updateRate);
});
function updateServerModel() {
// Only update server if we have a new movement
if (moved) {
moveShapeHub.server.updateModel(shapeModel);
moved = false;
}
}
});
</script>
<div id="shape" />
</body>
</html>
So it is able to find the /signalr/hubs and the other definitions but can't resolve the hub under IIS 7.5, but it works under IIS express.
Am I missing some setup under IIS 7.5?
What setup steps are needed under IIS 7.5?
Can this work under IIS 7.5?
Here is the hub code (straight from the demo):
using System;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace MoveShapeDemo
{
public class Broadcaster
{
private readonly static Lazy<Broadcaster> _instance =
new Lazy<Broadcaster>(() => new Broadcaster());
// We're going to broadcast to all clients a maximum of 25 times per second
private readonly TimeSpan BroadcastInterval =
TimeSpan.FromMilliseconds(40);
private readonly IHubContext _hubContext;
private Timer _broadcastLoop;
private ShapeModel _model;
private bool _modelUpdated;
public Broadcaster()
{
// Save our hub context so we can easily use it
// to send to its connected clients
_hubContext = GlobalHost.ConnectionManager.GetHubContext<MoveShapeHub>();
_model = new ShapeModel();
_modelUpdated = false;
// Start the broadcast loop
_broadcastLoop = new Timer(
BroadcastShape,
null,
BroadcastInterval,
BroadcastInterval);
}
public void BroadcastShape(object state)
{
// No need to send anything if our model hasn't changed
if (_modelUpdated)
{
// This is how we can access the Clients property
// in a static hub method or outside of the hub entirely
_hubContext.Clients.AllExcept(_model.LastUpdatedBy).updateShape(_model);
_modelUpdated = false;
}
}
public void UpdateShape(ShapeModel clientModel)
{
_model = clientModel;
_modelUpdated = true;
}
public static Broadcaster Instance
{
get
{
return _instance.Value;
}
}
}
public class MoveShapeHub : Hub
{
// Is set via the constructor on each creation
private Broadcaster _broadcaster;
public MoveShapeHub()
: this(Broadcaster.Instance)
{
}
public MoveShapeHub(Broadcaster broadcaster)
{
_broadcaster = broadcaster;
}
public void UpdateModel(ShapeModel clientModel)
{
clientModel.LastUpdatedBy = Context.ConnectionId;
// Update the shape model within our broadcaster
_broadcaster.UpdateShape(clientModel);
}
}
public class ShapeModel
{
// We declare Left and Top as lowercase with
// JsonProperty to sync the client and server models
[JsonProperty("left")]
public double Left { get; set; }
[JsonProperty("top")]
public double Top { get; set; }
// We don't want the client to get the "LastUpdatedBy" property
[JsonIgnore]
public string LastUpdatedBy { get; set; }
}
}
And here is the Startup.cs:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(MoveShapeDemo.Startup))]
namespace MoveShapeDemo
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}
Once you launch your site could you check to see if your hub proxy is getting loaded for /Signalr/hubs. Just hit your URL http:// localhost/SignalR/hubs.You should see the SignalR generated proxy (unless you have turned it off in your Global.asax which it does not look like it because you were able to hit it in IISExpress.
If you can bring up the hub proxy up then just change the following in your HTML, from
<script src="/signalr/hubs"></script>
to
<script src="http:/localhost/signalr/hubs"></script>
You can learn more about SignalR here - really good resource on everything that is signalR.
UPDATE:
You say that when running in visual studio and IIS expresss your Move.html works just fine. What else is in the Visual Studio solution or project as part of Move.html? You have C# code for your hub, have you deployed that? The use of /signalr/hubs suggests that Move.html and the hub are part of the same project, but in your original query you say that you just moved Move.html. You would have to publish the entire project and move that published version to the wwwroot folder. For publishing steps look here