<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexandre Bruffa on Medium]]></title>
        <description><![CDATA[Stories by Alexandre Bruffa on Medium]]></description>
        <link>https://medium.com/@alexandre.bruffa?source=rss-81d3bee7a7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NBe9HXQUKfYcVoDcuKgpoA.png</url>
            <title>Stories by Alexandre Bruffa on Medium</title>
            <link>https://medium.com/@alexandre.bruffa?source=rss-81d3bee7a7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:35:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexandre.bruffa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reading JWTs in Unity]]></title>
            <link>https://awstip.com/reading-jwts-in-unity-32e894f1fe2d?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/32e894f1fe2d</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 14:14:16 GMT</pubDate>
            <atom:updated>2024-11-07T06:26:22.044Z</atom:updated>
            <content:encoded><![CDATA[<h4>Performing Base64 Decoding on Cognito Tokens in Unity.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9HODKcT9p-dc2EzzN8BvA.png" /></figure><p><em>This article was originally published on my </em><a href="https://alexandrebruffa.com/reading-jwts-in-unity/"><em>website</em></a><em>.</em></p><p>You may prefer watching a video instead of reading, here it is!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWDvvlduwJg0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWDvvlduwJg0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWDvvlduwJg0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d02c5ef3b6abd23117446282113e862/href">https://medium.com/media/6d02c5ef3b6abd23117446282113e862/href</a></iframe><p>Weeks ago, I published <a href="https://www.udemy.com/course/unity3d-amazon-cognito/?referralCode=502423153E5F6EE623D4">a course on Udemy</a> explaining how <strong>Unity</strong> and <strong>Amazon Cognito</strong> can work together. In one of the lectures of the course, I mentioned that reading Cognito tokens in Unity brings some advantages: since important information is contained in those tokens, we can get rid of a Cognito API call to retrieve user information. The counterpart would be that it could be somehow challenging to decode JWTs in Unity. But we love challenges so let’s do it!</p><p>If you want to know how to use Amazon Cognito as a user directory or if you want to connect Unity with Amazon services such as <strong>Lambda</strong>, <strong>S3</strong>, or <strong>DynamoDB</strong>, I recommend you check <a href="https://www.udemy.com/course/unity3d-amazon-cognito/?referralCode=502423153E5F6EE623D4">my new course on Udemy</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOlz1_4l6c9EKtwomt3uwA.png" /><figcaption>My <a href="https://www.udemy.com/course/unity3d-amazon-cognito/?referralCode=502423153E5F6EE623D4">new course</a> on Udemy</figcaption></figure><p>That said, let’s start!</p><p>Cognito works with <strong>JSON web tokens</strong> (or JWTs). After logging in with a Cognito user, Cognito sends 3 JSON web tokens to the Unity client: access, ID and refresh tokens. Those tokens contain important information that can be extracted and used by the Unity client. In this post, we will focus on the <strong>ID token</strong>, since it contains interesting information about the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1o-gjTKqNWXnLqGQhxRhhA.png" /><figcaption>Cognito tokens</figcaption></figure><p>In order to create those tokens, Cognito first converts the original JSON data into binary data and then into text data thanks to the base64 algorithm. Just a side comment about a common mistake: JSON web tokens are <strong>NOT encrypted</strong>; they are <strong>encoded</strong>, meaning that they can be easily decoded on the client side. Plenty of online tools such as <a href="https://jwt.io/">jwt.io</a> offer JWT decoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_abXVxMnfzHfnGuN2y9AuQ.png" /><figcaption>JWT encoding process</figcaption></figure><p>To <strong>decode</strong> JSON web tokens in Unity, we are going to do the reverse process: convert the text data into binary data and then into a string thanks to UTF-8. We could also use ASCII but I recommend using UTF-8 to handle a large range of characters: Russian, Chinese, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ao_YbPLih5c4DFxUP8IrtA.png" /><figcaption>JWT decoding process</figcaption></figure><p>Now, let’s talk about the <strong>padding characters</strong>. When it comes to base64 decoding, the length of the data text must be a multiple of four. I won’t enter into details because that’s something complex with octets and sextets but anyway! If the length of the data text is not a multiple of four, we must add the necessary padding characters at the end. The padding character in base64 is always the equals sign (=).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct6oTNfipv3-Hf-XGBYapg.png" /><figcaption>Base64 padding characters</figcaption></figure><p>And here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aadf3cbbbc831bc7303a38beceeea5ed/href">https://medium.com/media/aadf3cbbbc831bc7303a38beceeea5ed/href</a></iframe><p>Notes:</p><ul><li>JWTs consist of three parts separated by dots: <strong>header</strong>, <strong>payload</strong>, and <strong>signature</strong>. So, we will split the ID token thanks to the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.split">Split function</a> (9) and we ensure that it contains three parts (11). Otherwise, this is not a valid token.</li><li>The information we need is contained in the <strong>payload</strong>, so we isolate it (13).</li><li>We calculate how many padding characters we will add at the end of the payload. So first, we calculate the <strong>remainder</strong> of the division by <strong>four</strong> using the <strong>modulo</strong> operator (14).</li><li>If the remainder is equal to zero, we can decode the text. Otherwise, we calculate how many characters are missing (18) and we add the <strong>padding characters</strong> at the end of the payload (19).</li><li>We convert the data into <strong>binary</strong> (22) thanks to the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.convert.frombase64string">FromBase64String</a> function and into <strong>string</strong> thanks to the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getstring">GetString</a> function (23).</li><li>The resulting string is a JSON string, so we convert it into an object (25) and we show it on screen (26).</li></ul><p>That’s it! This post was a bit more technical than other posts of mine but you can now decode Cognito tokens and more generally JSON web tokens in Unity.</p><p>Thanks for reading until the end! If you have any feedback or suggestions, please reach out to me on my social networks:</p><p>🌳 <a href="https://linktr.ee/alexandre.bruffa">Alexandre Bruffa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32e894f1fe2d" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/reading-jwts-in-unity-32e894f1fe2d">Reading JWTs in Unity</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity3D + Amazon Cognito: My New Course on Udemy!]]></title>
            <link>https://medium.com/@alexandre.bruffa/unity3d-amazon-cognito-my-new-course-on-udemy-ef65db7bb7e7?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef65db7bb7e7</guid>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[unity3d]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 17:14:39 GMT</pubDate>
            <atom:updated>2024-09-19T17:14:39.759Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build your user directory and access Lambda, S3 and DynamoDB from Unity!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXHtjaLfja81yy5wc1jIYw.png" /><figcaption>My new course on Udemy</figcaption></figure><p><em>This article was originally published on my </em><a href="https://alexandrebruffa.com/unity3d-amazon-cognito-my-new-course-on-udemy/"><em>website</em></a><em>.</em></p><p>I’m very excited to share with you that I have published my first course on Udemy!</p><p>➡️ Check it out: <a href="https://www.udemy.com/course/unity3d-amazon-cognito/?referralCode=502423153E5F6EE623D4">Unity3D + Amazon Cognito: The ultimate guide 2024!</a></p><p>This course focuses on how Unity3D and Amazon Cognito can work together and is divided into two main parts: using Cognito as a user directory and as an authorization service for Unity.</p><p>In the first part of the course we will see how Amazon Cognito can be used as a user directory. We will learn how to create, retrieve, and delete users from Unity. I will also show you some advanced features of Cognito such as the hosted UI or the federation endpoints and how to log in to a Cognito user with a Google account.</p><p>In the second part of the course, we will use Amazon Cognito as an authorization service. We will access Lambda, S3, and DynamoDB from Unity with guest and authenticated users. We will also see the pros and cons of having a direct integration vs. exposing an endpoint and how Cognito can act as an authorizer to secure an endpoint.</p><p>I conceived this course as a practice guide; beyond learning Cognito concepts and features, I will show how to write functional C# code in Unity scripts and how to use the AWS console with different Amazon services.</p><p>I really hope you will like it and find it useful for your future personal or professional projects. If you have some feedback or suggestions, please reach out to me on my social networks:</p><p>🌳 <a href="https://linktr.ee/alexandre.bruffa">Alexandre Bruffa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef65db7bb7e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RealTime Servers & JavaScript SDK: AWS Answered Me!]]></title>
            <link>https://medium.com/@alexandre.bruffa/realtime-servers-javascript-sdk-aws-answered-me-69430952d9bc?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/69430952d9bc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[gamelift]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 23:37:03 GMT</pubDate>
            <atom:updated>2024-05-03T04:30:43.644Z</atom:updated>
            <content:encoded><![CDATA[<h4>Version 2 or Version 3?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_tt_U9pZU0LPyHS6fbzRg.png" /></figure><p>Weeks ago, I showed how a real-time multiplayer game can integrate AI components by connecting a GameLift Realtime server and Bedrock, Amazon’s new generative AI service. I recommend you check out my previous post to know step-by-step how to do it:</p><p><a href="https://medium.com/@alexandre.bruffa/enhance-your-real-time-multiplayer-game-with-generative-ai-787254af1e80">Enhance Your Real-time Multiplayer Game with Generative AI (Bedrock)!</a></p><p>Hey! I made a video summarizing this post; check it out!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3xfonD8xJzc&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3xfonD8xJzc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a6b11414857b293fc5a9b293cf82834/href">https://medium.com/media/6a6b11414857b293fc5a9b293cf82834/href</a></iframe><h3>Context</h3><p>This is the general architecture I used to integrate AI components into a real-time multiplayer game built with Amazon GameLift:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpmFy1VJJdcpftcxhvJtHQ.png" /></figure><p>Let’s focus on the ⚡ <strong>part</strong>: To connect my Realtime server and Bedrock through a Lambda function, I added code to my Realtime script to assume the service role and invoke the Lambda function, as described in the <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-sdk-server-resources.html">GameLift documentation</a><strong>. </strong>Realtime servers use <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift_quickstart_integration.html">Node.js and JavaScript</a>, so I used the <a href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html">AWS SDK for JavaScript</a>.</p><p>🚨 For some reason, <strong>I could not use the </strong><a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/"><strong>AWS SDK for JavaScript version 3</strong></a>; it made my game server crash when starting. In the Events section, I figured out that an error was raised indicating that the game server was unhealthy and forcibly terminated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owcHxZXijw1hSW3GvKr0bQ.png" /></figure><p>When I used the AWS SDK for JavaScript version 2, everything worked like a charm. At this point, I wondered why I could not make it with version 3. Did I miss some requirements in the AWS documentation? Let’s delve into it.</p><h3>JavaScript SDK Version 2 vs. Version 3</h3><p>Working with version AWS SDK for JavaScript version 3 is convenient, and I will explain why. First, the AWS SDK for JavaScript version 2 is <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/">almost deprecated</a> (maintenance mode), and the documentation is sometimes hard to find. As a developer, I prefer to work with up-to-date tools.</p><p>Then, remember that the AWS SDK for JavaScript is not installed on Realtime servers, so you have to install it locally, zip it along with your Realtime script, and upload it to GameLift. The main evolution from version 2 to version 3 is <a href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html#welcome_whats_new_v3">the SDK package’s modularity</a>. With version 3, you can install and import only the packages you need instead of installing and importing the whole SDK into your code.</p><p>For the previous implementation, wrapping the whole SDK version 2 brought me another issue: the zip file was too large and could not be uploaded directly to GameLift. A workaround was uploading the file to an S3 bucket and creating an additional role, adding more complexity to the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n2FIyhVgozDWJeU_.png" /></figure><p>Working with version 3 would have avoided those issues.</p><h3>The Solution</h3><p>The GameLift documentation shows no indications about the compatibility between Realtime servers and the AWS SDK for JavaScript version 3. However, in the <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/introduction/#nodejs-versions">AWS SDK for JavaScript v3 documentation</a>, I found this requirement I missed the first time:</p><blockquote>v3.201.0 and higher requires Node.js &gt;= 14.<br>v3.46.0 to v3.200.0 requires Node.js &gt;= 12.<br>Earlier versions require Node.js &gt;= 10.</blockquote><p>Realtime servers use Node.js, but which version of Node.js? No clue about it in the whole GameLift documentation, so let’s find out! In my Realtime script, I added code to print the Node.js version of the Realtime server into the logs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/373a563ea4d271ad2e34624f9232e663/href">https://medium.com/media/373a563ea4d271ad2e34624f9232e663/href</a></iframe><p>Then, I read the game session logs, as I described in my <a href="https://medium.com/@alexandre.bruffa/debug-your-gamelift-game-server-like-a-pro-4cc06f5a3111">previous post</a>. Surprise! The Realtime servers are running an old version of Node.js: <strong>10.15.2</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGoc1Nu9KTHPWMaYy5V2_g.png" /></figure><p>OK, that could be a problem! The actual version of the AWS SDK for JavaScript (<strong>v3.494.0</strong>) is not compatible with this version of Node.js. So, in my local environment, I installed the STS and Lambda packages with an old version that matches the Node.js requirements: <a href="https://github.com/aws/aws-sdk-js-v3/releases/tag/v3.40.0"><strong>v3.40.0</strong></a>:</p><pre>npm install @aws-sdk/client-sts@v3.40.0<br>npm install @aws-sdk/client-lambda@v3.40.0</pre><p>Then, re-wrap, re-upload to GameLift (without size issue!), re-create a fleet, and… it works! The game server and game sessions are running correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*6eGXTAoZ6nn020Y5LF50dA.gif" /><figcaption>Me when I found the solution</figcaption></figure><h3>GameLift Team’s Answer</h3><p>While I was stuck with this problem, I contacted the GameLift team, and they answered me the following:</p><blockquote>Currently, GameLift does not support JavaScript v3 for Realtime Servers. We are happy to take this as an enhancement request and add it to our backlog. However, at this point, we cannot provide any timelines for the availability of this feature.</blockquote><p>This makes sense! The AWS SDK for JavaScript version 3 does not offer full support, so the GameLift team recommends not using it.</p><h3>Conclusion</h3><p>Although I showed how to make it work with version 3, the GameLift team highly recommends using AWS SDK for JavaScript version 2. So, to access AWS resources from your Realtime server, you can use AWS SDK for JavaScript <strong>version 2 (recommended)</strong> or <strong>version 3 &lt; v3.46.0 (at your own risk)</strong>.</p><p>As an addendum to my <a href="https://medium.com/@alexandre.bruffa/enhance-your-real-time-multiplayer-game-with-generative-ai-787254af1e80">previous article</a>, you can find below the Realtime script I used in both versions:</p><ul><li>The <a href="https://gist.github.com/alexandre-bruffa/0621104f11623d8e1e54c648b37aeebb">Realtime Script</a> with AWS SDK for JavaScript version 2</li><li>The <a href="https://gist.github.com/alexandre-bruffa/d686083d09c29f5cadac171feb9e339d">Realtime Script</a> with AWS SDK for JavaScript version 3</li></ul><p>A very big thanks to the GameLift team, who gave me a precise answer to my very technical question, and Chris Blackwell for his help and the guidance he’s always providing me regarding game services.</p><p>If you have any feedback or questions, feel free to reach out to me on my social networks:</p><p>🎬 <a href="https://www.youtube.com/@alexandrebruffa">YouTube</a> Ⓜ️ <a href="https://medium.com/@alexandre.bruffa">Medium</a> 🌐 <a href="https://alexandrebruffa.com/">Website</a></p><p>See you in the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69430952d9bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug Your GameLift Game Server Like a Pro]]></title>
            <link>https://medium.com/@alexandre.bruffa/debug-your-gamelift-game-server-like-a-pro-4cc06f5a3111?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cc06f5a3111</guid>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gamelift]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 05:33:14 GMT</pubDate>
            <atom:updated>2024-02-01T02:27:32.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>Debugging session!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-rCyTUNqx85jZfSwqs7Hg.png" /></figure><p>Lately, I have published a series of articles and videos about creating a real-time multiplayer game with Unity3D and Amazon GameLift. The feedback I received about them had been outstanding: a lot of developers downloaded my source code and made their own projects and games using Amazon services.</p><p><a href="https://betterprogramming.pub/building-a-real-time-multiplayer-game-with-unity3d-and-amazon-gamelift-228f706cfbec">Building a Real-Time Multiplayer Game With Unity3D and Amazon GameLift</a></p><p>I received many messages and e-mails asking me for help as well. Let’s be honest: the architecture of a real-time multiplayer game that I always suggest is simple but contains a lot of distinct elements working together like the cogs in a well-oiled machine. A simple mistake and the whole architecture will fail. Furthermore, GameLift can sometimes be unfriendly; I personally had some hard times when trying to find the cause of an error or bug.</p><p>In this post, I will explore the common errors people have experienced and how to debug a GameLift game server.</p><p>Do you prefer watching a video instead of reading? Here you have:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FX7IqenkmmY4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DX7IqenkmmY4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FX7IqenkmmY4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cf291d1a1c9ed5a75738cd9ed37f848/href">https://medium.com/media/7cf291d1a1c9ed5a75738cd9ed37f848/href</a></iframe><h3>5 Common Errors To Avoid</h3><p>This is the architecture of a real-time multiplayer game I always suggest in my videos and articles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZgEzreZR6W5o1AxpPoXxg.png" /></figure><p>And those are the 5 common mistakes related to the architecture I could identify:</p><h4>1. AWS SDK for .NET</h4><p>Numerous people asking me for help had trouble connecting to the Lambda function from Unity. Remember that Unity uses .NET Standard 2.1, and the Amazon <a href="https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/unity-special.html">documentation</a> recommends downloading the AWS SDK for .NET <a href="https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-obtain-assemblies.html#download-zip-files">here</a> for Unity. If you download the wrong version or download it from elsewhere, some Amazon services won’t work correctly, including the Lambda calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*U3IkaWp_Nh4DRXquk9a1Wg.png" /><figcaption>Unity project settings</figcaption></figure><h4>2. Multiple Unity Desktop Clients</h4><p>In my code, I have included a mechanism to avoid consuming the game server resources if the users minimize the application using the Unity functions <a href="https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationFocus.html">OnApplicationFocus</a> and <a href="https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationPause.html">OnApplicationPause</a>. Some of you were trying to launch multiple Unity desktop clients and experienced server disconnections in the out-of-focus clients. In this case, please comment both functions or add a <a href="https://docs.unity3d.com/Manual/PlatformDependentCompilation.html">conditional compilation</a> for the Unity editor in the AppController class.</p><h4>3. Client Proxy / Firewall / VPN</h4><p>The connection between the Unity client and the game server is established thanks to the <a href="https://aws.amazon.com/gamelift/features/">TCP and UDP networking</a>. Ensure you don’t have any software or system that could block your TCP and UDP ports, like a proxy, firewall, or VPN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nH6IB2-XLpGwEcCYr4oZpg.jpeg" /></figure><h4>4. Memory Provisioning for Lambda</h4><p>I have been told that for the first connection after a long time to the Lambda function, an error is returned, and the player can not join the game. This is totally “normal”: this phenomenon is known as a <strong>cold start</strong>.</p><p>According to the <a href="https://www.pluralsight.com/resources/blog/cloud/how-long-does-aws-lambda-keep-your-idle-functions-around-before-a-cold-start">cloud experts PluralSight</a>, “A cold start occurs when an AWS Lambda function is invoked after not being used for an extended period of time, resulting in increased invocation latency.”. A Lambda function has a default timeout of 3 seconds; an error is returned if the execution time exceeds the function timeout.</p><p>To solve this slow invocation issue, Amazon recommends over-provisioning your <a href="https://aws.amazon.com/blogs/architecture/best-practices-for-developing-on-aws-lambda/">Lambda function memory instead of the timeout</a> to avoid unexpected costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-LSrnaCQ8J5MYnfzW94EQ.png" /><figcaption>Lambda function configuration</figcaption></figure><h4>5. GameLift Launch Path</h4><p>Before creating your GameLift fleet, you need first to upload to GameLift a compressed archive (zip file) containing your Realtime script and dependencies. During the fleet creation, you will be asked for the launch path, in other words, the path of your Javascript code file within the zip file. For example, if you have no dependencies and have compressed the Javascript file directly, the path will be file.js. If you have compressed a folder containing your Javascript file and dependencies, the path will be folder/file.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnDLl5ihbnpdRJaFN1hNqw.png" /><figcaption>Launch path during fleet creation</figcaption></figure><p>if you want more insights about the Realtime script, please check my post about it:</p><p><a href="https://medium.com/better-programming/unity3d-amazon-gamelift-focus-on-the-realtime-script-c8f0e9ac4392">Unity3D + Amazon GameLift: Focus on the Realtime Script</a></p><h3>Debugging a GameLift Game Server</h3><p>Suppose that your Unity client runs great, and your Lambda function is called correctly, but a new game session can not be created, probably due to an error in GameLift. The first thing you must check is whether your game server is running correctly, thanks to the GameLift events and metrics.</p><h4>Events &amp; Metrics</h4><p>In the GameLift console, click on your fleet and go to the Events section. This section collects all the log entries describing an event that involves GameLift resources. The <a href="https://docs.aws.amazon.com/gamelift/latest/apireference/API_Event.html">GameLift documentation</a> says the following: “In addition to tracking activity, event codes and messages can provide additional information for troubleshooting and debugging problems.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wdkcRrFwB0g8YfE-spFWQ.png" /><figcaption>Events section</figcaption></figure><p>If your fleet is running correctly, you should see the following main events showing up in this specific order: FLEET_CREATED, FLEET_STATE_VALIDATING, FLEET_STATE_ACTIVATING, FLEET_STATE_ACTIVE, FLEET_SCALING_EVENT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bl40ZmZisctfQqBRgN8jUw.png" /><figcaption>Fleet creation events flow</figcaption></figure><p>If you see critical messages like SERVER_PROCESS_TERMINATED_UNHEALTHY during the fleet creation, something may be wrong with either the launch path (see previous section) or your Realtime script (wrong syntax or broken dependencies).</p><p>The last message of the successful fleet creation is a scaling message, meaning that your fleet has automatically scaled up, launching a new EC2 instance. If you go to the Metrics section, you can visualize it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cg7SrHaV2rH0z_87QmgpbQ.png" /></figure><p>Your game server is running correctly!</p><h4>Game Session Logs</h4><p>Now, suppose that your game server is running correctly: your fleet has scaled up, and no critical messages have shown up during the fleet creation. You are able to execute multiple Unity clients at the same time, and the multiplayer feature works great. However, in some cases, you notice that for some actions you perform in the Unity client, your game server does not have the expected behavior and can even crash. Something is failing in your Realtime script, and you want to check the value of certain variables at a precise moment in time.</p><p>There is a simple workaround: you can write into the game session logs and then access them to see what happened.</p><p><strong>▶️ Writing into the game session logs</strong></p><p>Do you remember my previous article about talking with NPCs?</p><p><a href="https://medium.com/@alexandre.bruffa/enhance-your-real-time-multiplayer-game-with-generative-ai-787254af1e80">Enhance Your Real-time Multiplayer Game with Generative AI (Bedrock)!</a></p><p>I will add a few lines of code in the Realtime script: when a player starts to talk with an NPC, I will write information into the game session logs. According to the <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/logging-server-messages-rts.html">GameLift documentation</a>, there are 6 levels of server log messages; let’s try with 3 of them: info, warning, and error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bd3340115eb46552ec1865c93241226/href">https://medium.com/media/5bd3340115eb46552ec1865c93241226/href</a></iframe><p>We have written into the game session logs; now, let’s access them!</p><p><strong>▶️ Accessing the game session logs</strong></p><p>This part is a little bit tricky. As described in the <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/logging-server-messages-rts.html#accessing-rts-server-logs">GameLift documentation</a>, when a game session finishes, the related logs are stored in an S3 bucket. There is no simple way to access those logs; the only way to achieve it is by using the <a href="https://docs.aws.amazon.com/gamelift/latest/apireference/API_GetGameSessionLogUrl.html">GetGameSessionLogUrl API call</a> to get the location of the logs. I will implement the API call in a Lambda function. I’m a Python guy so I will do it with Python, but it’s up to you to use your favorite language!</p><p>Remember that <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html">Lambda includes boto3</a>, the official AWS SDK for Python, perfect! Checking the documentation of the boto3 function <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/gamelift/client/get_game_session_log_url.html">get_game_session_log_url</a>, we can figure out that the function requires a parameter called GameSessionId, described as “A unique identifier for the game session to get logs for.”. There is a slight confusion with the boto3 documentation and, more generally, with the whole Amazon documentation: we need the game session ARN, not the game session ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Swz-JcAgnKbjbTK71nyqeA.png" /><figcaption>Game session ID and ARN</figcaption></figure><p><strong>▶️ Building the Lambda function</strong></p><p>Now we can write the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fab294c6c5342f5cc30109e8c79cf5a8/href">https://medium.com/media/fab294c6c5342f5cc30109e8c79cf5a8/href</a></iframe><p>Before executing the function, we need to give the Lambda function the necessary permissions to access the game session logs. Go to the Lambda function role and add the following policy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da966206d4cb4584d0d534d3b0321b38/href">https://medium.com/media/da966206d4cb4584d0d534d3b0321b38/href</a></iframe><p><strong>▶️ Reading the logs</strong></p><p>Now, let’s execute the function! The answer will return a pre-signed URL of the location of the logs for the specific game session:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c89c5bb4ce11336ca0ee227c2c35bb09/href">https://medium.com/media/c89c5bb4ce11336ca0ee227c2c35bb09/href</a></iframe><p>Note that a pre-signed URL is temporary: in this particular case, the URL is valid for 15 minutes after the request. Visit the URL with your favorite internet browser and download the logs. Our messages can be visualized!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yekc6BdZAE50iU-VE8DWaA.png" /><figcaption>game session log file</figcaption></figure><h3>Final Thoughts</h3><p>Thanks for reading this post until the end! I really hope it helped you troubleshoot your real-time multiplayer game and understand more deeply how the game session logs work.</p><p>If you have any feedback or questions, feel free to reach out to me on my social networks:</p><p>🎬 <a href="https://www.youtube.com/@alexandrebruffa">YouTube</a> Ⓜ️ <a href="https://medium.com/@alexandre.bruffa">Medium</a> 🌐 <a href="https://alexandrebruffa.com/">Website</a></p><p>See you in the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cc06f5a3111" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhance Your Real-time Multiplayer Game with Generative AI (Bedrock)!]]></title>
            <link>https://medium.com/@alexandre.bruffa/enhance-your-real-time-multiplayer-game-with-generative-ai-787254af1e80?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/787254af1e80</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[gamelift]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bedrock]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 15:26:24 GMT</pubDate>
            <atom:updated>2023-11-30T17:09:22.702Z</atom:updated>
            <content:encoded><![CDATA[<h4>Talking With NPCs!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_1bv-hRecBU-QAe7HQU-g.png" /></figure><p>Can an NPC be smart? What about having a real conversation with an NPC? You may have watched those <a href="https://www.youtube.com/watch?v=4sCWf2VGdfc">incredible videos</a> of gamers talking with AI NPCs. Can it be done with Unity3D and Amazon services? Let’s see!</p><p>Check my video to learn how to do it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOP3wzv7AHoc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOP3wzv7AHoc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOP3wzv7AHoc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c62a74706e9382bab664a18b1dc21bbc/href">https://medium.com/media/c62a74706e9382bab664a18b1dc21bbc/href</a></iframe><h3>Preamble</h3><p>Lately, I have published a series of articles and videos about building a real-time multiplayer game with Unity3D and Amazon GameLift.</p><p><a href="https://betterprogramming.pub/building-a-real-time-multiplayer-game-with-unity3d-and-amazon-gamelift-228f706cfbec">Building a Real-Time Multiplayer Game With Unity3D and Amazon GameLift</a></p><p>I also entered the AI field and produced content about integrating Unity3D and AI services: ChatGPT, Dall-E, and Amazon Bedrock.</p><p><a href="https://betterprogramming.pub/generative-ai-with-amazon-bedrock-and-unity3d-e1ecd5c0c8a2">Generative AI With Amazon Bedrock and Unity3D</a></p><p>On my video about Amazon Bedrock, a clever follower left this comment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*FpYM2Th7vp0wX1BHihnMiw@2x.jpeg" /></figure><p>What an outstanding idea! Technically, it would be a perfect mix between my work about Amazon GameLift and the one about Bedrock. Thanks for the idea, bro; let’s do it!</p><h3>About NPCs</h3><p>A non-player character (NPC), as its name indicates, is a character that is not controlled by a player but can eventually interact with the real players of a game. Therefore, every action or decision taken by the NPC is server-managed. The flow is the following:</p><ol><li>A player interacts with an NPC; the player notifies the game server.</li><li>The game server processes the information and eventually connects to other services (Database, AI, etc. )</li><li>The game server sends an answer to all the players, and Unity clients are updated.</li></ol><h3>General Architecture</h3><p>The architecture of this project contains 3 main parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BardtvCUoInXfkIJTgCM2Q.png" /></figure><ol><li>A simple architecture of a real-time multiplayer game implicating the services Cognito, Lambda, and GameLift.</li><li>A Lambda function that calls the generative AI service Amazon Bedrock.</li><li>A connection between the GameLift’s game server and the Lambda function.</li></ol><p>For the first two parts, please refer to the following articles and videos: <a href="https://medium.com/better-programming/building-a-real-time-multiplayer-game-with-unity3d-and-amazon-gamelift-228f706cfbec">Building a Real-Time Multiplayer Game With Unity3D and Amazon GameLift</a> and <a href="https://medium.com/better-programming/generative-ai-with-amazon-bedrock-and-unity3d-e1ecd5c0c8a2">Generative AI With Amazon Bedrock and Unity3D</a>. This article will focus on how to invoke a Lambda function from a GameLift’s game server.</p><h3>Accessing AWS Resources From GameLift</h3><p>We want the game server to access another AWS resource here, Lambda. The classical way to do it would be to create a role with associated policies to allow GameLift to invoke a specific Lambda function. But this is an uncommon case and requires an <strong>extra step</strong>. The <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-sdk-server-resources.html">GameLift documentation</a> says you can achieve doing the following:</p><ol><li>Set up an IAM service role for Amazon GameLift.</li><li>Associate the service role with an Amazon GameLift fleet.</li><li><strong>Add code to your game server to assume the service role.</strong></li></ol><p>So, why this extra step? Remember that GameLift game servers are actually composed of one or various EC2 instances (fleet); therefore, we must associate a role to the fleet <strong>and also</strong> to the EC2 instance where the game session is running. After that, we can invoke our Lambda function from the game server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIMfy3HVBsXjbucuUWwBGw.png" /></figure><p>It’s not so straightforward, so fasten your seatbelt, and let’s start!</p><h3>The IAM role</h3><p>The new role we are creating will allow GameLift to access other resources. To do so, we select GameLift as a trusted entity when creating the role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Xst0y6TyVFvdzP1wD6LJg.png" /></figure><p>By default, an AWS-managed policy called GameLiftGameServerGroupPolicy is attached to the role. We create a new policy to allow access to the Lambda function and attach it to the role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1YMPf_k8qO6IZ2LiDW-DA.png" /></figure><p>Okay, so we have the role ready; we can attach it to a new GameLift fleet. But don’t create the fleet yet! We need to work on the Realtime script and dependencies first.</p><h3>The Realtime Script</h3><p>This is the spicy part. The role we have created is assumed by the GameLift fleet, but as mentioned before, we also need to assume the role from the Realtime script. Realtime servers use <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift_quickstart_integration.html">Node.js and JavaScript</a>, so we will use the <a href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html">AWS SDK for JavaScript</a>.</p><p>For some reason, I could not use the AWS SDK for Javascript version 3; it made my game server crash. I used the <a href="https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/welcome.html">AWS SDK for Javascript version 2</a> instead, and everything worked like a charm. If you could achieve it with version 3, please reach out to me!</p><p>First, we need the game server to assume the role we have created. In the init function of the Realtime Script, we call the STS service and assume the role:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e15c93dbff1728e2ba73759682c9b458/href">https://medium.com/media/e15c93dbff1728e2ba73759682c9b458/href</a></iframe><p><strong>Notes</strong>:</p><ul><li>We call the function assumeRole as specified in the STS <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/STS.html#assumeRole-property">documentation</a></li></ul><p>As indicated in the <a href="https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html">STS documentation</a>, the response has the following structure containing credentials:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2b450ea45177f2761ee4df2653ce4aa/href">https://medium.com/media/f2b450ea45177f2761ee4df2653ce4aa/href</a></iframe><p>Thanks to the credentials, we can now call our lambda function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f94e23ffa8a4b08286c9df8cf8e18df5/href">https://medium.com/media/f94e23ffa8a4b08286c9df8cf8e18df5/href</a></iframe><p><strong>Notes</strong>:</p><ul><li>We call the Lambda constructor thanks to the credentials returned by STS, as specified in the <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#constructor-property">documentation</a>.</li><li>We invoke the Lambda function (in my case npcFunction), as specified in the <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property">documentation</a>.</li></ul><p>To get more details about how the Realtime script works, please refer to this previous article:</p><p><a href="https://medium.com/better-programming/unity3d-amazon-gamelift-focus-on-the-realtime-script-c8f0e9ac4392">Unity3D + Amazon GameLift: Focus on the Realtime Script</a></p><h3>The Dependencies</h3><p>In the previous section, we worked with the AWS SDK for JavaScript in the Realtime script. Small but very important detail: the AWS SDK for JavaScript <strong>is not installed</strong> on the game server! Good news: we can upload the dependencies along with the Realtime script. Therefore, we will follow those steps:</p><h4>Install Node.js in your local environment.</h4><p>First, go to the Node.js from the <a href="https://nodejs.org/en/download">official website</a>. Select the operating system running on your local machine and install Node. Once installed, open a new terminal (or command prompt) and type “node”. You should be able to enter the Node console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjSnXbse0ILPqWWXZEOCiw.png" /></figure><h4>Install the AWS SDK for Javascript</h4><p>In a new terminal, go to the folder containing your Realtime script and install the AWS SDK for Javascript version 2 thanks to Node’s package manager, NPM:</p><pre>npm install aws-sdk</pre><p>Once installed, 3 new items have been created: the package.json and package-lock.json files and the node_modules folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*d2W3qnzV5MmSnCz6jx-J0Q.png" /></figure><h4>Wrap the script and the dependencies</h4><p>Zip the folder containing the Realtime script and the dependencies (4 files in total), and go to the GameLift console. In the script section, create a new script and select the zip file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5FUNogVPiUtjs87_WA7bQ.png" /></figure><p>🚨 Houston, we have a problem: our zip file is too big! The reason is the following: AWS SDK for Javascript version 2 is not modular, so we had no choice: we have installed and zipped the whole SDK (12 MB). With the AWS SDK for Javascript version 3, we could have installed <a href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/loading-the-jssdk.html">only the services we need</a> (STS and Lambda), and this would have resulted in a lightweight zip file (2–3 MB).</p><p>Hopefully, another option is available: hosting our zip file in an Amazon S3 bucket. This is our updated architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fboCxYjQgT7sn8ub2_BtPg.png" /></figure><h4>Create an S3 bucket and a related role</h4><p>Create a new S3 private bucket and upload the zip file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXuxk5NvFvDwh7cAWkpBvw.png" /></figure><p>In the IAM console, create a new role with GameLift as a trusted entity and attach a policy that allows the private bucket and its content to be read:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRrOY0B3_S6qBcXoB5mF5w.png" /></figure><h4>Upload the script and the dependencies to GameLift</h4><p>Come back to the GameLift console! In the script section, create a new script, but this time, select the zip file from S3 and the role we have just created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCDrjEan15MIL_t0VCOQVw.png" /></figure><p>GameLift can now access your Realtime script and dependencies during fleet creation through an S3 bucket.</p><h3>Creating a new Fleet</h3><p>When creating a new fleet, in the additional details section, indicate the role we have created at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZFf0M5ONTm36-MHRAMljQ.png" /></figure><p>You will be asked for the Realtime script. Select the script you have created before, and in the Runtime configuration section, indicate the script&#39;s path. Remember that we have zipped a folder containing the script; therefore, the path will be folder/script, in my case, GameLift/Multiplayer.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjGT_E6kMSOakdWa_sNKxQ.png" /></figure><h3>The Unity Client</h3><h4>The NPC</h4><p>As I mentioned in other posts, I’m <a href="https://www.linkedin.com/in/alexandrebruffa/">not a modeler or a 3D artist</a>; therefore, I always look for free assets for my projects. The characters I’m using for this project, like the previous ones, are from the website <a href="https://www.mixamo.com/#/">Mixamo</a>. This time, I looked for something different for the NPC and found this great <a href="https://free3d.com/3d-model/statue-v1--445854.html">Moai</a> model on <a href="https://free3d.com/">free3D.com</a>. OBJ format is compatible with Unity, perfect!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXaO8w7Pl2X1mW2vuqeH-g.png" /><figcaption>Moai on free3D.com</figcaption></figure><h4>The events</h4><p>For this project, I added 4 new events related to the NPC:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def401741235b5ee77695f6e3c2b026e/href">https://medium.com/media/def401741235b5ee77695f6e3c2b026e/href</a></iframe><ul><li>PLAYER_MEETS_NPC: A player notifies the game server that he wants to interact with the NPC. If the game server allows it, the same event is sent back to all players.</li><li>PLAYER_TO_NPC: The player can now interact with the NPC; he can send this event along with a message.</li><li>NPC_TO_PLAYER: The game server sends a message back to the player.</li><li>PLAYER_LEAVES_NPC: The interaction ends, and all players are notified.</li></ul><h3>Final Result</h3><p>This is the final result of one of the characters interacting with Moai; it looks pretty cool!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*l6J6BVb0fzLv2E55gnpZUA.gif" /></figure><h3>Closing Thoughts</h3><p>Weeks ago, I had the opportunity to share my knowledge as a speaker at the <a href="https://betterprogramming.pub/my-first-experience-as-a-speaker-in-an-aws-conference-471bffc26c8b">AWS UG Peru Conference 2023</a>. One of the attendees asked me: “What is the advantage of using GameLift over another similar service like Photon?”. My answer was the following: using GameLift, YOU build the cloud architecture of your game, and therefore, you can do absolutely what you want. You could, for example, connect your game to an AI service, a database, a notification system, etc.</p><p>And that is totally what I meant with this article: accessing AWS Resources from a GameLift game server opens the door to infinite possibilities! The implementation was a little bit complex, but hey, it is totally worth it!</p><h3>Resources</h3><p>Here are the resources mentioned in the article:</p><ul><li>The <a href="https://gist.github.com/alexandre-bruffa/0621104f11623d8e1e54c648b37aeebb">Realtime Script</a> in JavaScript</li><li>The <a href="https://drive.google.com/file/d/168af5K0dqX7EVJnsetIvOJXwOD2rw83K/view?usp=sharing">Unity package</a> of the game</li><li>The <a href="https://gist.github.com/alexandre-bruffa/747341add4b09b9c9aa728b722ef3164">Lambda policy</a> for GameLift</li><li>The <a href="https://gist.github.com/alexandre-bruffa/311aeb8bff48fdc9499011432dab429f">S3 policy</a> for GameLift</li></ul><p>I also used free <a href="https://www.mixamo.com/">Mixamo</a> characters and a model from <a href="https://free3d.com/">free3D.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=787254af1e80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Experience as a Speaker in an AWS Conference]]></title>
            <link>https://medium.com/better-programming/my-first-experience-as-a-speaker-in-an-aws-conference-471bffc26c8b?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/471bffc26c8b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gamelift]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity3d]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 06:59:45 GMT</pubDate>
            <atom:updated>2023-10-18T15:23:18.624Z</atom:updated>
            <content:encoded><![CDATA[<h4>My experience at the AWS UG Peru Conference 2023</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiNt8YvnTO4BeC-jyTi9eQ.png" /></figure><p>Last Saturday, I had the opportunity to share my knowledge as a speaker at the AWS UG Peru Conference 2023. It was a wonderful experience; I will share it in this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0GoMHmtPt6V4Rnx5kh6Zg.jpeg" /><figcaption>Promotional banner for my talk</figcaption></figure><h3>An Event Huger Than Expected</h3><p>When I postulated to be a speaker at this conference, I totally underestimated the event&#39;s magnitude. 4500 registered persons, 2300 attendees, and more than 100 speakers in just one day making it one of the biggest AWS events in Latin America. It was impressive!</p><p>4 floors of the PUCP Cultural Center in Lima were full of AWS enthusiasts attending highly diverse talks and participating in activities, workshops, and contests; an <em>El Dorado</em> for any cloud lover!</p><p>Speakers from all over the Americas shared their knowledge in various languages. I chose to speak Spanish to feel more comfortable and answer the audience&#39;s questions easily.</p><figure><img alt="My name and picture on the banner of the Nazca conference room" src="https://cdn-images-1.medium.com/max/1024/1*o3pdk4N4ywnPl92JMP0LxA.jpeg" /><figcaption>My name and picture on the banner of the Nazca conference room</figcaption></figure><h3>A Risky Talk</h3><p>For my talk, I chose to make a live demo of a real-time multiplayer game created with Unity3D and Amazon GameLift. Undoubtedly a bold bet since this live demo required multiple fully operational Unity clients, some Amazon services running on the cloud, and an excellent internet connection. If one of those components did not respond as expected, it would have been a total failure!</p><p>Following my fellow AWS CB <a href="https://alfalfita.cloud/">Diana Alfaro</a>’s wise advice, I recorded the whole demo the day before the conference. In the worst case, I would have shown a video to the audience. Maybe not the ideal scenario, but it would have saved the day.</p><p>Hopefully, the internet of the PUCP Cultural Center could handle thousands of simultaneous connections with a high bandwidth; perfect! I could make my demo without experiment any inconvenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOXQvVy9e9w_cYqzu2PoCQ.jpeg" /><figcaption>3 Unity clients running on 2 devices</figcaption></figure><h3>A Great Audience</h3><p>I will be honest; for this talk, I was expecting a cloud veterans audience, but the title of my talk attracted the curiosity of young people interested in video game creation, and the result was awesome! I’m aware that the content I’m producing through my posts and videos may be uncommon, and I was so thrilled that so many people came to see my talk!</p><p>The spectators paid a lot of attention and asked me questions about GameLift, Unity, and game development in general. A lucky guy in the first row could even participate in the demo: I let him play with one of the Unity clients running on a mobile device while everybody could see it on the projector screen.</p><figure><img alt="Overview of the audience" src="https://cdn-images-1.medium.com/max/320/1*ZjcOeLpMUxPeCj4XwiWC8Q.gif" /><figcaption>My family also came to see me ❤️</figcaption></figure><h3>Final Thoughts</h3><p>It was an incredible experience, and I hope to be part of the AWS UG Peru Conference next year as a speaker and as a member of the organization&#39;s staff.</p><p>My talk was not recorded, but I created a video summarizing the Q&amp;A section.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWPSaGpT739s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWPSaGpT739s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWPSaGpT739s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ab660f3b5e5042070006fe3e9441d18/href">https://medium.com/media/4ab660f3b5e5042070006fe3e9441d18/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=471bffc26c8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/my-first-experience-as-a-speaker-in-an-aws-conference-471bffc26c8b">My First Experience as a Speaker in an AWS Conference</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI With Amazon Bedrock and Unity3D]]></title>
            <link>https://medium.com/better-programming/generative-ai-with-amazon-bedrock-and-unity3d-e1ecd5c0c8a2?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ecd5c0c8a2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 03:12:46 GMT</pubDate>
            <atom:updated>2023-10-12T17:27:20.890Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a cool AI chat with Unity3D and Amazon Bedrock.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hj9_7laPkv_vTSe6y3CDfw.jpeg" /></figure><p>A few days ago, Amazon made a big announcement: the service <strong>Bedrock</strong> was finally released.</p><p>If you missed the news, here it is: Amazon decided to enter massively into the generative AI field and invested in the company <a href="https://www.cnbc.com/2023/09/25/amazon-to-invest-up-to-4-billion-in-anthropic-a-rival-to-chatgpt-developer-openai.html">Anthropic for $4 billion</a> in order to compete with popular AI services like ChatGPT, Dall-E, MidJourney, etc. The first proposal of Amazon is Bedrock, a fully managed AI service that offers multiple foundational models such as Claude, Jurassic, and Stable Diffusion XL, among others.</p><p>In my previous articles, I created Unity3D applications communicating with <a href="https://betterprogramming.pub/i-made-chatgpt-talk-using-unity3d-and-aws-b0e83e6cce66">ChatGPT</a> and <a href="https://medium.com/better-programming/generating-ai-images-with-dall-e-aws-and-unity3d-33e9b77a2b5d">Dall-E</a>. Let’s do the same with Bedrock!</p><p><a href="https://betterprogramming.pub/generating-ai-images-with-dall-e-aws-and-unity3d-33e9b77a2b5d">Generating AI Images With DALL-E, AWS, and Unity3D</a></p><p>Do you prefer something more interactive instead of reading? Check my video!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkzKxuGhdeZM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkzKxuGhdeZM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkzKxuGhdeZM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/775a49ace88350d5312f2050a7fd4f95/href">https://medium.com/media/775a49ace88350d5312f2050a7fd4f95/href</a></iframe><h3>General Architecture</h3><p>Here is the general architecture of our application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC81wbuLpNy6St40j2OlwQ.png" /></figure><p>We use 3 Amazon services:</p><ul><li><strong>API Gateway</strong> to create, expose, and consume endpoints.</li><li><strong>Lambda</strong> to receive the client&#39;s requests and communicate with Bedrock.</li><li><strong>Bedrock</strong> to generate answers based on the client’s prompts.</li></ul><p>If you want to get further adding a login mechanism with Cognito, please refer to my previous article:</p><p><a href="https://betterprogramming.pub/i-made-chatgpt-talk-using-unity3d-and-aws-b0e83e6cce66">Connecting Unity3D, AWS, and ChatGPT Together</a></p><h3>Bedrock</h3><p>First, we have to enable the foundational models we want to use. By default, all the models are disabled. Go to the Bedrock console and enable the models you will use in the model access section. If you have an updated payment method, activating the models only takes a few minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JHGOtOfcUqeZ5s5yH1b1g.png" /><figcaption>Model access section in the Bedrock console</figcaption></figure><p>If you don&#39;t enable the models in the Bedrock console, you will receive this error in Lambda:</p><blockquote>An error occurred (AccessDeniedException) when calling the InvokeModel operation: Your account is not authorized to invoke this API operation.</blockquote><h3>Lambda, Boto3 and Bedrock</h3><p>If you follow my work, you know I’m a Python guy, so I will use the Python SDK for AWS, <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a>. Good news: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock.html">Bedrock is available</a> on Boto3; bad news: Lambda runs an old version of Boto3 in which Bedrock does not exist yet.</p><p><strong>💡 Here is a workaround</strong>: creating a new Lambda layer with an up-to-date version of Boto3. This is how to do it:</p><ol><li>In PyCharm, create a new project and install boto3 in a new virtual environment. Boto3 and all the dependencies will be installed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vl3wkHw4l_KSrkPN-pk11g.png" /><figcaption>PyCharm project</figcaption></figure><p>2. Go to the venv folder of your project and copy the lib folder into a new folder called python. Then, zip it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGaHIlkXe2G8MPwlRioqKw.png" /><figcaption>venv folder</figcaption></figure><p>3. Go to the Layers section of the Lambda console and create a new layer. Upload the zip file we have created before and choose the same Python version as your local Python virtual environment for the runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROqEeN2uots5sKKrMp54WQ.png" /><figcaption>Creating a new Layer</figcaption></figure><h3>The Lambda Functions</h3><p>We create 2 Lambda functions, one for text generation and the other one for image generation, both with the same version as previously for the runtime (In my case, Python 3.9), and we add the layer we have created before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6R8GZZtJU3us3tXSUImmw.png" /><figcaption>Adding a new layer to the Lambda function</figcaption></figure><h4>The text generation function</h4><p>For the text generation, I use the Claude model and implement it as described in the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/api-methods-run-inference.html">Amazon documentation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8685d4d23ff657ecd8a6c455f7a917c/href">https://medium.com/media/e8685d4d23ff657ecd8a6c455f7a917c/href</a></iframe><h4>The image generation function</h4><p>For the image generation, I use the Stable Diffusion XL model and implement it, as described in the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/api-methods-run-inference.html">Amazon documentation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3a1786db32f89f92c4be342fb954e66/href">https://medium.com/media/e3a1786db32f89f92c4be342fb954e66/href</a></iframe><p>Note that the model IDs can be found in the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html">Bedrock documentation</a>.</p><h4>The Lambda Policy</h4><p>In order to allow Lambda to invoke a Bedrock model, we create a new managed policy and add it to the Lambda functions roles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SljwNm8xbzLeuvh2bEWpZQ.png" /></figure><h3>API Gateway</h3><p>In the API Gateway console, we create a new REST API with 2 resources: image and text. Each resource has a post method integrating with the Lambda functions we have created before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7f9023gwwV1aqICVdwXAQ.png" /><figcaption>API resources</figcaption></figure><p>When deploying the API, you will be asked to create a new stage. After the creation of the stage, the final endpoint will be shown. You will have to use this URL in the Unity client to perform the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt2Xfy-uUnrnURZ5w4o05Q.png" /><figcaption>API stages</figcaption></figure><h3>The Unity Client</h3><p>the Unity client allows the user to send a message to generate a text or an image as an answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*WeDHM33gd7bK25upb07_Sw.png" /></figure><h4>Handling the request</h4><p>First, we need to create serializable classes to embed the sending and receiving data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fd2843a71bdf32efa3fbdfb8fa16150/href">https://medium.com/media/3fd2843a71bdf32efa3fbdfb8fa16150/href</a></iframe><p>Sending a request in Unity is an asynchronous process. Therefore, we create a coroutine that sends the request to the server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a87df5d781eadf664465c2c9d5d079d/href">https://medium.com/media/9a87df5d781eadf664465c2c9d5d079d/href</a></iframe><h4>Dealing with the generated image</h4><p>If we ask for an image generation, the result sent by Bedrock is a base64 image. To show it on the Unity UI, we must convert it into bytes and create a Texture2D. Then, we assign the texture to the RawImage component of the UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef5952fc4e532ebc7e3995db2651102d/href">https://medium.com/media/ef5952fc4e532ebc7e3995db2651102d/href</a></iframe><h4>Result</h4><p>Here is the result with text and image generations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*_IDlPTKOZaU3gHkEsBjNgQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*o7bEtTkAMgROKdV4jSkoWA.gif" /><figcaption>Text generation // Image generation</figcaption></figure><h3>Costs</h3><p>Let’s check with the <a href="https://calculator.aws/">AWS Calculator</a> and the <a href="https://aws.amazon.com/bedrock/pricing/">Bedrock pricing sheet</a> what our system cost would be for a very pessimistic scenario: you love the app, and you perform <strong>2,000 requests a month</strong>. 1,000 for text generation with the Claude model and 1,000 for image generation with Stable Diffusion XL.</p><ul><li><strong>API Gateway</strong>: With 2,000 requests to our REST API, the monthly cost is <strong>0,01 USD</strong></li><li><strong>Lambda</strong>: With 2,000 requests with an average time of 5 seconds and 512 MB of memory allocation, the monthly cost is <strong>0.08 USD.</strong></li><li><strong>Bedrock</strong>: 1,000 text generations by month with a maximum of 300 output tokens and 20 input tokens per request would result, in the worst case, in <strong>$0.2204 + $9.804</strong>. 1,000 image generations would give us a bill of <strong>$18</strong>.</li></ul><p><strong>Total</strong>: The total bill for our system would be approximately <strong>28 USD</strong> monthly. It’s quite affordable!</p><h3>Final Thoughts</h3><p>Using Bedrock is very intuitive, and integrating it with other Amazon services is absolutely straightforward. The fact that Bedrock is an in-house product makes the integration easier: there is no need for API keys or external requests to make it work, resulting in greater performance and security.</p><p>Every code of this article has been tested using Unity 2021.3.3 and Visual Studio Community 2022 for Mac. The mobile device I used to run the Unity app is a Galaxy Tab A7 Lite with Android 11.</p><p>Thanks for reading until the end!</p><h3>Resources</h3><p>Here is the resource mentioned in the article:</p><ul><li>The <a href="https://drive.google.com/file/d/1QWbbHsmMrHi9gKolXfRmwclMdK1Sg4Qm/view?usp=sharing">Unity package</a> of the application</li><li>The <a href="https://gist.github.com/alexandre-bruffa/c876fe69e00b70b9830863e8c7f06eb2">text generation function</a> in Python</li><li>The <a href="https://gist.github.com/alexandre-bruffa/537e19a9ab05748ac77b4a10370cc20b">image generation function</a> in Python</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ecd5c0c8a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/generative-ai-with-amazon-bedrock-and-unity3d-e1ecd5c0c8a2">Generative AI With Amazon Bedrock and Unity3D</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity3D + Amazon GameLift: Focus on the Realtime Script]]></title>
            <link>https://medium.com/better-programming/unity3d-amazon-gamelift-focus-on-the-realtime-script-c8f0e9ac4392?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8f0e9ac4392</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gamelift]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 05:45:58 GMT</pubDate>
            <atom:updated>2023-08-28T14:36:20.214Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write your own script and take control over the game server!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2EUtpggEAmieZJsgGgHdg.jpeg" /></figure><p>In a <a href="https://medium.com/better-programming/building-a-real-time-multiplayer-game-with-unity3d-and-amazon-gamelift-228f706cfbec">previous article</a>, I showed how to build an entire real-time multiplayer game with Amazon GameLift and Unity3D. The process implicates creating game sessions and player sessions with Lambda, guest access to the services with Cognito, and a game server with GameLift.</p><p>We could also find out that the game server’s behavior is defined by a script written in Javascript: <strong>the Realtime Script</strong>. This article will detail how this script works and how to create game server events.</p><blockquote>Note: You can also check out the video version of this blog post</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FikDdlZsjKng%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DikDdlZsjKng&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FikDdlZsjKng%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffe2cf6170263d9c1042c117790e6a59/href">https://medium.com/media/ffe2cf6170263d9c1042c117790e6a59/href</a></iframe><h3>Overview of The Realtime Script</h3><p>The <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/realtime-script.html">Realtime Script</a> is a collection of callback functions the game server calls during its lifetime. In other words, we can implement custom behavior for each of these functions. All the callback functions are described in the <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/realtime-script-callbacks.html">GameLift documentation</a>; here are the main ones:</p><ul><li>onStartGameSession(): Called when a new game session is started. In the callback function, we can store relevant information as the game server start time.</li><li>onPlayerAccepted(): Called when a player is accepted into the game. In the callback function, we can notify the other players that a new player has just joined the game.</li><li>onPlayerDisconnect(): Called when a player has left or been forcibly terminated. In the same way, we can notify the other players that the player disconnected in the callback function.</li><li>onMessage(): Called when a player sends a message to the server (i.e., action performed, position, etc.). In the callback function, we can send the new data to the other players.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7yynz2iu_i8MK7mg_ElrQ.png" /></figure><p>Furthermore, the game session provides interesting functions such as:</p><ul><li>getPlayers(): Retrieves a list of players currently connected to the game session.</li><li>newTextGameMessage(): Creates a new message containing text.</li><li>sendReliableMessage(): Sends a message to a player.</li><li>processEnding(): Terminates the game server.</li></ul><p>All the game session functions are available in the <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/realtime-script-objects.html">GameLift documentation</a>.</p><h3>Creating a Game Server Event</h3><p>In my previous article, I provided a very basic script making the game server act as a simple “dispatcher”. The game server notifies the players if someone joins or disconnects and resends a message sent by a player to the other players (i.e., action, life update, etc. ).</p><p>This time, we will create a non-related player event: a meteorite will fall on the map from time to time. No matter how many players are on the map or what they are doing, this event is 100% managed by the game server.</p><p>Our script contains a loop function used to check if the game session should be ended. We will integrate our new server event in the loop function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V32yUsykqTwwJIGoOT1aWg.png" /></figure><p>We modify the script, adding the new feature in the loop function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb21db8243b0402a33b8737f7c1b14c5/href">https://medium.com/media/fb21db8243b0402a33b8737f7c1b14c5/href</a></iframe><p>Notes:</p><ul><li>We use the sendReliableMessage and newTextGameMessage functions described in the <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/realtime-script-objects.html">GameLift documentation</a>.</li><li>We use the function getRandomArbitrary described in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values">Mozilla Developers&#39; documentation</a>.</li></ul><p>You can find the entire code in the resources section of this article ⬇️</p><h3>The Unity Client</h3><p>In the Unity client, we implement the new event sent by the game server with a countdown and cool VFXs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*ZN-gZ9ZUAQcwkCIrRtLTRg.gif" /></figure><p>It looks awesome! For the meteorite and the explosion, I used assets from the <a href="https://assetstore.unity.com/packages/vfx/particles/voxel-arsenal-136540">Voxel Arsenal assets</a>. I managed the explosion force field with a <a href="https://docs.unity3d.com/Manual/class-SphereCollider.html">Sphere Collider</a> in trigger mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kU_ub5DYh4V2gTxBvQQraQ.png" /><figcaption>Explosion force field</figcaption></figure><p>I used the <a href="https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html">OnTriggerEnter</a> and the <a href="https://docs.unity3d.com/ScriptReference/GameObject.CompareTag.html">CompareTag</a> functions to detect this force on the player. Then, I normalized the differential vector and applied a ratio to it. I found that a ratio of 200 creates a cool visual effect. Finally, I applied the <a href="https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html">AddForce</a> function to the player’s Rigidbody:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ea2c80f87a405f0239ab36f5377705/href">https://medium.com/media/56ea2c80f87a405f0239ab36f5377705/href</a></iframe><h3>Final Thoughts</h3><p>At first glance, the Realtime Script can be complex and challenging to understand, but once you master it, you have total control over the game server’s behavior and can do absolutely what you want! Meteorites, snow, rain, sunshine, real-time updating environment, non-player characters, etc. The only limit is your imagination!</p><p>In the resources section, I provide a Unity package of the game I showed in the demo. The meteorite and explosion assets are not included because of the license type.</p><p>You are free to use all the resources I provided in this article. Please ping me if you use them to build your game; I would be delighted to see the result!</p><h3>Resources</h3><p>Here are all the resources mentioned in the article:</p><ul><li>The <a href="https://gist.github.com/alexandre-bruffa/e42c9c8d17c073897b497efc4f0f8015">GameLift Script</a> written in JavaScript</li><li>The <a href="https://drive.google.com/file/d/1ZeSu7TfSeMu0h29aNSZs0NnEv-soQH0V/view?usp=sharing">Unity package</a> of the game</li></ul><p>For the demo, I’m using the <a href="https://assetstore.unity.com/packages/vfx/particles/voxel-arsenal-136540">Voxel Arsenal assets</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8f0e9ac4392" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/unity3d-amazon-gamelift-focus-on-the-realtime-script-c8f0e9ac4392">Unity3D + Amazon GameLift: Focus on the Realtime Script</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Unsafe Content With Unity3D and Amazon Rekognition]]></title>
            <link>https://medium.com/@alexandre.bruffa/detecting-unsafe-content-with-unity3d-and-amazon-rekognition-3a3829fbfbbf?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a3829fbfbbf</guid>
            <category><![CDATA[tik-tok]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rekognition]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 05:50:42 GMT</pubDate>
            <atom:updated>2023-07-13T05:50:42.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or investigating why I have been permanently banned from TikTok</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_LHTCqZQSJypimoA-xQZg.png" /></figure><p>If you prefer watching a video instead of reading, here you have:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEKJ43l_HiZk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEKJ43l_HiZk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEKJ43l_HiZk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4af074a354be0b31ea1278bbf9404d61/href">https://medium.com/media/4af074a354be0b31ea1278bbf9404d61/href</a></iframe><h3>My Brief Journey on TikTok</h3><p>Weeks ago, I finally decided to download TikTok. I download the app and create a new account. The first thing I always do just after registering on a social network is upload a profile picture. Strangely, TikTok did not let me do it. I tried two more times the same day, but I had no success. After that, I also tried to add friends and change my username, but still no success. I waited for a couple of days, I reopened the app, and I got this message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*fEkSmehyZW8WDjdIao8S6w@2x.jpeg" /><figcaption>Permanently banned message in Spanish.</figcaption></figure><p>I have been permanently banned from TikTok, and I don’t know why! Then I started to think. What did I do wrong? I did not post any publications or messages. I used a valid email to register, entered my real name, and tried to upload a real picture of me. I don’t believe my email and my name are a problem. What about my profile picture? Did TikTok detect it as inappropriate? Is it because I have no hair? 👨🏻‍🦲 How to find it out?</p><h3>The System I built</h3><p>Then I remembered that Amazon has a service for unsafe content detection: <a href="https://aws.amazon.com/rekognition/">Rekognition</a>; let’s try it! Additionally, you may remember <a href="https://medium.com/better-programming/generating-ai-images-with-dall-e-aws-and-unity3d-33e9b77a2b5d">this previous article</a> of mine where I created a chat in Unity showing images from Dall-E. I will reuse the interface for this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4FC521f3Cv35My1r3nIOQ.png" /></figure><p>This is how it works:</p><ul><li>The Unity client login thanks to Cognito User Pool.</li><li>The client uploads then a picture to S3.</li><li>Finally, the client calls a Lambda function that works directly with Rekognition to define if the picture contains unsafe content.</li></ul><h3>Amazon Services</h3><p>➡️ About <strong>Cognito</strong>, I created an authenticated access using a User Pool coupled with an Identity Pool. A policy attached to the authenticated role of the Identity Pool allows users to access S3 (PutObject) and Lambda (InvokeFunction). If you want to know in detail how to do it, please check this previous article of mine:</p><p><a href="https://medium.com/@alexandre.bruffa/connecting-unity3d-with-aws-services-248790ad50c0">Connecting Unity3D With AWS Services</a></p><p>➡️ The <strong>S3 Bucket</strong> is private, so nobody but the authenticated users can access it. I called it censorimagesbucket.</p><p>➡️ I wrote the <strong>Lambda</strong> function in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/721f43774e80c0b46bc1b1f3e8d88250/href">https://medium.com/media/721f43774e80c0b46bc1b1f3e8d88250/href</a></iframe><p><strong>Notes</strong>:</p><ul><li>I used <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">boto3</a>, the AWS SDK for Python, to connect with Rekognition.</li><li>I used all the Rekognition’s top-level category <a href="https://docs.aws.amazon.com/rekognition/latest/dg/moderation.html">moderation labels</a>. My face may be offensive in many ways; we never know.</li><li>I used Rekognition’s <a href="https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectModerationLabels.html">DetectModeration API</a> thanks to the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition/client/detect_moderation_labels.html#">detect_moderation_labels</a> function and the S3Object parameter.</li><li>I used the very cool Pythonic <a href="https://docs.python.org/3/library/functions.html#any">any</a> function.</li></ul><p>Don’t forget to attach to the function’s role a policy allowing access to Rekognition and S3:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ba265439c31bf2af4d7d86fcb780cdf/href">https://medium.com/media/2ba265439c31bf2af4d7d86fcb780cdf/href</a></iframe><h3>Unity</h3><p>The connection between Unity3D and Amazon services is done through the AWS SDK for .NET, as described in my <a href="https://medium.com/@alexandre.bruffa/connecting-unity3d-with-aws-services-248790ad50c0">previous article</a>. However, the function invocation is different this time because we have to send the filename to Lambda. We do it thanks to the <a href="https://docs.aws.amazon.com/lambda/latest/dg/example_lambda_Invoke_section.html">Payload</a> parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dadf9d896a32899f1e6ee39bc7469e8/href">https://medium.com/media/7dadf9d896a32899f1e6ee39bc7469e8/href</a></iframe><h3>Result</h3><p>I performed three tests: one with a picture of Bibi, my daughter’s favorite teddy bear, a picture of a <a href="https://www.freepik.com/free-photo/young-arabic-woman-with-beautiful-body-swimwear-smiling-tropical-beach_2244930.htm?query=bikini">girl wearing a bikini</a>, and a picture of myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*tNvA8rGhQ_Qr87nch4aKFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*D1zMFIfHQlKvaoOGq2S74g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*1YoYSIfzwDve19qtHjqOAA.png" /><figcaption>Three tests with the Unity application</figcaption></figure><p>It’s working great! The only unsafe content (the girl in a bikini) has been filtered successfully, and the following moderation labels have been detected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/906841fcd761ed4e981fb1515b3ee671/href">https://medium.com/media/906841fcd761ed4e981fb1515b3ee671/href</a></iframe><p>The result is very accurate, with high confidence rates.</p><h3>Conclusion</h3><p>Apparently, my face is not unsafe content! I still don’t know why I have been permanently banned from TikTok, but thanks to this misadventure, I had the opportunity to discover Amazon Rekognition and realize an implementation with Unity3D.</p><p>All ids and tokens shown in this article are fake or expired; if you try to use them, you will not be able to establish any connections.</p><p>Every code of this article has been tested using Unity 2021.3.3 and Visual Studio Community 2022 for Mac. The mobile device I used to run the Unity app is a Galaxy Tab A7 Lite with Android 11.</p><h3>Resources</h3><p>Here are all the resources mentioned in the article:</p><ul><li>The <a href="https://gist.github.com/alexandre-bruffa/9ad1fafffbc429a7ded5a5a4175074a9">Lambda function</a> in Python</li><li>The <a href="https://gist.github.com/alexandre-bruffa/1cc3ef280c25bf28abd4754661c4a3a6">Lambda policy</a> attached to the Lambda role</li><li>The <a href="https://gist.github.com/alexandre-bruffa/ecf63ad0c7084cf6e6c0129d4921f203">Cognito policy</a> attached to the Cognito role</li><li>The <a href="https://drive.google.com/file/d/1u5PjFnt62oEFbeUgF_iVLZT0hDmAL-LL/view?usp=sharing">Unity package</a> of the application</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a3829fbfbbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting Unity3D With AWS Services]]></title>
            <link>https://medium.com/@alexandre.bruffa/connecting-unity3d-with-aws-services-248790ad50c0?source=rss-81d3bee7a7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/248790ad50c0</guid>
            <category><![CDATA[aws-sdk]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Alexandre Bruffa]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 14:54:14 GMT</pubDate>
            <atom:updated>2023-07-04T03:36:25.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>3 ways of doing it!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLVMbHPVy5QSMYw_8-g6bA.jpeg" /><figcaption>Illustration by <a href="https://www.instagram.com/niimde/">Gianca Chavest</a></figcaption></figure><p><em>This article was initially published in the AWS Community Builders’ </em><a href="https://dev.to/aws-builders/connecting-unity3d-with-aws-services-1poe"><em>dev.to</em></a><em>.</em></p><p>In my <a href="https://medium.com/@alexandre.bruffa">last articles</a>, I realized direct integrations between Unity3D and AWS using the AWS SDK for .NET. I generally don’t dive into details about how the connection between Unity3D and the AWS services is made in order to focus on the primary topic. Still, it deserves a whole article because it’s not that simple!</p><p>There are many ways to access AWS resources from Unity. In this article, I will summarize three of them: using an IAM user, using a Cognito guest user, and using a Cognito authenticated user.</p><p><strong>General considerations</strong>: For this article, we will use the AWS SDK for .NET. Since Unity uses .NET Standard 2.1, you will need the .NET Standard 2.0 assemblies available <a href="https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-obtain-assemblies.html#download-zip-files">here</a> and unzip the file in your Unity project’s Plugins folder. Since we will perform asynchronous calls, you will also need the <a href="https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces/">AsyncInterfaces</a> package.</p><p>If you prefer to watch a video instead of reading this article, here you have!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIW1b30AbiLw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIW1b30AbiLw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIW1b30AbiLw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a241625a0f58eafe55b5f2ca7b9934f7/href">https://medium.com/media/a241625a0f58eafe55b5f2ca7b9934f7/href</a></iframe><h3>1. Using an IAM User</h3><p>Suppose you want to allow a specific user (i.e., a third-party app) to upload files to one of your S3 buckets. However, you only want to give programmatic access without implementing a signup or login flow. Using an IAM user is a perfect fit in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JRLMoJXK-YYSxmOD.png" /></figure><p>Let’s simulate the process:</p><p>- In the S3 console, create a new S3 private bucket. I will call mine awsresourcesbucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wbR7PzuJ9gQ7Gcf6.png" /></figure><p>- In the IAM console, create an IAM user with programmatic access and create a new Access Key; you will be given an Access Key and a Secret Access Key. Once created, don’t forget to copy the Secret Access Key. It is shown just one time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*bePsngYTdM-eStBs.png" /></figure><p>- Attach a new policy to the IAM user. The policy gives the required permissions to write into the S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*OCoOaoeIJfL_hgDM.png" /></figure><p>- In Unity, build an S3 Client thanks to the IAM user’s Access Key and Secret Access Key, and upload the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3933e099b84d012cc7171d38059f809/href">https://medium.com/media/c3933e099b84d012cc7171d38059f809/href</a></iframe><p>Comments about the above code:<br>- We use the <a href="https://assetstore.unity.com/packages/tools/integration/native-gallery-for-android-ios-112630">NativeGallery package</a> to pick an image from the device.<br>- We use the <a href="https://docs.aws.amazon.com/sdkfornet/latest/apidocs/items/MS3S3PutObjectAsyncPutObjectRequestCancellationTokenNET45.html">PutObjectAsync</a> function as described in the <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/example_s3_PutObject_section.html">AWS documentation</a>.<br>- The function UploadFileAsync is asynchronous; you can call it with the await operator inside an async function.</p><h3>2. Using a Cognito Guest User</h3><p>You may remember my <a href="https://medium.com/better-programming/building-a-real-time-multiplayer-game-with-unity3d-and-amazon-gamelift-228f706cfbec">last article</a>, where I built a real-time multiplayer game with Unity3D and Amazon GameLift. The Unity client calls a Lambda function to start playing, and we want that everybody who has downloaded the game can play without being logged in. You can achieve it using guest users of a Cognito Identity Pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-vctyrhjXnsTX4Ir.png" /></figure><p>Let’s simulate it:</p><p>- In the Lambda console, create a simple Lambda function returning a dummy value (I will call it `awsResourcesFunction`). I will do it in Python, but it’s up to you to choose your favorite programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*uEjkNV7LaQTtPE_R.png" /></figure><p>- In the Cognito console, create a Cognito Identity Pool with guest access. During the Pool creation, you will be asked to create a new guest role; I will call them respectively awsResourcesIdentityPool and awsResourcesCognitoRole.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*C46mEpF4cpUpSgq_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*EikefiKcwZ7qirmJ.png" /></figure><p>- Once the Identity Pool is created, enter the guest role and attach a new policy. The policy gives the required permissions to invoke the Lambda function we have created before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JDAW3B9uF7bKrV4T.png" /></figure><p>- In Unity, we first build the AWS Credentials thanks to the Identity Pool ID and then the Lambda Client with those credentials.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f00610a42e59cd001c9d1e0548b83a4/href">https://medium.com/media/1f00610a42e59cd001c9d1e0548b83a4/href</a></iframe><p>Comments about the above code: <br>- The <a href="https://docs.aws.amazon.com/lambda/latest/dg/API_InvokeAsync.html">AWS documentation</a> indicates that the function InvokeAsync has been deprecated, but remember that we are using the .NET Standard 2.0 assemblies, so it’s valid for us!<br>- The <a href="https://docs.aws.amazon.com/sdkfornet/latest/apidocs/items/MLambdaLambdaInvokeAsyncStringNET45.html">InvokeAsync</a> function is asynchronous; you can call it with the await operator inside an async function.</p><h3>3. Using a Cognito Authenticated User</h3><p>Now imagine that you want to allow the players of your game to upload a profile picture, but you require a login to do it. This case is a bit more complex because your game will handle guest and authenticated users. You can achieve it by creating a User Pool and adding authenticated access to our Identity Pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UA-3IKJATuNOCXMC.png" /></figure><p>Let’s try:</p><p>- In the Cognito console, create a new User Pool. You also be asked to create an Application Client during the User Pool creation. Don’t forget to enable the ALLOW_USER_PASSWORD_AUTH as authentication flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zmaZCp1Rw4Ux4iJ8.png" /></figure><p>- For this example, we assume we already have a user registered and confirmed. Please take a look at this <a href="https://medium.com/better-programming/signing-up-users-from-unity3d-to-aws-cognito-using-the-aws-sdk-for-net-4a45f3a5f1fc">article</a> of mine to learn how to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*dbkEjce0sPYLIO_S.png" /></figure><p>- Then, go back to the Identity Pool we created before, click on “Add identity provider” of the Authenticated access section, choose “Amazon Cognito User Pool”, and link the Cognito User Pool we have created previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NFifF3tuQ_b4kxuN.png" /></figure><p>- Go then to “Edit role”, create a new role, and attach a new policy to the role (or you can reuse the policy we created for the IAM User). The policy gives the required permissions to write into the S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*64ldseVTIuoNVGTJ.png" /></figure><p>- In Unity, we first login to the Cognito User Pool with the user Credentials; a Token ID is returned. Then we build the AWS Credentials thanks to the Identity Pool ID, and we add the login data to the AWS Credentials: the `Token ID` and the User Pool Provider Name. We can finally build the S3 Client with the AWS Credentials and upload a file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4545cf954de7bf868cac6b7b7fc413ae/href">https://medium.com/media/4545cf954de7bf868cac6b7b7fc413ae/href</a></iframe><p>Comments about the above code:</p><p>- We log in to the Cognito User Pool thanks to the <a href="https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CognitoIdentityProvider/MCognitoIdentityProviderInitiateAuthInitiateAuthRequest.html">InitiateAuthAsync</a> function.<br>- We add the login data to the AWS Credentials thanks to the <a href="https://docs.aws.amazon.com/sdkfornet/latest/apidocs/items/MCognitoIdentityCognitoAWSCredentialsAddLoginStringStringNET45.html">AddLogin</a> function.<br>- The Provider Name is the concatenation of the following: cognito-idp + region + .amazonaws.com/ + Cognito User Pool ID.</p><h3>Final Thoughts</h3><p>Connecting Unity3D with AWS services is challenging work; I hope that this article could help you!</p><p>All ids and tokens shown in this article are fake or expired; if you try to use them, you will not be able to establish any connections.</p><p>Every code of this article has been tested using Unity 2021.3.3 and Visual Studio Community 2022 for Mac. The mobile device I used to run the Unity app is a Galaxy Tab A7 Lite with Android 11.</p><p>A special thanks to <a href="https://www.instagram.com/niimde/">Gianca Chavest</a> for designing the fantastic illustration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=248790ad50c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>