Getting Google Sheet Data Updates In Unity

Separating data from Unity code is one of the main ways to keep your project maintainable and resistant to change. Anyone who has experience in game development knows how quick iteration in a constantly changing universe is a necessary part of the process.

(Yes, you are the cat.)

In case your game has a substantial narrative part, facilitating writer/developer interaction is also very important; I was reminded how common is this need by a recent interview of Leigh Alexander The Most Important Part Of Writing A Video Game Is The Tools, on her writing experience for Reigns: Her Majesty.

Writing for games has specific needs and contexts (see a detailed post of mine Videogame Dialogues: Writing Tools And Design Ideas), and so its important for the writer and the developers to quickly see how the text appears in the context of gameplay.

Supposing your writer is updating a Google sheet, I provide you with a very simple way to automatically get an updated textual asset at each Unity run, so making it easy to check how it feels in game.

The solution is simple as Google lets you download any shared doc in CSV format by just requesting the correct URL; you can also specify a target sheet in a multi-sheet document. What is a little bit tricky is that whenever your writer is using newlines, commas or quotation marks, this may break the CSV format.

What is cool of the solution is that it creates a textual asset of the downloaded content, so that say as long as you are running in Unity’s editor, you download the updates, but as soon as you build, the app will use the asset.

You find a complete solution as a Gist on Github :-)

Follow me on Twitter where I post about game design, game development, Unity3d, applied / serious games.

Social Share Toolbar

Unity: Dense Auto Increment Your Build Number Across Scenes

I was looking for a way to have a build number in Unity so that:

  1. I want a “build” number to be dense, at least as dense as commits
  2. it should auto increment on run
  3. it should auto increment from whatever scene you are launching your game
  4. it should be possible to decide to show it or not in every scene
  5. it should totally take care of itself – so when I get feedback on a new build I can always ask the tester which build is she using, and I don’t go “damn it I forgot to increase the build number!!”

The idea is simply to have an editor script that changes a prefab (so that you can place it in every scene, but has a global state) each time you run. Here is my code, which you can fit to your needs (this also does the life-saving “save scene before run” which you may pick too):

// Author: Pietro Polsinelli - http://designAGame.eu
// Twitter https://twitter.com/ppolsinelli
// All free as in free beer

using TMPro;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace OL
{
    [InitializeOnLoad]
    public class AutoSaveOnRun
    {
        static AutoSaveOnRun()
        {
            //Thanks https://twitter.com/andrewlukasik for the "+=" fix.
            EditorApplication.playmodeStateChanged += () =>
            {
                if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
                {
                    GameObject build = AssetDatabase.LoadAssetAtPath("Assets/__Scripts/Tools/Components/Build/Build.prefab",
                        typeof(GameObject)) as GameObject;

                    if (build != null)
                    {
                        TextMeshProUGUI bn = build.GetComponent<TextMeshProUGUI>();
                        if (string.IsNullOrEmpty(bn.text))
                            bn.text = "1";
                        else
                        {
                            bn.text = (int.Parse(bn.text)+1).ToString();
                        }
                    }
                    
                    EditorSceneManager.SaveScene(SceneManager.GetActiveScene());
                    AssetDatabase.SaveAssets();
                }
            };
        }
    }
}

P.S. More approaches

In order to change the build on compile and not on save, I now use this code in the (also very useful) stop-play-on-compile class:

// Copyright Cape Guy Ltd. 2015. http://capeguy.co.uk.
// Provided under the terms of the MIT license -
// http://opensource.org/licenses/MIT. Cape Guy accepts
// no responsibility for any damages, financial or otherwise,
// incurred as a result of using this code.

// Modified by Pietro Polsinelli. 2017. https://twitter.com/ppolsinelli

public class ExitPlayModeOnScriptCompile
    {
        static bool increasedBuildForThisCompile;

        // Static initialiser called by Unity Editor whenever scripts are loaded (editor or play mode)
        static ExitPlayModeOnScriptCompile()
        {
            Unused(_instance);
            _instance = new ExitPlayModeOnScriptCompile();
        }

        ExitPlayModeOnScriptCompile()
        {
            EditorApplication.update += OnEditorUpdate;
        }

        ~ExitPlayModeOnScriptCompile()
        {
            EditorApplication.update -= OnEditorUpdate;
            // Silence the unused variable warning with an if.
            _instance = null;
        }

        // Called each time the editor updates.
        static void OnEditorUpdate()
        {
            if (EditorApplication.isCompiling &amp;&amp; !increasedBuildForThisCompile)
            {
                increasedBuildForThisCompile = true;

                GameObject build = AssetDatabase.LoadAssetAtPath("Assets/__Scripts/Tools/Components/Build/Build.prefab",
                    typeof(GameObject)) as GameObject;

                if (build != null)
                {
                    TextMeshProUGUI bn = build.GetComponent&lt;TextMeshProUGUI&gt;();
                    if (string.IsNullOrEmpty(bn.text))
                        bn.text = "1";
                    else
                    {
                        bn.text = (int.Parse(bn.text) + 1).ToString();
                    }
                }
            }

            if (!EditorApplication.isCompiling)            
            {
                increasedBuildForThisCompile = false;
            }

            if (EditorApplication.isPlaying &amp;&amp; EditorApplication.isCompiling)
            {
               Debug.Log("Exiting play mode due to script compilation.");
                EditorApplication.isPlaying = false;
            }
        }

        // Used to silence the 'is assigned by its value is never used' warning for _instance.
        static void Unused&lt;T&gt;(T unusedVariable)
        {
        }

        static ExitPlayModeOnScriptCompile _instance = null;
    }
}

Yet another approach is to identify the build number with a platform build (I don’t use that because I want density): https://gist.github.com/andrew-raphael-lukasik/36a30f0955d7cdc758e394dc4e7266bf.

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, applied / serious games.

 

Social Share Toolbar

A post on videogame writing tools and user interface techniques

I just published a post on Gamasutra Videogame Dialogues: Writing Tools And Design Ideas, written with the voltairesque Daniele Giardini. We write about our current experiments with writing tools and dialogue user interface design. Hope you’ll find something useful there!

Social Share Toolbar

Is Unity WebGL loading? A simple loader

F = (When you publish your Unity application or prototype in WebGL a problem that your testers or players may have is that while the browser is loading the application, no progress bar appears and so they may be tempted to reload the page again and so… F() ).

A simple fix to reassure them is to paste this script at the bottom of the index.html file that Unity produces at build:

<script>
  /**
   * Created by
   * Matteo Bicocchi @pupunzi
   * Pietro Polsinelli @ppolsinelli
   * Follow us as we are creating a game on #football 
   * with a story: "Football Voodoom" :-)
   * */

  var appName = "<b>" + Module.codeUrl.replace("Release/", "").replace(".js","") + "</b> ";
  var canvas = document.getElementsByTagName("canvas")[0];
  var canvasRect = canvas.getBoundingClientRect();

  var loader = document.createElement("div");
  loader.id = "loader";

  var loaderWidth = canvas.offsetWidth;
  var loaderHeight = canvas.offsetHeight;

  document.body.appendChild(loader);

  loader.style.position = "absolute";

  loader.style.top = 0;
  loader.style.bottom = 0;
  loader.style.left = 0;
  loader.style.right = 0;
  loader.style.margin = "auto";
  loader.style.width = loaderWidth + "px";
  loader.style.height = loaderHeight + "px";
  loader.style.background = "transparent";
  loader.style.color = "#fff";
  loader.style.opacity = 0.8;
  loader.style.fontSize = "16px";
  loader.style.letterSpacing = "3px";
  loader.style.fontWeight = "100";
  loader.style.textAlign = "left";
  loader.style.padding =  "30px";
  loader.style.boxSizing = "border-box";

  var dotCount = 0;
  var checkDisplay = setInterval(function(){

    if(Module.progress.progress > 0) {
      loader.style.display="none";
      clearInterval(checkDisplay);
    } else {

      loader.innerHTML = "Loading " + appName;

      for (var x = 0; x<dotCount; x++){
        loader.innerHTML+= ".";
      }
      
      dotCount = dotCount >= 40 ? 0 : ++dotCount;
    }
  },100)
</script>

This will show immediately “Loading…” and will animate it until the app loader appears. See it here:

Unity WebGL custom loader

Cool no? The JavaScript is really basic and should work wherever WebGL does.

 

 

 

Social Share Toolbar

Tips For The Pragmatic Unity Developer

In the video below I’ve presented several productivity tips / hacks for the great Unity3d developer, that cultivates his / her essential qualities (impatience laziness hubris):

 

Sources & References

The three most essential plugins are DOTween, Text Mesh Pro and Console Pro.

Jet Brains IDE for C# preview here.

The “auto-save on play” script is here, The “no more hot reload script” is here, both by the same cool guy.

The scene object enable and disable script is this:

public class TheScene : MonoBehaviour
    {
        public GameObject[] activateOnStartup, deactivateOnStartup;
        
        void Start()
        {
            foreach (GameObject go in activateOnStartup)
            {
                go.SetActive(true);
                if (go.GetComponent<CanvasGroup>() != null)
                    go.GetComponent<CanvasGroup>().alpha = 1;
            }
            foreach (GameObject go in deactivateOnStartup)
            {
                go.SetActive(false);
                if (go.GetComponent<CanvasGroup>() != null)
                    go.GetComponent<CanvasGroup>().alpha = 0;
            }
        }
    }

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, applied / serious games.

Social Share Toolbar

A Circular Range Control for Unity UI

I needed a circular range control to be for a project using Unity UI, and there seemed not to be one built-in, I created one. I wanted it to work on both desktop and mobile (touch). In building it I found out that to make it usable it requires quite a bit of tuning. [Read more…]

Social Share Toolbar

Untangling GameObject State in Unity

In this short post and video I try to discuss and clarify a few points about GameObject state in Unity with respect to game, scene and “runtime” scope. It is a bit more complex than one may understand initially, so bear with me a little.

When you start developing scenes in Unity, it won’t take long before you start asking questions like:

How can I get the same GameObject in different scenes?

Why do static properties sometimes get reset across scenes?

Why when I reload a scene I get duplicated objects which are meant to be singletons?

How can I comply with the (highly practical) principle “Make the game runnable from every scene” when I have global instances from other scenes?

Here are some answers.

Here is the full schema I refer to:

GameObject State in Unity

While MonoBehaviour’s  life-cycle is quite well documented e.g. both directly in Unity docs here and also by third parties e.g. here, how to handle GameObject’s persistence in and across scenes may be more obscure.

So here are written (partial) answers to the questions above:

How can I get the same GameObject in different scenes?
Would be probably better to reword this as “how can I persist and share data across scenes” – and there are many ways to do that :-)

Why do static properties sometimes get reset across scenes?
Only static properties which are GameObjects present in the scene will get reset (typically singletons). Other static properties will be preserved across the virtual machine.

Why when I reload a scene I get duplicated objects which are meant to be singletons?
That is because you marked those objects with DontDestroyOnLoad and created them (also) in other scenes. Create them via code (not in hierarchy) checking before their existence.

How can I comply with the (highly practical) principle “Make the game runnable from every scene” when I have global instances from other scenes?
This is best done just as explained above: create the global objects in every scene via code if they don’t already exist.

 

Unity Execution Order

Unity Execution Order – from Unity documentation.

If you are in need of learning some good patterns in software game development, a really nice book is Game Programming Patterns. Here are also 50 Tips for Working with Unity (Best Practices) which I reread from time to time, understanding progressively more and more of them (but still not all :D).

Thanks to Daniele Giardini for some feedback on the state scheme above.

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, applied / serious games.

Social Share Toolbar

Creating Match 3 Games in Unity

How to create quickly a match 3 game in Unity? Or any kind of match game? I have been working on an original match 3 game (an applied game actually) together with Unity 2D guru Daniele Giardini and I took some notes, which I present in the video below. This is not a tutorial: I just point out some concepts you will probably need to deal with.

Consider also that this is all done with Unity 5, which by introducing 2D, sprites (and also new UI) has made it much simpler to create this kind of games. And as in all my games, its actually Unity plus Gamelogic Grids component, as in my models (and probably in games in general) grids are pervasive.

Here is the video:

I started writing my tests from GameLogic match 3 sample project. The code project is based on GameLogic’s Grids for Unity component, and I’m using as much as possible the DOTween’ component for smoothing movements and effects.

The GameLogic fellows compiled an exhaustive survey of match games, including a wonderful infographic on match game structure spectrum:

2015-09-18 16_28_08-Microsoft Edge

Subtleties of match 3 game mechanics

explodingSubtleties of game design mechanics emerge once you are creating a prototype: sequential matching, peculiarities of click / swipe matching, generative universe (no need of generational AI) … discrete / continuous matches … .

If you believe that game design is basically a formal activity, mainly to do with mechanics (which actually I believe to be too simplistic) you need to be a developer at least at some level, because in building the prototype you understand the mechanics, with all its possible variations.

References

Match Game Mechanics: An exhaustive survey.

GameLogic Match 3 sample project.

Grids for Unity GameLogic FAQ.

Match 3 game draft in Unity tutorial with full code.

You Must Build a Boat.

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, serious games.

Social Share Toolbar

A podcast & sources for (romantic) game polish and feel – DAG pod 22

In this podcast Daniele Giardini and Pietro Polsinelli (myself) discuss the notions of game polish and feel.

Here is the podcast:

There is also a video of the podcast here:

References

Game Feel: the book.

The game Goscurry.

football drama prototype

The Football Drama site.

DOTween

DOTween tweening component site. Easings http://easings.net/en.

Finally, Vlambeer talk on game feel.

Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, applied games.

Social Share Toolbar

Making a sport game in Unity: model & prototype

I just published a video where I describe how to start modelling and developing a sport game, specifically football (soccer) in my case:

In the following notes some motivation for the work and references from the video.

What am I trying to do?

I am creating a game on football (not American Football), called Football Drama: this game is supposedly the story of the coach in the context of a Football Manager like game. The latest version of Football Manager for smartphones has a cool game play:

FM 15 on smartphone

One of the first thing I did in Unity is search for a plugin that would handle the match play part. Given the number of plugins available in the Asset Store and the popularity of football, I was pretty sure that my only problem would be picking the best plugin. Wrong.

I didn’t want to do thisimage

The only decent looking component I found is Soccer Project by “Astute Games”, which is ok but actually does nothing useful in my perspective, as it provides passive 3D models of players and little more.

The are simply no plugins covering modelling, movement and AI for football games in the Asset Store.

Maybe because “The barrier of entry on making a decent team sports game is really high.”, as they say in one of the few discussion of the theme indie & sports available online.

The Simple Soccer examplehttp://ecx.images-amazon.com/images/I/51jAoX1id6L.jpg

In chapter 4 of the book Programming Game AI by Example the author provides a nice implementation of a simple soccer game.

I’ve downloaded the Java sources and made the sample run in my IDE.

simpleSoccer

Here are some of the Java classes of this example:

image

Movements are regulated by physics:

image

Complete Java source code is here.

Not what I want for a sport game

This material is useful but what it is modelling is not football. seems more snooker to me Sorriso. I want a simple grid with squares as players and a state handling framework, where the (hierarchical) state machine can easily be extended. Movement is not determined by physics – the right metaphor is not snooker.

If you actually watch a football game, its a highly fractioned game of control and tactics, my reference for this development has been Cameroon vs. England (World Cup 1990):

Physics plays a role on long shots, but I will model that using tweening (the wonderful DOTween library by Daniele Giardini). I will call the model I need Football Grid.

Football Grid: The model

imageThe example is also using heavily inheritance to model all aspects of play. I instead will be happily mixing inheritance and composition, reducing inheritance to a minimum and modelling state with classes only when strictly necessary. A great book to learn about basic game programming patterns, if you are new to the topic is Game Programming Patterns.

The three states of game play: paused, preparing play, in play: this is simply an enum.

I used object hierarchy and modelling of states with class instances only when it is strictly useful, so e.g. in the case of a player state.

Here are the classes of my model:

image

2015-04-05 16_11_46-UnityVS.footballDrama - Microsoft Visual Studio

2015-04-05 16_20_15-UnityVS.footballDrama - Microsoft Visual Studio

Curve ball effects

2015-04-05 16_29_08-PowerPoint Slide Show - [MasterSlides.ppt [Compatibility Mode]]

To get these effects you can simply tween (I use DOTween) the ball differently along the X and Y axis:

DOTween curse transform

More?

Follow me on Twitter – I study game design, development (2D), applied games, and I post about progress on Football Drama.

Football Drama game design

Unity components used

DOTween tweening component

Game Logic Grids http://gamelogic.co.za/grids/

DOTween http://dotween.demigiant.com/

Thank you!

Image references

“Association football 4-4-2 formation” by MaxDZ8, based on work from Mario Ortegon – self-made, original file from Mario Ortegon. Licensed under CC BY 2.5 via Wikimedia Commons – http://commons.wikimedia.org/wiki/File:Association_football_4-4-2_formation.svg#/media/File:Association_football_4-4-2_formation.svg

“Association football 4-3-3 formation” by Threner. Licensed under CC BY-SA 3.0 via Wikimedia Commons – http://commons.wikimedia.org/wiki/File:Association_football_4-3-3_formation.svg#/media/File:Association_football_4-3-3_formation.svg

Social Share Toolbar