Ethereum Unity3D Boilerplate Questions

@dgoodrich Hi Dave, First of all thanks for all your hard work! I am working on a WebGL game and I am trying to make a connection between MetaMask web wallet and Unity. On the javascript side i use the following code to get a sessionToken:

  MoralisAuthenticate: async function () {
    let user = Moralis.User.current();
    if (!user) {
      user = await Moralis.authenticate({ signingMessage: "Authenticate" });
    } else {
      // Refresh local data
      user = await Moralis.User.current().fetch();
    }

    if ('attributes' in user && 'sessionToken' in user.attributes) {
      unityInstance.SendMessage('ConnectWallet', 'setUserSession', user.attributes.sessionToken.toString());
    } else {
      console.log("sessionToken not found!");
    }
  }

And on the Unity side I use this code to try and get the user:

    public async void setUserSession(string sessionToken)
    {
        MoralisUser user = await MoralisInterface.GetClient().UserFromSession(sessionToken);
    }

The javascript side is working perfectly but the UserFromSession gives me trouble. When i press my connect button the first time I get the following error:
image

And when I press it again I get the this error:

If I look at the failed 400 network request I see that the x-parse-session-token header is missing. If I test this request with cURL and add this header i get a response. Is my approach wrong or is there a bug somewhere in the C# SDK?

1 Like

The x-parse-session-token-header is set from the sessionToken value you pass in. Here is the code:

            if (!String.IsNullOrEmpty(sessionToken))
            {
                Headers.Add(new KeyValuePair<string, string>("X-Parse-Session-Token", sessionToken));
            }

Are you sure the setUserSession method is receiving the sessionToken?

Yeah I double checked that and even hard coded the sessionToken but I get the same error. I did some more debugging and I think I found the problem.

In the UniversalWebClient.cs files there is a allowHeaders list and it seems “x-parse-session-token” is missing:

        static List<string> allowedHeaders { get; } = new List<string>
        {
            "x-parse-application-id",
            "x-parse-installation-id",
            "content-type"
        };
1 Like

Any update on calling Cloud Functions on the same Moralis server from multiple devices?

1 Like

I’m new here plz guide me how to integrate moralis with unity3d and send tokens to different wallet address

@dgoodrich HOW TO SEND ETH/BNB ERC20/BEP20 TOKENS IN-GAME UNITY3D ? The code on documentation isn’t working in unity plz guide me I’m new here.

Did you get the demo running before making any modifications?

Is there a specific error you are seeing?

I am sorry that something here is not clear - any specific method you need help with?

  1. Take a look at the AwardableController.cs file for a demo for calling Nethereum methods.
  2. Take a look through the Nethereum documentation. to learn how to use Nethereum to transfer tokens.

You should be able to use the MoralisInterface.SendEvmTransactionAsync or MoralisInterface.SendTransactionAndWaitForReceiptAsync functions to perform the transfer. However Nethereum offers several overrides to these that are not exposed in the MoralisInterface. If you need one of these variants you can take a look at the MoralisInterface code to see how the two methods mentioned above are set up and called.

Regards,

David

Sorry it took a bit. I was still not able to reproduce the error you are reporting.

Originally I thought you meant you could not login from different devices at the same time. So I just set up a cloud function and an update so that the cloud function was called every 500 frames. I deployed to Android and desktop and ran each at the same time. Both returned the cloud function results with no errors.

Regards,

David

Can you provide the source code for this so that I can replicate it?

On those lines, I feel that you might be in a better place if you can check our source code as well.

Is Moralis also works on BEP-20 Tokens?

Yes, if you set up the necessary chain parameters to those of BSC.

1 Like

Ah, did you turn on user validation?

1 Like

Were you able to implement the API call to connect with the browser’s Metamask plugin via WebGL? Could you share with us how you did it?

WebGL + Agora.IO + Photon PUN2 with erros on build here:

First erro is because WebSockets is duplicated (both use WebSockets, Photon and Ethereum Boilerplate). Removing one, the error is this:

Failed running command "C:/Program Files/Unity/Editor/2020.3.26f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Editor/2020.3.26f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"C:\Documents\Unity HDRP\Metaverse Caio\Assets\..\Temp\emcc_arguments.resp" (process exit code: 1)
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()

Failed process stderr log:
warning: unexpected number of arguments 1 in call to '__cxa_pure_virtual', should be 0
warning: unexpected number of arguments 2 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0
warning: unexpected number of arguments 4 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0
warning: unexpected number of arguments 5 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0
warning: unexpected number of arguments 4 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0
warning: unexpected number of arguments 2 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0
warning: unexpected number of arguments 3 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0
error: unresolved symbol: WebSocketAddSubProtocol
error: unresolved symbol: WebSocketAllocate
error: unresolved symbol: WebSocketClose
error: unresolved symbol: WebSocketConnect
error: unresolved symbol: WebSocketFree
error: unresolved symbol: WebSocketGetState
error: unresolved symbol: WebSocketSend
error: unresolved symbol: WebSocketSendText
error: unresolved symbol: WebSocketSetOnClose
error: unresolved symbol: WebSocketSetOnError
error: unresolved symbol: WebSocketSetOnMessage
error: unresolved symbol: WebSocketSetOnOpen
Aborting compilation due to previous errors | undefined
Traceback (most recent call last):
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 3063, in <module>
    sys.exit(run())
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 1780, in run
    final = shared.Building.emscripten(final, append_ext=False, extra_args=extra_args)
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\shared.py", line 2274, in emscripten
    emscripten._main(cmdline)
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 2233, in _main
    return temp_files.run_and_clean(lambda: main(
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\tempfiles.py", line 93, in run_and_clean
    return func()
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 2238, in <lambda>
    DEBUG=DEBUG,
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 2164, in main
    temp_files=temp_files, DEBUG=DEBUG)
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 86, in emscript
    glue, forwarded_data = compiler_glue(metadata, libraries, compiler_engine, temp_files, DEBUG)
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 218, in compiler_glue
    glue, forwarded_data = compile_settings(compiler_engine, libraries, temp_files)
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 541, in compile_settings
    cwd=path_from_root('src'), error_limit=300)
  File "C:\Program Files\Unity\Editor\2020.3.26f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\jsrun.py", line 132, in run_js
    raise Exception('Expected the command ' + str(command) + ' to finish with return code ' + str(assert_returncode) + ', but it returned with code ' + str(proc.returncode) + ' instead! Output: ' + str(ret)[:error_limit])
Exception: Expected the command ['C:/Program Files/Unity/Editor/2020.3.26f1/Editor/Data\\Tools\\nodejs\\node.exe', '--stack_size=8192', '--max-old-space-size=4096', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten\\src\\compiler.js', 'C:\\Users\\caioc\\AppData\\Local\\Temp\\tmpj8vakl.txt', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Audio.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\case_1174367_workaround.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\case_1179945_workaround.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\case_1187965_workaround.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\case_1208971_workaround.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Cursor.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Eval.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\FileSystem.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Logging.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Profiler.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\SystemInfo.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\UnetWebSocket.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Video.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\WebCam.js', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\WebRequest.js', 'C:\\Documents\\Unity HDRP\\Metaverse Caio\\Assets\\Photon\\PhotonLibs\\WebSocket\\WebSocket.jslib', 'C:\\Program Files\\Unity\\Editor\\2020.3.26f1\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten\\src\\library_pthread_stub.js'] to finish with return code 0, but it returned with code 1 instead! Output: // The Module object: Our interface to the outside world. We import
// and export values on it. There are various ways Module can be used:
// 1. Not defined. We create it here
// 2. A function parameter, function(Module) { ..generated code.. }
// 3. pre-run appended it, var Module = {}; ..generated
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()
Exception: Failed building WebGL Player.
UnityEditor.WebGL.ProgramUtils.StartProgramChecked (System.Diagnostics.ProcessStartInfo p) (at /Users/bokken/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/ProgramUtils.cs:52)
UnityEditor.WebGL.WebGlBuildPostprocessor.EmscriptenLink (UnityEditor.Modules.BuildPostProcessArgs args, System.Boolean wasmBuild, System.String sourceFiles, System.String sourceFilesHash) (at /Users/bokken/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:423)
UnityEditor.WebGL.WebGlBuildPostprocessor.LinkBuild (UnityEditor.Modules.BuildPostProcessArgs args) (at /Users/bokken/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:464)
UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args) (at /Users/bokken/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:914)
UnityEditor.Modules.DefaultBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <55729f52d042492e9efc384182ae2feb>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <55729f52d042492e9efc384182ae2feb>:0)
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler()
1 Like

Does it work if you run Unity and Moralis only?
Try removing other libraries you mention

I think it will be difficult for us to debug the other tools and libraries you use

But if you have an issue that is Moralis specific - we can help :raised_hands:

3 Likes

Removing Photon PUN2 from Unity, work as well. But I need this package, because my game is Multiplayer
Has a way to make it compatible with Photon PUN2?

Edit: this issue is only on WebGL platform, in Windows in my other project with Photon Fusion, Moralis + Photon Fusion work as well. But there is Windows x64 game platform. The issue is only in WebGL

1 Like

WebGL and WebSockets get error with all multiplayer platform, like Colyseus, Photon, etc.

Here the error:

Plugin 'WebSocket.jslib' is used from several locations:
 Assets/MoralisWeb3ApiSdk/WalletConnectSharp.Unity/Network/Client/WebSocket.jslib would be copied to <PluginPath>/WebSocket.jslib
 Assets/Photon/PhotonLibs/WebSocket/WebSocket.jslib would be copied to <PluginPath>/WebSocket.jslib
Please fix plugin settings and try again.

UnityEditor.Modules.DefaultPluginImporterExtension:CheckFileCollisions (string)
UnityEditorInternal.PluginsHelper:CheckFileCollisions (UnityEditor.BuildTarget)
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()
1 Like

I got the solution myself.

The error was in:

Assets\MoralisWeb3ApiSdk\WalletConnectSharp.Unity\Network\Client\WebSockets.jslib

Solution:

Modify the name to WebSockets2.jslib
and change the following code snippet in WebSockets2.jslib:

Code snippet:

		 * Instance structure:
		 * {
		 * 	url: string,
		 * 	ws: WebSocket
		 * }

To:

		 * Instance structure:
		 * {
		 * 	url: string,
		 * 	ws: WebSocket2
		 * }

Now you able to use Moralis with Photon PUN/Colyseus or another Multiplayer service who use WebSockets too with Unity <3

5 Likes

Sound like you are building something very cool. I hope you will share / demo it for us sometime.

This is the next feature I will implement. I hope to have the WebGL / Metamask interface ready by the end of the month (if not sooner).

Regards,

David

2 Likes

Just following up - Is this working for you now?

1 Like