<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[GamerzDan]]></title><description><![CDATA[Small Indie Game Development Studio From India]]></description><link>https://gamerzdan.com/</link><image><url>https://gamerzdan.com/favicon.png</url><title>GamerzDan</title><link>https://gamerzdan.com/</link></image><generator>Ghost 3.31</generator><lastBuildDate>Mon, 14 Apr 2025 10:22:23 GMT</lastBuildDate><atom:link href="https://gamerzdan.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)]]></title><description><![CDATA[Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP).  We will keep this blog post quite straight forward, for in-depth details and explanation, please watch our above video instead.  ]]></description><link>https://gamerzdan.com/setting-up-a-server-backend-for-your-unity3d-game-using-lemp-linux-nginx-mysql-php/</link><guid isPermaLink="false">60eea880a0519301efc8ebbb</guid><category><![CDATA[tutorial]]></category><category><![CDATA[cloud]]></category><category><![CDATA[database]]></category><category><![CDATA[gamedev]]></category><category><![CDATA[multiplayer]]></category><category><![CDATA[unity3d]]></category><category><![CDATA[server]]></category><category><![CDATA[linux]]></category><dc:creator><![CDATA[Shubhank  Gaur]]></dc:creator><pubDate>Wed, 14 Jul 2021 13:33:31 GMT</pubDate><media:content url="https://gamerzdan.com/content/images/2021/07/vlcsnap-2021-07-14-02h51m50s550.png" medium="image"/><content:encoded><![CDATA[<figure class="kg-card kg-embed-card"><iframe width="356" height="200" src="https://www.youtube.com/embed/txUS7VZRYfo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><img src="https://gamerzdan.com/content/images/2021/07/vlcsnap-2021-07-14-02h51m50s550.png" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"><p>We will keep this blog post quite straight forward, for in-depth details and explanation, please watch our above video instead.  </p><p><strong>Links referenced in the Video:</strong><br>-Turn-Based RPG Template on Unity Assetstore:<br> https://assetstore.unity.com/packages/templates/systems/turnbase-rpg-template-107578<br>-PHP Webservice for the above template: <br>https://github.com/insthync/rpg-php-service<br>-Puttygen (to generate SSH keys): <br>https://www.puttygen.com/<br>-MobaXTerm (SSH Client, to connect to your server):<br> https://mobaxterm.mobatek.net/ <br>-HeidiSQL (Desktop Client to manage your SQL database, preferred over PHPMYADMIN): <br>https://www.heidisql.com/</p><hr><h2 id="creating-the-cloud-server-instance-">Creating the Cloud Server (instance)</h2><p>Our cloud provider of choice is Scaleway (Elements), not just because they are cheaper, provide unmetered bandwidth traffic but also because they are the most easiest to use, specially their dashboard/panel. <br>The server we will use in this guide costs less than Euro 2 for 1GB Ram, 10GB SSD, 1 Core and a public IP with unmetered traffic.<br>All in all, they provide the most value for money and what we personally use for a lot of our projects.<br>DISCLAIMER: We are not sponsored or affiliated with them in any way.</p><p>Sign up for a account at Scaleway Elements</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.scaleway.com/en/elements/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Scaleway Elements | A Complete Cloud Ecosystem</div><div class="kg-bookmark-description">Scaleway Elements is a single way to create, deploy and scale your infrastructure in the cloud. We help thousands of businesses to run their infrastructures easily.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.scaleway.com/favicon/apple-touch-icon-180x180.png" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"><span class="kg-bookmark-publisher">Scaleway</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.scaleway.com/scaleway-og.jpg" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></div></a></figure><p>If not redirected automatically after account creation, login to their Console (Dashboard) here:</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://console.scaleway.com/project"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Scaleway Elements Console</div><div class="kg-bookmark-description">Begin your Journey in the Public Cloud and start scaling with us</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://console.scaleway.com/favicon/apple-touch-icon-180x180.png" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></div></div><div class="kg-bookmark-thumbnail"><img src="https://console.scaleway.com/social.png" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></div></a></figure><p>In the video, we went straight to creating our instance, but we first need to setup our SSH keys which we can assign and use during server creation. <br>SSH keys are like a two part file-based security system, where you provide one public file to the server and then use a private file while connecting to the server via SSH. </p><p>Its a better form of security system than plain-text password system and quite the standard when it comes to server security and access.</p><p>Download and open PuttyGen (link at top of this post).<br>Make sure type of key is set to SSH2-RSA2 and click generate. Move your mouse in the empty space to generate the key. <br>Then save the public key and private key separately (name them so you can recognize which is which). </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2021/07/vyCAfEFZFe.gif" class="kg-image" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"><figcaption>Puttygen Generate SSH RSA2 keys</figcaption></figure><p>There is one more step involved using Puttygen which we missed in the video. You need to convert your saved Private Key to OPENSSH format and re-save it again.<br>This OPENSSH format private key is what we will use in our SSH client to connect to our server.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2021/07/myGDNZZefK.gif" class="kg-image" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"><figcaption>Convert/Generate OPENSSH format private key</figcaption></figure><p>Now lets add our SSH key to the Scaleway Console so it can be used while creating our server. <br>Head over to Profile-&gt;Credentials in Scaleway Console (or click below link).</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://console.scaleway.com/project/credentials"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Scaleway Elements Console</div><div class="kg-bookmark-description">Begin your Journey in the Public Cloud and start scaling with us</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://console.scaleway.com/favicon/apple-touch-icon-180x180.png" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></div></div><div class="kg-bookmark-thumbnail"><img src="https://console.scaleway.com/social.png" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></div></a></figure><p>Click Add a New SSH Key and paste the contents of the Public Key we generated and saved earlier (you can open that file in Notepad to copy its content).<br>Give your SSH Credential a name and add it.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2021/07/chrome_P91JEjMQoK.png" class="kg-image" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)" srcset="https://gamerzdan.com/content/images/size/w600/2021/07/chrome_P91JEjMQoK.png 600w, https://gamerzdan.com/content/images/size/w1000/2021/07/chrome_P91JEjMQoK.png 1000w, https://gamerzdan.com/content/images/size/w1600/2021/07/chrome_P91JEjMQoK.png 1600w, https://gamerzdan.com/content/images/2021/07/chrome_P91JEjMQoK.png 1671w" sizes="(min-width: 720px) 720px"><figcaption>Adding our public SSH Key to Scaleway Console</figcaption></figure><p>SSH part all done. Let's move towards creating our instance.</p><ul><li>Click on Instances on your left sidebar, under Compute.</li><li>Create an Instance.</li><li>Change Availability Zone to Amsterdam (Stardust, their cheapest instance type is only available there at present).</li><li>Choose Ubuntu 20.04 as OS/Instance Image.</li><li>Select Stardust in Instance Type.</li><li>Enter name of your Instance and relevant tags (OPTIONAL).</li><li>Make sure the SSH key we added earlier is shown here.</li><li>Make sure the ESTIMATED COST for 1 Month shows below 2 Euro (which includes a public IP).</li><li>Create a new instance.</li></ul><figure class="kg-card kg-image-card"><img src="https://gamerzdan.com/content/images/2021/07/GFxd1XKpzA.gif" class="kg-image" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></figure><p>Congratulations, we have our Linux/Ubuntu server created now. Time to move to next step, connecting to it and setting it up</p><hr><h2 id="connect-to-our-server-instance-and-set-it-up">Connect to our server instance and Set it up</h2><p>You can use any SSH client of your choice to connect to your server (Putty being most popular), we will use MobaXTerm which is our favorite (link at top reference box).</p><ul><li>Download, install and Open MobaXTerm.</li><li>Click Sessions tab, enter your server's <strong>public IP</strong> (copy it from the Console) in Remote Host, enter <strong>root </strong>as username.</li><li>Click Advanced SSH settings tab below. Check mark <strong>Use private key.</strong></li><li>Click the <strong>browse </strong>button and select the previously saved <strong>SSH Private Key (OPENSSH).</strong></li><li>Click OK to save your server's profile and it should connect automatically.</li></ul><figure class="kg-card kg-image-card"><img src="https://gamerzdan.com/content/images/2021/07/tTsQ7NHy6K.gif" class="kg-image" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></figure><p>Once connected, lets do some initial setup of our server.<br>From here onwards, you can just keep copy-pasting the server commands from this post in your MobaXTerm (shift + insert or right click in it to paste the command).</p><!--kg-card-begin: markdown--><pre><code># Update Server Repos
apt update
# Install Zip/Unzip and VNStat for bandwidth monitoring and iftop for traffic
apt install -y zip unzip vnstat iftop
</code></pre>
<!--kg-card-end: markdown--><p>!! (OPTIONAL FOR YOU) !!<br>Make a sub-directory in /home (home directory) to download and unzip our backend service's code</p><pre><code>cd /home
mkdir rpg
cd rpg
# Download
wget "https://github.com/insthync/rpg-php-service/archive/refs/tags/1.18.zip"
# Unzip files and move them
unzip 1.18.zip
ls
# Move all files from rpg-php-service folder to current folder
mv rpg-php-service/* ./</code></pre><hr><h2 id="install-and-setup-nginx-webserver-and-php">Install and Setup Nginx webserver and PHP</h2><p>Let's install Nginx Webserver and PHP and some of its modules</p><pre><code>apt install -y nginx php-fpm php-mbstring php-curl php-intl php-xml php-json php-mysqlnd php-mysql
phpenmod mbstring</code></pre><p>Configure Nginx Webserver to serve PHP/HTML files on our server's Public IP from our backend's directory (/home/rpg)</p><pre><code># If asked which editor to use, choose nano
nano /etc/nginx/sites-enabled/default</code></pre><p>Delete everything in that file, replace it with below content (copy-paste it) and press Ctrl + W and Enter to save the file changes</p><pre><code>server {
	listen 80 default_server;
    
    # The directory from where to serve your code/content
    root /home/rpg;
    
    server_name _;
    index index.html index.php;
    
    client_max_body_size 100M;
    client_header_timeout 3000;
    client_body_timeout 3000;
    fastcgi_read_timeout 3000;
    fastcgi_buffers 8 128k;
    fastcgi_buffer_size 128k;
    
    
    location / {
    	try_files $uri $uri/ /index.php;
    }
    
    location ~ \.php$ {
    	#Uncomment below line if nginx reports fastcgi-php.conf missing
        #include fastcgi_params;
        #Comment below line if using above, should only use one of them
    	include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

}</code></pre><p>Press Ctrl + W to save the file. <br>Run below commands to test your nginx changes (conf file) and restart the webserver.</p><pre><code>#This checks that your nginx conf is all good, if so, restart the nginx server
nginx -t
service nginx restart</code></pre><hr><h2 id="install-and-setup-mysql-database-server">Install and Setup MySQL Database Server</h2><pre><code>apt update
apt install software-properties-common -y
apt install mariadb-server -y</code></pre><p>MySQL (mariadb) is now installed, lets run its post-installation security script</p><pre><code>mysql_secure_installation</code></pre><ul><li>Press enter when asked for root password as initially its blank</li><li>Press Y and enter to change root password, enter your new password and press enter to save</li><li>Keep pressing Y to everything else</li></ul><p>Let's login to MySQL to create our Database and assign it a user to access it</p><pre><code>mysql -u root</code></pre><p>Please note that below are normal SQL queries to create a database, create a user with password and then assign privileges on that database to that user</p><pre><code class="language-SQL">create database rpgDB;
CREATE USER 'rpg_user'@'%' IDENTIFIED BY 'passwordhere';
GRANT ALL ON rpgDB.* TO 'rpg_user'@'%';
FLUSH PRIVILEGES;
QUIT;</code></pre><p>Then you can use the above created database and its user info in the configuration file of your backend service (shown in video, skipped here).</p><hr><h2 id="-optional-install-phpmyadmin-to-manage-your-database">(OPTIONAL) Install PHPMYADMIN to manage your database</h2><p>PHPMYADMIN is a well known GUI-based database management tool, but we personally recommend using a desktop-client based management tool like HeidiSQL (shown in video).</p><p>Nevertheless, here is how you install PHPMYADMIN, to hide and secure our phpmyadmin's access, please change <strong>hiddenmysql </strong>to whatever directory name you want.</p><pre><code>apt install -y phpmyadmin
ln -s /usr/share/phpmyadmin /home/rpg/hiddenmysql</code></pre><p>Your PHPMYADMIN will be accessible at http://YOURPUBLICIP/hiddenmysql</p><p>If you get a count or count-related error in phpmyadmin, please follow these steps</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://stackoverflow.com/questions/48001569/phpmyadmin-count-parameter-must-be-an-array-or-an-object-that-implements-co"><div class="kg-bookmark-content"><div class="kg-bookmark-title">phpmyadmin - count(): Parameter must be an array or an object that implements Countable</div><div class="kg-bookmark-description">I’ve uploaded the backup to a table, opening the table I see this: Warning in ./libraries/sql.lib.php#601count(): Parameter must be an array or an object that implements Countable Backtrace ./</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v&#x3D;c78bd457575a" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"><span class="kg-bookmark-author">alebal</span><span class="kg-bookmark-publisher">Stack Overflow</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon@2.png?v&#x3D;73d79a89bded" alt="Setting up a server backend for your Unity3D Game using LEMP 
(Linux, Nginx, MySQL, PHP)"></div></a></figure><p>*Please do restart the services using below step before trying to access your backend code or even phpmyadmin</p><hr><p>Let's do a final restart of all our services</p><pre><code>service nginx restart
service php7.4-fpm restart
service mysql restart</code></pre><p>All done, enjoy.</p>]]></content:encoded></item><item><title><![CDATA[Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)]]></title><description><![CDATA[Introduction to using Firestore Cloud Database by Firebasse for Game Development with Unity3D (Part 1/4)]]></description><link>https://gamerzdan.com/using-firebase-cloud-firestore-with-unity3d-introduction/</link><guid isPermaLink="false">5f4d83d03850d7022f0e5da8</guid><category><![CDATA[unity3d]]></category><category><![CDATA[firebase]]></category><category><![CDATA[firestore]]></category><category><![CDATA[tutorial]]></category><category><![CDATA[gamedev]]></category><category><![CDATA[cloud]]></category><category><![CDATA[database]]></category><dc:creator><![CDATA[Shubhank  Gaur]]></dc:creator><pubDate>Mon, 31 Aug 2020 23:16:43 GMT</pubDate><media:content url="https://gamerzdan.com/content/images/2020/08/Firebase_Tasks.png" medium="image"/><content:encoded><![CDATA[<img src="https://gamerzdan.com/content/images/2020/08/Firebase_Tasks.png" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)"><p>I am a one man army right now in my small indie game studio (GamerzDan) out of India (Registered in US as GamerzDan, Inc.), so I generally do not put my time to create these kind of guides or tricks/tips as a programmer or YouTube videos, I use most of my time prototyping and programming in general.  </p><p>But recently due to my need of a backend database for our upcoming <strong>Chess Game "Shatranj"</strong> and my interest in going for a Cloud solution instead of a self-hosted one (server+mysql+php/api) which I normally self-create and use, I decided to look into <strong><a href="https://firebase.google.com/">Google Firebase</a></strong>, which is a suite of Backend as a Service products for apps and in general.  <br>Now, I have known and been aware of Firebase since years even before being into game development, or app development before it. But I never actually ended up using it for any of my client or production projects so this was my first time actually diving into it.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/image-1.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/image-1.png 600w, https://gamerzdan.com/content/images/size/w1000/2020/09/image-1.png 1000w, https://gamerzdan.com/content/images/2020/09/image-1.png 1280w" sizes="(min-width: 720px) 720px"><figcaption>Both Cloud Firestore and Realtime Database are cross platform, so as a Unity Developer it means you can use both products on Desktop and Mobile devices seemlessly.</figcaption></figure><hr><p>Table of Contents</p><ul><li><a href="#introductiontorealtimedatabaseandcloudfirestore">Introduction to Realtime Database and Cloud Firestore</a></li><li><a href="#differencebetweenrealtimeandfirestoredatabases">Differences between Realtime and Firestore Databases</a></li><li><a href="#pricingmodelofrealtimeandfirestoredatabases">Pricing model of Realtime and Firestore Databases</a></li><li><a href="#codedifferenceandapproachbetweenrealtimeandfirestoredatabase">Code Difference and Approach between Realtime and Firestore Database</a></li><li><a href="#followuppartsofthisguide">Followup Parts of this guide</a></li></ul><hr><!--kg-card-begin: markdown--><h2 id="introductiontorealtimedatabaseandcloudfirestore">Introduction to Realtime Database and Cloud Firestore</h2>
<!--kg-card-end: markdown--><figure class="kg-card kg-embed-card"><iframe width="612" height="344" src="https://www.youtube.com/embed/Zw2ojPq9IQc?start=120&feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p>I was interested in Firebase's cloud database solutions, of which the most popular being <a href="https://firebase.google.com/products/realtime-database"><strong>Realtime Database</strong></a> and other more powerful, newer and state of the art solution being <strong><a href="https://firebase.google.com/products/firestore">Cloud Firestore</a></strong>.<br>Due to lack of general information available for Cloud Firestore and Firebase's docs seeming quite intimidating, I looked into Realtime Database first for my specific needs but pretty soon realized its not for me due to how it works, how the <u>data is structured (JSON eww)</u> and some of its other limitations I felt from my understanding, compared to which Cloud Firestore just seemed a perfect replacement for anyone currently using or being used to old school RDBMS like MySQL.  </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/image.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/image.png 600w, https://gamerzdan.com/content/images/2020/09/image.png 700w"><figcaption>Unlike Realtime Database which uses a flat text data structure in form of JSON, Cloud Firestore uses a data structure similar to MySQL where we have collections (tables), which contain documents (records/rows) and documents which contain our actual data in key-value form (aka columns)</figcaption></figure><hr><!--kg-card-begin: markdown--><h2 id="differencebetweenrealtimeandfirestoredatabases">Difference between Realtime and Firestore Databases</h2>
<!--kg-card-end: markdown--><p>I have discussed the major differences in my attached Youtube Video (again, as per my understanding and needs) and why as a GameDev or AppDev in general you should avoid Realtime Database and go for Cloud Firestore.  </p><figure class="kg-card kg-embed-card"><iframe width="612" height="344" src="https://www.youtube.com/embed/Zw2ojPq9IQc?start=360&feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p><br></p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/image-3.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/image-3.png 600w, https://gamerzdan.com/content/images/2020/09/image-3.png 842w" sizes="(min-width: 720px) 720px"><figcaption>Some differences between Cloud Firestore and Realtime Database and why Firestore is a better option for a App or Game developer</figcaption></figure><p>But as a refresher, differences between Realtime Database and Firestore and why to go for Cloud Firestore as a game or app developer:</p><ul><li>Realtime Database uses a JSON tree-like nested structure, your complex or large data can get really branched out or nested, harder to read for yourself and becomes hell remembering the structure while accessing it. Overall, its way different than your standard SQL database structure.<br>On other hand, Cloud Firestore uses a more SQL-relatable data structure which is key-value based (just like mysql columns and rows) and uses dictionary as the standard way to send or get data to your app. Furthermore, Firestore divides your whole data structure into Collections (Tables), Documents (columns/data header) and then fields (rows/actual data). Its easier to understand, analyze and plan your database structure and thus, saves you valuable development time as you feel more used to it and easy to remember.</li><li>Code difference, this depends on personal choice but I like key-value dictionary structure more than JSON structure, and thus, like how Firestore's code works to send or get data to your database. It feels more natural to write the code and prepare your data when its in a dictionary.</li><li>Search Query/Data Filtering, again depends on personal choice but Realtime Database plain and simple sucks for filtering data or querying on it. You can only run one Query per call and cannot club multiple conditions as easily as you can in Firestore with a single call, furthermore, Firebase themselves pride Firestore to be able to run complex and compound queries on millions of data within a second.</li><li>Data Types. Realtime Database is a flat json text data, cannot support Data Type, boo. Firestore supports almost all standard Data Types and even your custom classes, yay.</li></ul><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/image-12.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/image-12.png 600w, https://gamerzdan.com/content/images/2020/09/image-12.png 800w" sizes="(min-width: 720px) 720px"><figcaption>However, visually speaking, the actual structure of both Realtime and Firesttore Database looks almost identical</figcaption></figure><hr><!--kg-card-begin: markdown--><h2 id="pricingmodelofrealtimeandfirestoredatabases">Pricing model of Realtime and Firestore Databases</h2>
<!--kg-card-end: markdown--><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/image-4.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/image-4.png 600w, https://gamerzdan.com/content/images/2020/09/image-4.png 810w" sizes="(min-width: 720px) 720px"><figcaption>Pricing model and difference between how Firebase charges for Realtime Database and Cloud Firestore and a real world example calculation</figcaption></figure><p>Both Realtime Database and Firestore has free usage tier, which is pretty generous and chances for most apps/games are you don't need to pay a penny till your game grows and goes big.  <br>Firebase uses a Pay-As-You-Go pricing model which is neat as even for paid limits, you do not need to pay fixed costs per month and only pay as per your usage and needs (can be a few cents or a few thousand dollars).</p><figure class="kg-card kg-embed-card"><iframe width="612" height="344" src="https://www.youtube.com/embed/Zw2ojPq9IQc?start=900&feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p><br>Realtime Database has a pretty straightforward pricing model.</p><ol><li>You have a simultaneous connections limits i.e. how many apps/users can connect and run queries at once. It is 100 in free tier and 200k/database in pay-as-you-go tier. <br>By the way, that's 200k connections PER DATABASE and not per account or app, so if you are smart and pre-plan your database structure, you can spread your one big fat database into multiple databases to hold common data (one db for users, one db for matches, one db for logs, etc.) and thus can achieve even 1 Million connections at once (in real world your gonna need when you make a hit like Dota 2 or PUBG). However, in free tier you can only create 1 Database, unlimited in paid.<br></li><li>Mostly you only pay for amount of storage your data needs (1GB free tier and $5/GB paid) and amount of outgoing traffic (10GB/month free, $1/GB paid) your app uses (Firebase to your app, or data you retrieve). There is no cost for incoming data towards Firebase (Your app to Firebase, or storing data). That's sweet.<br>That data storage of 1GB is quite sufficient for most devs even across multiple projects. My bloated wordpress site's database uses 600MB~ and it has 150k registered users and more than 3 Million rows of data.  <br></li><li>Only thing of actual interest is that outgoing traffic, which again, is quite sufficient even in free tier but can get out of hand if you plan your database structure or program your code poorly (like getting data every frame or in update loop). That traffic cost can cost you a fortune if your really using high amount of data, just 10GB of network can cost you $10 and as a example, that same bloated wordpress database I mentioned above uses 250GB PER DAY (so in Realtime Database terms, thats $250 per day). Now obviously wordpress is a bloated platform, database is not as optimized and its a large database but you get the picture. As I self host it myself (server+mysql), I really only pay around $10~ PER MONTH. I mean, if I were hosting that same database on Realtime, I would be using 7720GB network per month, so $7k charge.</li></ol><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/chrome_MpIZQTeMsE.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/chrome_MpIZQTeMsE.png 600w, https://gamerzdan.com/content/images/size/w1000/2020/09/chrome_MpIZQTeMsE.png 1000w, https://gamerzdan.com/content/images/2020/09/chrome_MpIZQTeMsE.png 1049w" sizes="(min-width: 720px) 720px"><figcaption>Firebase Realtime Database Pricing - Free and Pay as you Go</figcaption></figure><hr><p><strong>Now comes the more interesting one, Cloud Firestore pricing model, not as easy to understand at first.</strong></p><ol><li>There are no connection limits in Firestore, 1 user, 10 users or 10 million users, Firestore can handle it all.</li><li>Just like Realtime, we get 1GB storage in free plan however, we only pay $0.18/GB for extra storage we use. Comparing it to Realtime's $5/GB, this is dirt cheap.<br>Now there is a argument as Realtime uses flat text data in json and Firestore uses Data Types and key-value, Firestore uses more storage for same amount of data compared to Realtime. That is true. But lets be honest, how much would extra storage would that be ? 2x times? 5x times? Even with 5x times, you pay $0.9 for 5GB of storage. Some articles make entry level users really paranoid with Firestore costs, but when you calculate it using Real World use case and examples, one can even argue it costs less than Realtime.</li><li>Just like Realtime, we also pay for network, only outgoing traffic (data retrieved) and not incoming traffic towards firebase (data store/sent, its free). <br>We get 10GB/month traffic in free tier, but paid traffic has a bit more complex structure as it uses Google Cloud pricing for traffic which depends on the location your Firestore database is hosted (US, EU, Asia, etc.)<br>However, as a real world example, lets suppose we store our Firebase Database in Europe (EU) region as I consider it more central to handle Asian and American user traffic. <br>* All incoming traffic towards Firebase servers is free.<br>* All outgoing traffic from Firebase towards your users/apps in same region is Free i.e. all traffic to all our users in Europe is free<br>* All outgoing traffic from Firebase towards users in US is charged flat at $0.01/GB and this is regardless of which primary region you host your database, so if you chose Asia you pay same rate for all traffic used by US users. However, if you choose US as your database location, you pay nothing due to same region rule.<br>* All outgoing traffic from Firebase towards users in any region except US or your database region (EU) costs you between $0.1-$0.2/GB depending on which country/region the user is from. For example, Singapore is $0.1/GB while China is $0.2/GB<br>Even if you consider the higher limit of $0.2/GB, its still cheaper than Realtime cost of $1/GB. Basically in same $1 amount, you get 5GB network (minimum) to 10GB or more depending on your user's location and which location you decide to store your Firestore database in.</li><li>Other than network, you also get free usage and paid usage for amount of Read, Write and Delete operations you make on your database. These limits are per day and fairly generous.  <br><strong><u>Read operations are 50k/day free and $0.06/100k paid<br>Write operations are 20k/day free and $0.18/100k paid<br>Delete operations are 20k/day free and $0.02/100k paid</u></strong><br><br>Taking my chess game as a example, if I have 500 users online and playing at  per day (250 matches) and each match I need to send/store 100 moves on average, I need to make 250 x 100 = 25,000 write operations each day, which are almost within my free tier limit. Even when I cross the 20k limit, I am paying $0.06 for the next 100k I use. Do note that the above example uses extreme write operations because I know for a fact I won't be making 100 move calls per match and if I need to, I can just store all the moves in a large dictionary and make a single call to send all that data at once after the match ends instead of 100 individual write operations.  </li></ol><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://gamerzdan.com/content/images/2020/09/chrome_3ZAvh8yir5.png" class="kg-image" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/chrome_3ZAvh8yir5.png 600w, https://gamerzdan.com/content/images/size/w1000/2020/09/chrome_3ZAvh8yir5.png 1000w, https://gamerzdan.com/content/images/2020/09/chrome_3ZAvh8yir5.png 1329w" sizes="(min-width: 720px) 720px"><figcaption>Firebase Cloud Firestore Pricing - Free Tier and Paid Tier</figcaption></figure><figure class="kg-card kg-gallery-card kg-width-wide kg-card-hascaption"><div class="kg-gallery-container"><div class="kg-gallery-row"><div class="kg-gallery-image"><img src="https://gamerzdan.com/content/images/2020/09/chrome_aK9fg7uNIm.png" width="1308" height="871" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/chrome_aK9fg7uNIm.png 600w, https://gamerzdan.com/content/images/size/w1000/2020/09/chrome_aK9fg7uNIm.png 1000w, https://gamerzdan.com/content/images/2020/09/chrome_aK9fg7uNIm.png 1308w" sizes="(min-width: 720px) 720px"></div><div class="kg-gallery-image"><img src="https://gamerzdan.com/content/images/2020/09/chrome_nJ6oXhTaxM.png" width="1331" height="513" alt="Using Firebase Cloud Firestore with Unity3D - Introduction (1/4)" srcset="https://gamerzdan.com/content/images/size/w600/2020/09/chrome_nJ6oXhTaxM.png 600w, https://gamerzdan.com/content/images/size/w1000/2020/09/chrome_nJ6oXhTaxM.png 1000w, https://gamerzdan.com/content/images/2020/09/chrome_nJ6oXhTaxM.png 1331w" sizes="(min-width: 720px) 720px"></div></div></div><figcaption>Firebase Cloud Firestore Network Traffic Pricing - Only outgoing traffic from Firebase servers to your app is counted</figcaption></figure><p>Believe me, free tier is very generous and chances are you will hardly need more than that. Furthermore, here is icing on cake, any and all pay as you go charges are ABOVE and AFTER your free tier limit. <br>If you use 20GB bandwidth a month, 10GB will be free as part of free tier and you pay for 10GB.<br>If you make 25k or even 50k write operations a day, 20k of those will be free and only the difference will be counted from the 100k you get for $0.06 (which btw is not even per day and as a total amount of credits whether you use 10k from 100k per day or per week).<br><br>More Google Cloud Info on Pricing here - <br><a href="https://firebase.google.com/pricing">https://firebase.google.com/pricing</a><br><a href="https://cloud.google.com/firestore/pricing">https://cloud.google.com/firestore/pricing</a><br><a href="https://cloud.google.com/firestore/pricing#internet-egress">https://cloud.google.com/firestore/pricing#internet-egress</a></p><hr><!--kg-card-begin: markdown--><h2 id="codedifferenceandapproachbetweenrealtimeandfirestoredatabase">Code Difference and Approach between Realtime and Firestore Database</h2>
<!--kg-card-end: markdown--><p>The reason many entry-level devs avoid Firestore and why there is such a huge lack of tutorials, guides, examples or resources on using Firestore with Unity, is how confusing Firebase's docs for Firestore are and how bad their actual code examples are. They are even bad for a boilerplate code and they should have provide some better examples and explanations for their code examples, heck even a example use case.</p><p>However, once you start getting your hands dipped into Firestore and understand how it works, how you interact with your data and its structure, how to structure your data internally in your code, Firebase is actually way way easier than Realtime Database and even SQL databases in general, once you understand and start restructuring Firebase's code examples to your own needs, it becomes a breeze to use and now I don't think I will even ever use MySQL again unless I specifically need to (example: my firebase costs start getting out of hand and I know that my costs for a self-hosted MySQL database and server will be lower).</p><figure class="kg-card kg-embed-card"><iframe width="612" height="344" src="https://www.youtube.com/embed/Zw2ojPq9IQc?start=1560&feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><hr><!--kg-card-begin: markdown--><h3 id="boilerplatecodeexampleofusingrealtimedatabaseinunity3dc">Boilerplate Code Example of using Realtime Database in Unity3D (C#)</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Add/Save Data to Realtime Database</p>
<pre><code>mDatabaseRef.Child(&quot;users&quot;).Child(userId).SetRawJsonValueAsync(json);
mDatabaseRef.Child(&quot;users&quot;).Child(userId).Child(&quot;username&quot;).SetValueAsync(name);
</code></pre>
<p>Get/Retrieve Data from Realtime Database</p>
<pre><code>FirebaseDatabase.DefaultInstance
      .GetReference(&quot;Leaders&quot;)
      .GetValueAsync().ContinueWith(task =&gt; {
        if (task.IsFaulted) {
          // Handle the error...
        }
        else if (task.IsCompleted) {
          DataSnapshot snapshot = task.Result;
          // Do something with snapshot...
        }
      });
</code></pre>
<p>Filtering Data (Query/Search) in Realtime Database</p>
<pre><code> FirebaseDatabase.DefaultInstance
        .GetReference(&quot;Leaders&quot;).EqualTo(&quot;score&quot;).LimitToLast(1)
    }
</code></pre>
<p>^^The EqualTo that checks for score on what or where, no explanation provided, heck even above code example is created by me as Realtime Database has 0 actual code snippets on Filtering Data:<br>
<a href="https://firebase.google.com/docs/database/unity/retrieve-data#filtering_data">https://firebase.google.com/docs/database/unity/retrieve-data#filtering_data</a></p>
<!--kg-card-end: markdown--><p><a href="https://firebase.google.com/docs/database/unity/retrieve-data#filtering_data">Yeah, thats all code example and doc Firebase provide for using Filtering/Query/Search in Realtime Database</a></p><hr><!--kg-card-begin: markdown--><h3 id="boilerplatecodeexamplesofusingcloudfirestoreinunity3dc">Boilerplate Code Examples of using Cloud Firestore in Unity3D (C#)</h3>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p>Add/Save Data to Cloud Firestore</p>
<pre><code>DocumentReference docRef = db.Collection(&quot;cities&quot;).Document(&quot;LA&quot;);
Dictionary&lt;string, object&gt; city = new Dictionary&lt;string, object&gt;
{
        { &quot;Name&quot;, &quot;Los Angeles&quot; },
        { &quot;State&quot;, &quot;CA&quot; },
        { &quot;Country&quot;, &quot;USA&quot; }
};
docRef.SetAsync(city).ContinueWithOnMainThread(task =&gt; {
        Debug.Log(&quot;Added data to the LA document in the cities collection.&quot;);
});
</code></pre>
<p>Get/Retrieve Data from Cloud Firestore</p>
<pre><code>DocumentReference docRef = db.Collection(&quot;cities&quot;).Document(&quot;SF&quot;);
docRef.GetSnapshotAsync().ContinueWithOnMainThread(task =&gt;
{
  DocumentSnapshot snapshot = task.Result;
  if (snapshot.Exists) {
    Debug.Log(String.Format(&quot;Document data for {0} document:&quot;, snapshot.Id));
    Dictionary&lt;string, object&gt; city = snapshot.ToDictionary();
    foreach (KeyValuePair&lt;string, object&gt; pair in city) {
      Debug.Log(String.Format(&quot;{0}: {1}&quot;, pair.Key, pair.Value));
    }
  } else {
    Debug.Log(String.Format(&quot;Document {0} does not exist!&quot;, snapshot.Id));
  }
});
</code></pre>
<p>Query/Filter/Search Data in Cloud Firestore Database</p>
<pre><code>CollectionReference citiesRef = db.Collection(&quot;cities&quot;);
Query query = citiesRef.WhereEqualTo(&quot;State&quot;, &quot;CA&quot;);
query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask) =&gt;
{
    foreach (DocumentSnapshot documentSnapshot in querySnapshotTask.Result.Documents)
    {
        Debug.Log(String.Format(&quot;Document {0} returned by query State=CA&quot;, documentSnapshot.Id));
    } 
});
</code></pre>
<p>Point to note is that even the above provide Code Snippets in Firebase Firestore docs are quite unexplaining and can be confusing to entry level devs switching from MySQL or other databases.<br>
However, once you start understanding how the data is structured in Firestore, how to structure your own data, which Firestore methods to use for what purpose, you will realize that actual real world use code of Firestore is quite simple and human readable.<br>
We will see more actual code examples that I have created and using in our own <strong>Chess Game Shatranj</strong> in followup posts but here is a example:</p>
<p>My way of adding new data to my <strong>Moves</strong> Collection/Table, I am passing the document name I want to use as <strong>matchid</strong> and a <strong>Dictionary&lt;string, object&gt; userData</strong> with actual data to send and store.<br>
I have saved references to both <strong>FirebaseFirestore</strong> object and my moves <strong>CollectionReference</strong> in <strong>moves</strong> object so I can use a single keyboard to access that instead of <strong>db.Collection(&quot;moves&quot;).Document(matchid)</strong></p>
<pre><code>internal void fsAddToMoves(string matchid, Dictionary&lt;string, object&gt; userData)
    {
        DocumentReference docRef = moves.Document(matchid);  //This should always be unique or else will be overwritten

        //Show loading bar UI
        docRef.SetAsync(userData).ContinueWithOnMainThread(task =&gt;
        {
            //Executed when updation done, probably disable your loading progress here
            //Disable Loading bar UI

            if (task.IsFaulted)
            {
                Debug.Log(&quot;Updating move failed &quot; + task.Exception.InnerException.Message); //probably userdata.userid is blank
            }
            else
            {
                Debug.Log(&quot;Moves updated: &quot; + docRef.Id);
            }
        });
    }

</code></pre>
<p>Boilerplate Code version</p>
<pre><code>void addData(documentTitle, data){
moves.Document(documentTitle).SetAsync(data).ContinueWithOnMainThread(task =&gt;
        {
            //Task completed, check if it finished and data saved success
        }
}
</code></pre>
<!--kg-card-end: markdown--><hr><!--kg-card-begin: markdown--><h3 id="followuppartsofthisguide">Followup Parts of this guide</h3>
<p>Part 2/4: Adding/Saving Data to Cloud Firestore<br>
Part 3/4: Getting/Retrieving Data from Cloud Firestore<br>
Part 4/4: Quering, Filtering and Searching Data and Nested Data Structures</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>