Coinmonks

Coinmonks is a non-profit Crypto Educational Publication. Other Project — https://coincodecap.com/ & Email — gaurav@coincodecap.com

Unity Engine + MetaMask Wallet

Automagically connect your Unity game with Metamask Wallet (or any web3 wallet)

Leon Do
Coinmonks
Published in
4 min readOct 20, 2020

--

This project has the ChainSafe family! ChainSafe is incredibly excited to have Leon join us as Head of Gaming. His Unity SDK is now publicly available on ChainSafe’s Github here as the Web3.Unity library, where it will continue to get developed. Please check out our announcement article to learn more

Overview

In this article, you’ll be able to

  • Create a web3 WebGL template
  • Change Player Settings for web3 template
  • Connect your Unity game with MetaMask
  • Display MetaMask address in game.

Web3 WebGL Template

Create a new project

In your project under Assets, create a folder called WebGLTemplates

Next, download an existing WebGL template or use the template below. Check the Unity Manual for more information. Move the template into WebGLTemplates

https://github.com/underscoredLabs/web3-webgl-template

The end result should look like:

How does it work?

There are two changes

  1. In the index.html inside Web3Template, we’re importing a script

<script src="TemplateData/web3Connect.js"><script/>

2. Under TemplateData/web3Connect.js the script is

In short, this template says:

When the web page loads, connect to a web3 wallet.

Change Player Settings

In your Unity project, go to File > Build Settings...

Switch Platform to WebGL. Once done go to Player Settings...

Change WebGL Template to Web3Template that we added previously.

To test the MetaMask connection, Build and Run

There should be a prompt to connect

Display Address in Game

Now that it’s connected, let’s make use of the data. This example will display the web3 wallet address in game.

Right Click > UI > Button

Select the Button and Add Component. Create a new script. In this example, the script is called GetWalletAddress.cs

Paste the code in GetWalletAddress.cs

Create another file called web3.jslib For more info check out the Unity Docs.

Paste the code into web3.jslib The buffer and mallocs is also from the Unity Docs.

Now that the code is done, connect everything together. Drag the Button object to the On Click () handler and select the OnClick() function we created.

Drag the Text into the Button Text script.

To verify, Build and Run one more time.

Clicking the button should display an address

hard to see but it works

This will lay the foundation for more complex interactions such as fetching ERC-721 data to display in-game items.

Also, Read

--

--

Responses (6)