قالب وردپرس درنا توس
Home / IOS Development / Unit and eatery: Why and how

Unit and eatery: Why and how



You know about Bitcoin, but do you know about its relative, Ethereum, and the potential it gives for gaming?

In this tutorial, you will learn why Ethereum is interesting to game developers and how it works from a game developer perspective.

By the end of this tutorial, you will know:

  • Why the Ethereum network may interfere with the gaming industry.
  • How the Ethereum network works at a high level and how to interact with it. 19659005] How a Unity game connects to the Ethereum network using the Nethereum library. You see a demonstration producer and get high scores from an Ethereum test network.
Note : This tutorial assumes that you are familiar with Unity and that you have an intermediate knowledge of C #. If you need any updates, check out our other Unity Tutorials. Prerequisites for Ethereum are unnecessary.

Time to get started!

Why Ethereum is Interesting

So why should you, as a game developer, care about Ethereum? To understand, consider game ecosystem . In other words, you must consider how to play games today and how your data is stored.

The game ecosystem today

  Ethereum and device: Why and how

When playing a game, you generate all types of data. These data include game progress, achievements, friend lists, items and many other things. Third parties like PlayStation Network, Xbox Live, Steam and many others store this data for you. These data are about you, but you do not own it. In most cases, the only way to access this data is on the terms set by third-party vendors. You must also trust, or hope that these same vendors will not get hacked or close to store, which happens more often than you might realize – especially when they are profitable.

The Game Ecosystem With Ethereum

  Ethereum and Unity: Why and How

The Ethereum Network, on the other hand, requires no third party to run or monitor it and it's incredibly safe. Also, by saving your game data in Ethereum, you can regain ownership of your data.

Ethereum, however, is not available. Without third parties paying for the costs, players must pay small fees to the Ethereum network to store their data. When you understand what Ethereum can offer, you agree that this is not such a bad deal.

Opportunities in the game ecosystem with eterum

  Ethereum and device: Why and how

Once you've played your game Data is in Ethereum and controlled by you, amazing opportunities arise. Each game, regardless of the platform, has access to your game data. Imagine an Xbox game that offers you a free space ship because you own an item in another game on PlayStation!

Even more exciting is because you own your goods, you can trade them for other objects across games and platforms. You can even sell your items for cash without the permission of any third party who controls your data (because there is no third party!). Imagine acting as a free spaceship with someone for an item they own in another game, on another platform.

Before you learn more about how Ethereum works, get to know the demonstration project.

Start Project

Download the startup project for this tutorial by using the link at the top or bottom of this page.

Open the project in Device, and open the scene named main located in Assets RW Scenes .

Note : You get some warnings about unassigned fields. For now you can ignore these; they will be gone at the end of the training.

Review the game object hierarchy:

 Ethereum and device: Why and how

  • Main Camera : Camera.
  • EventSystem : Handles events and input.
  • GameplayController : All gameplay logic.
  • UI Gameplay : User Interface for instructions.
  • HighScoreController : All logic related to high scores and Ethereum. The only editing you want to do in this tutorial is on the script attached to this GameObject.
  • UI HighScore : User Interface for Speaker Timer, scroll display and update button.
  • Arena : Gameplay objects.

Press the Play button.

You play as Ether the Elephant. Your goal is to avoid contact with the other animals. The amount of time you avoid them translates into your score.

Looking at the game interface, the rules are on the left; and on the right there is an empty high score table and a refresh button that currently does not do anything:

 screeen01.jpg

Throughout the rest of this tutorial, you will build up the UI elements and integrate played with an Ethereum test network that stores high scores. But first, you must understand how Ethereum works. You also need to get an Ethereum account.

How Ethereum Works

This section explains the Ethereum Network and intentionally avoids using technical terms.

Ethereum is young. It first came alive in 2015. The development stage is related to how the internet was in the early 1990s. Like the early internet, Ethereum has critics and challenges ahead of it.

Ethereum uses a network of computers connected over the internet. Each computer is a node . Simple programs run on these nodes, and they are usually written in a language called Solidity . Solidity is a bit like a subset of JavaScript or C #. Learning Solidity is beyond the scope of this tutorial.

The programs run on nodes inside a virtual machine. A virtual machine is like a stand-alone operating system that runs inside the main operating system of the node. This virtual machine is an EVM (Ethereum Virtual Machine). EVM helps prevent programs from hurting, for example, trying to dry a node's hard drive. EVM also provides a standard environment where the applications run. A knot can use Windows or Linux as the main operating system, and in both cases will offer the same standardized EVM:

 diagram04.jpg

The programs must be quite simple. They can talk to each other but should not move large amounts of data or make large amounts of treatment. Suitable candidates are things that register ownership of assets, votes, auctions or trade. A good rule of thumb is that a program can be about as sophisticated as a good programmable calculator.

The Ethereum network has a "heartbeat" where every 15 seconds or so all of the eligible programs run on the network and the results get saved.

Do you live in interesting times

Nothing happens for free of course. The execution of programs costs the person who wants to perform it a small fee. These fees are distributed among those who run the hubs. People who run nodes are called miners and earn fees in return to provide their computing power to the network. This is how the Ethereum network maintains itself.

The nodes on the network are all copies of each other. Each node contains same programs and same data as any other node. When a program runs, it runs on every hub under this heartbeat.

This makes the network remarkably resilient. If more nodes go offline, as long as somebody survived, the network can continue to run as usual. However, the main advantage of having each node is identical to trust.

The Trustless Network

Ethereum Network is not owned or operated by any individual or company. The software behind it is open source. Everyone can contribute to the source code and can download the software and set up a node.

Does this mean that you must trust all connected to the network to behave nicely and not tamper with your program code or program results? The answer is an emphatic "No!". The Ethereum network guarantees that your programs will run as you wrote them, without the possibility of manipulation. It also guarantees that program results are stored just as the program produced them. This is the killer function that Ethereum offers!

The details of how this trust works is where Ethereum becomes complex and is beyond this scope of study. But the basic idea is that it uses techniques from a branch of mathematics called cryptography, along with some smart algorithms. Some of the miners activity is to validate that the interaction with the network follows the Ethereum rules.

The amazing result is that there is a network of computers run by strangers without central authority, but you can trust the network to run your programs just as you encoded them without the possibility of manipulation!

Fees

The last piece to understand is fees. Easy reading of the network is free. Anything that causes a change to network applications or data costs a fee. This fee must be paid by the person who (or what) wants the change. Execution of a program costs a fee largely related to how many CPU cycles it requires and how much persistent data storage it changes.

The fee varies and depends on many factors, but at the time of this writing there are a few cents. Network fees given to miners are not paid in dollars. Fee is paid in a virtual currency (think "in-game" currency) called Ether . Ether is an integral part of the Ethereum network, and it is trading for dollars on many online exchanges.

Some Terminology

The above explanation avoided the use of technical terminology. When you read other material about Ethereum, you must know these technical terms.

  • Ethereum is a decentralized network because it has no central server that controls the network.
  • The method that the miners agree on what ouput of programs should be is the consensus mechanism .
  • The network stores all its data and applications in a block chain which is a special data structure like
  • Ether is part of a family of virtual currencies, called cryptocurrencies
  • .
  • The programs running on the network are smart contracts or dApps ] [Mapof"DistributedApplications")
  • The 15th second "Heartbeat" network is block time ].

Some theory! Time to get your hands dirty to add Nethereum the demo project library.

Installing Nethereum

Nethereum is an open source. NET library for Ethereum. It allows Unity to communicate with the Ethereum network.

Go to the Release page for the Nethereum GitHub project, and find the section 2.2.1 Unity3d . Download the file named Nethereum.Unity.zip

In your project, under Assets RW create a new folder named Plugins . Unzip the zip file and copy the contents of the newly created folder. Your project should now look like this:

 screen02.jpg

Now you will learn about accounts and transactions and you will get a try Ether.

Ethereum Accounts and Transactions

It's time to go deeper into the EVMs you looked back in Figure 4. In an EVM, many items are called accounts . Accounts can perform code, transfer Ether, maintain an internal data store and talk to each other. All accounts have an address which is a long hexadecimal number that uniquely identifies it. All accounts have a private key, which is also a long hexadecimal number. This private key is the password to access the current account.

By default, EVM is lifeless. Nothing happens unless someone sends a transaction . A transaction is like a message to an account for making something like transferring Ether or driving code. Once the message is received, the Ethereum network will be alive and will process this transaction. A long hexadecimal number identifies transactions uniquely.

Get an Ethereum Account

The easiest way to set up is to use a browser plugin named MetaMask . MetaMask works with Chrome, Firefox and Opera. It allows you to use the browser to access the Ethereum network. Unfortunately, there is no MetaMask release for Safari, so install Chrome if necessary. To install MetaMask, follow the steps on the MetaMask page.

First, select the browser extension:

 metainstall_screen01.jpg

Then add it to Chrome:

 metainstall_screen02.jpg

Next, confirm adds to Chrome:

 metainstall_screen03.jpg

A small fox icon appears in the browser toolbar; click on the icon to start MetaMask:

 metainstall_screen04.jpg

Reveals the ability to try the new MetaMask beta:

Accept Terms and Privacy Statements:

MetaMask uses the word DEN to mean your collection of Ethereum accounts. On the next screen, enter a new password and confirm it:

 metainstall_screen06.jpg

If you ever forget the password you just typed in, enter the seed sentence to recover your accounts. So if you can not keep your password safe, keep it so far the seed sentence for sure:

 metainstall_screen07.jpg

MetaMask is now ready for use, but it is live by default Main network . There are several test networks; In this tutorial, you use Rinkeby .

Click on the network name at the top:

 metainstall_screen08.jpg

Select the Rinkeby Network from the list:

 metainstall_screen09.jpg

MetaMask creates your first account for you and shows a balance of zero Ether. If you want to rename the account, hover your mouse over the account name and click edit :

 metainstall_screen10.jpg

Woo hoo! You have now MetaMask set up and an Ethereum account on the Rinkeby network. It's time to tell Unity this good news.

Copy your address from MetaMask by clicking the triple ellipse and select Copy address to clipboard :

 screen14a.jpg

In the main game you will find the game object HighScoreController. In the inspector, you must change Player Ethereum Account to the value you just copied from MetaMask.

 screen13a.jpg

Copy your private key (sometimes abbreviated to PK) from MetaMask by clicking on the triple elips and selecting Export Private Key :

 screen14b.jpg

MetaMask requires you to confirm your password. At this point, make sure you're on the Rinkeby Test Network, not the living network:

 screen15a.jpg

Then copy the private key:

 screen16.jpg ]

In the main game you will find GameObject HighScoreController. In the inspector, you must change Player Ethereum Account PK to the value you just copied from MetaMask.

 screen13b.jpg

Are you ready to get any Ether in your account?

Get Eternity in Your Ethereum Account

On Ethereum Network in Ethernet, you buy Ether with normal currency, often using online stores. Real-life testing software is not a good idea. To get free Ether into your test account, use a crane by following these steps:

  1. Copy your address from MetaMask by clicking the triple ellipse and select Copy Address to Clipboard just as you did over.

      screen08.jpg

  2. Tweet your address as in this example . You can also create a public Facebook post or a public Google Plus post.

      screen07.jpg

  3. Go to the Rinkeby crane and paste the link to the social media post you just created. Use the drop-down menu on the right side of the screen to select how much Ether you want to receive:

      screen05.jpg

After a few seconds, you'll see a confirmation:

 screen06.jpg

  1. Wait another 20 seconds or so, and then check your balance. You can check your balance in MetaMask; That's the amount of Ether (ETH) at the bottom left here:

      screen09.jpg

Reading an account balance

You are a solvents on the test network! Now you will see how Unity can read your balance. In the HighScoreController.cs file, add some extra using sentences at the top of the file:

  using System.Numerics;
uses Nethereum.Hex.HexTypes;
uses Nethereum.JsonRpc.UnityClient;

Replace the content of GetAccountBalanceCoroutine with this code:

  public IEnumerator GetAccountBalanceCoroutine ()
{
was getBalanceRequest = new EthGetBalanceUnityRequest (networkUrl); // 1
// Send balance request with player account and ask for balance in last block
yield return getBalanceRequest.SendRequest (playerEthereumAccount, Nethereum.RPC.Eth.DTOs.BlockParameter.CreateLatest ()); // 2

if (getBalanceRequest.Exception == null) // 3
{
were balance = getBalanceRequest.Result.Value; // 4
// Convert the balance from whey to ether and round to 8 decimal places for display
uiTextEtherBalance.text =
Nethereum.Util.UnitConversion.Convert.FromWei (Balance, 18) .ToString ("n8"); // 5
}
else
{
Debug.Log ("RW: Get Account Balance gave an exception:" + getBalanceRequest.Exception.Message);
}
}

The numbered notes in the above code show that it performs these steps:

  1. The script creates a new Nethereum request that passes in the network you are using.
  2. The script sends the request asynchronously and sends parameters that identify the player Ethereum account and say which block number you want the balance to. You want the latest, latest block.
  3. The script checks for an error in the conversation.
  4. The script draws the balance.
  5. The Ethereum network generally records Ether values ​​in a unit called Wei. It takes a billion billion Wei to make up an Ether, so you need to do a device conversion to get the Ether value to show.

Play the scene. Touch the Update button and wait a few seconds. The balance is shown just below the highscore table:

 screen10.jpg

Preparing to interact with High Score Contract

Now connect the game to a smart contract that records the top 40 results. The smart contract is written in the language Solidity.

Your first step is to create a C # wrapper around the Solidity contract to make it easy to interact with your C # code. Open the file HighScoreContractWrapper.cs in the code editor from the Assets RW Scripts

folder.

The first comment block is the copyright notice. The second comment block you should uncomment. Remove / * on line 30 and * / at the end of the file. Save the file. The end result will be like this:

  / *
* Copyright (c) 2018 Razeware LLC
...
* /
...
uses Nethereum.ABI.Encoders;
uses Nethereum.ABI.FunctionEncoding.Attributes;
...
[Parameter ("int256", "score", 2)]
public BigInteger Score {get; set; }
}

To get an idea of ​​how the contract works, browse through the contract source. You can see it stores a public selection of highscores and reveals a feature to receive a new high score named setTopScore . C # wrapper HighScoreContractWrapper.cs gives you a C # method CreateSetTopScoreTransactionInput that you can use to send a new high score to the smart contract.

Note : Understand the details behind the C # wrapper script and the smart contract is beyond the scope of this tutorial. See the links at the end of this tutorial to learn more.

Return to editing HighScoreController.cs again. In the global data section near the top of the file, add two new private variables:

  private HighScoreContractWrapper scoreContractService;
private HexBigInteger gasLimit = new HexBigInteger (4712388);

The first is a reference to C # wrapper; The other represents the most you want on a transaction. The term gas is not covered in this tutorial, but you can think of it as Ether.

At the end of Start add these lines:

  // Service for interaction with high score contract
scoreContractService = new HighScoreContractWrapper ();

Ethereum uses 256-bit integer, which needs a data type that is not available in Unity by default. Find the PrettifyScore method and change the signature to receive a BigInteger instead of an int :

  private string PrettifyScore (BigInteger score) ...

Save everything, switch to Unity and make sure the project compiles.

Next, you read the high score contract.

Get High Score from Ethereum

Return to your Code Editor. Find the method GetHighScoresCoroutine and replace the body with:

  public IEnumerator GetHighScoresCoroutine ()
{
was topScoreRequest = new EthCallUnityRequest (networkUrl); // 1
// Use the service to create a call entry
were countTopScoresCallInput = scoreContractService.CreateCountTopScoresCallInput ();
// Call request sends and provides for answers
yield return topScoreRequest.SendRequest (countTopScoresCallInput,
Nethereum.RPC.Eth.DTOs.BlockParameter.CreateLatest ()); // 2

// Decode the top score using the service
where scores = new list  ();
var count = scoreContractService.DecodeTopScoreCount (topScoreRequest.Result); // 3
Debug.Log ("RW: High Score Count:" + Score);
for (int i = 0; in < count; i++)
   {
      topScoreRequest = new EthCallUnityRequest(networkUrl);                          // 4
      var topScoreCallInput = scoreContractService.CreateTopScoresCallInput(i);
      yield return topScoreRequest.SendRequest(topScoreCallInput, 
        Nethereum.RPC.Eth.DTOs.BlockParameter.CreateLatest());
      scores.Add(scoreContractService.DecodeTopScoreDTO(topScoreRequest.Result));
   }

   var orderedScores = scores.OrderByDescending(x => x.Score) .ToList (); // 5
was topScores = "";
foreach (score in ordered scores)
{
string playerAddress = PrettifyAddress (score.Addr);
string playerSCore = PrettifyScore (score.Score);
topScores = topScores + playerSCore + ":" + playerAddress + Environment.NewLine;
}
uiTextHighScores.text = topScores;
}

The code performs these steps:

  1. The script creates a new Nethereum request.
  2. The script sends the request asynchronously and sends parameters identifying the smart contract method we want to call.
  3. The script checks to see how many top scorers it is.
  4. The script draws out details for each top score one at a time.
  5. The script sorts the score and makes each high score entry a nice format for display on screen.

Enter the scene, hit the update, wait a few seconds, and the list of high scores will appear:

 screen_refresh_01.jpg

Write high points to Ethereum

Return to your code editor, find the method SubmitHighScoreCoroutine and replace the body with:

  public IEnumerator SubmitHighScoreCoroutine ()
{
// Create the transaction input with coded values ​​for the function
were transactionInput = scoreContractService.CreateSetTopScoreTransactionInput (playerEthereumAccount, contractOwnerAddress, contractOwnerPK, liveTimeMilliSeconds, gasLimit);

// Create device request with the private key, URL, and user address
was transactionSignedRequest = new TransactionSignedUnityRequest (networkUrl, playerEthereumAccountPK, playerEthereumAccount); // 1

// Send request and wait
yield return transactionSignedRequest.SignAndSendTransaction (transaction input);

if (transactionSignedRequest.Exception == null)
{
// Get transaction receipt
Debug.Log ("RW: Top score delivers tx:" + transactionSignedRequest.Result);
}
else
{
Debug.Log ("RW: Error Sent Tx:" + TransactionSignedRequest.Exception.Message);
}
}

The above code is similar to what you've seen before. It prepares a request, sends it and interprets the results. The comment // 1 shows the noticeable difference where you use the player's private key and address to authorize the transmission of a transaction. This spends some of the player's Ether to pay miners.

Save and play the scene. Touch space to start playing and try to get a good score – at least enough to get into the top 40. When the elephant dies, wait a few seconds. Then press the update button and wait a few seconds. If your high score made it to the top 40, it should appear in the list:

 screen_refresh_03.jpg

You will also see that your Ether balance is reduced somewhat by the cost of the transaction to send into highscore.

Examination of Ethereum High Score Transactions

You can view the status of a transaction using a block explorer . When the game sends a high score, the console displays a message starting RW: Highscore sent tx: followed by a transaction number:

 screen_refresh_02.jpg

You can Create a URL with the pattern:
https://rinkeby.etherscan.io/tx/ [transaction ID here]

And enter it into a browser to see the transaction status like this.

] screen_refresh_05.jpg

Puh! It has been quite a trip! You have now completed the practical part. The following sections package this tutorial, starting with some opinions about the challenges Ethereum faces today.

Challenges for Eating Room in Games

Steve Wozniak, one of the founders of Apple, recently said that Eatery could be as influential as Apple in the long run. Remember that technology has begun!

The biggest challenges facing Ethereum in game development are those listed below.

  • resistance . You will understand that the surrounding people who currently store your game data may be reluctant to see other services being involved.
  • Scaling . Ethereum can handle about 10 transactions per second. This must go higher to allow widespread adoption. Casper aims to introduce proof-of-stake to the Ethereum network. This can create a reality that helps with the scaling problem.
  • [charges. At the time of writing, fees are around a few cents. This is too expensive for some uses.
  • Public Error . Using smart contracts on a public block means that the bugs are visible to everyone, but you can not fix them quickly.

Note : Remember, nobody works as the Ethereum Network Police. Ethereum itself is certain, but human error occurs. If you send incorrect ether on the live network by mistake, it is gone forever.

Where to go from here?

Download the completed project from the link below. The art of the project is by Kenny.nl.

Learn more about eatery and solidarity

When you have finished playing the demo project, you may want to explore deeper into Ethereum.

A good place to start learning about Ethereum and Solidity is the official site. An author and speaker I recommend is Andreas Antonopoulos who has a book about Ethereum later in 2018.

Learn more about Nethereum

The Nethereum project is open source. Thanks to Juan Blanco whose advice and demo code inspired the samples here. You can join Gitter and chat with others about the project.

Get Inspired

Take a look at what others have already done with Games and Ethereum for more inspiration:

Games

  • ] CryptoKitties is like a short trading game where you collect and breed digital cats. This game got a lot of pressure because it was at one time so popular it affected the performance of the entire Ethereum network.
  • CryptoCuddles is a short game game built on top of the CryptoKitties game. You can fight with kittens that you have bred in CryptoKitties. This is because CryptoKitties smart contracts are open to any other developer to use. Very cool!
  • ChainMonsters are very interesting, it's a bit like Pokémon on Ethereum with smart contracts that are visible.

Services

  • uPort is a project to deal with people's ethereal identities. uPort will make it easier to use the network without having to enter a long private key.
  • GamerToken wants to be a regular currency in the game as any game can use.
  • Ownage wants to be a commodity platform in the game.

We hope you have had the training, if you have questions or comments, please join the discussion below.




Source link