Changing the uss style sheet of a Visual Element during runtime.

I want to be able to use a default uxml as inventory for example. I need the structure of the inventory to be the same, but the uss changes per game or even per scene.

I used a game object that I called „Scene Configuration“. (could make it a scriptable object and integrate into game manager, but that is for the future).

The Scene Configuration has an entry

public StyleSheet inventoryUSSFile;

There I drag the custom uss file for the generic inventory uxml.

In the controller for the Inventory UI I read this value from the scene configuraton. This is the uss file asset I want to apply to the inventory on startup.

        private void SetSceneDependantInventoryUSS()
        {
            // get the style sheet list

            VisualElementStyleSheetSet styleSheets = m_Root.styleSheets;

            if (sceneConfiguration.GetSceneInventoryUSS() != null)
            {
                m_Root.styleSheets.Clear();

                m_Root.styleSheets.Add(sceneConfiguration.GetSceneInventoryUSS());
            }
        }

I get the list of style sheets attached to the uxml, but rather a VisualElementStyleSheetSet, that has the ability to add uss style sheet assets to the Visual Element. Thus you need to work directly with the styleSheets object from the Visual Element.

Then I clear all active stylesheets and add mine. Done. No refresh needed.

Working Substance Designer Template for generating Unity3D Terrain Layer

As promised what feels half a century ago, I now have the correct and working template for creating Unity3D URP/HDRP Terrain Layers, with Diffuse, Normal and Mask Map.

Substance Graph

Of course this is only the rough template. It also just converts the inverted graymap from the input bitmap node for smoothness (0=rough, 1=smooth) and sets metal to 0 (no metal). You will have to change that depending of the type of terrain layer you create. (obvious, but I thought I just say it).

But the mask generation is now 100% working, I tested it thoroughly.

You can download the template substance designer file here.

Generic Fluid Shader Reproduction Try

Well, I saw this post on twitter :

Will I be able to do that in Unity with Shader Graph ? We will see. I am not really good in Shader Graph, although I did some previous shaders with it and always managed to get what I wanted. (Reminder to myself : Post them here)

STEP ONE

Good. Let me just start Gimp and do something like that. So in the Filter > Render -> Noise menu there are „difference-clouds“ which is exactly what I was looking for but sadly not scaleable or anything. So I took Plasma, desaturated it and did a slight gaussian blur on it.

Step Two

Right. The animation direction is top-right. So let me do that in Unity. After totally black out how to this () I remember how to do it.

Using time to move the uv offset and multiple time by -0.5 so it scrolls in the right direction in the right timing. (the uv is the image that maps the surface 3D positions to a point on the 2D texture, for those who don’t remember). Ah I forgot one step you also have to set the tiling to 0.1 so it zoom big into the texture.

STEP THREE

All right. I use a Blend Node with Screen Mode to do that. Not sure if that the right mode, but as I remember from working with Substance Deisgner, Screen Mode is basicly mixing two textures together.

STEP FOUR

Well ok, on it.

Done. 🙂

STEP FIVE

Uh, well, ooook. XD

Here we goooo.

STEP SIX

If you say so. 🙂

STEP SEVEN

So I have no clue atm how to do this in Unity Shader Graph. Buuut I think the Replace Colors Node is what I want and yes this did kinda work out.

FINAL STEP 8

All right, this translated into shader graph :

Conclusion

This was a quick morning experiment, and it does not look like the original. At least not yet. But it was worth the try and it certainly is something. I will try to perfect it at a later time. Then I also will make the shader graph asset downloadable. Shout outs to the orginal author of the tweet ! XD

Unity3D : Global Debug On/Off

I have a custom template class for new C# class in Unity. Mostly cause I was too „lazy“ to use a debug singelton class or enhance the GameObject/Object class with a custom debug function.

        protected void dbg(string message, bool error = false)
        {
            if (debugMode & !error)
                Debug.Log("[ " + this.GetType().Name + " ( " + Time.time + " / " + Time.frameCount + " )] " + message);

            if (error)
                Debug.LogError("<color=\"red\">[" + this.GetType().Name + " (" + Time.time + ")] " + message + "</color>");
        }

So now I have a lot of Classes using this function and it can be turned off in the inspector with a toggle. But after a while of course this ends in chaos, since when you just want a certain aspect you are working appear in the console, you have to go through all of those classes and turn debug off manualy.

Instead I now added a static menu function that uses reflection to turn the debug state of each class on or off globally.

#if UNITY_EDITOR

using UnityEditor;
using System.Reflection;

#endif

        [MenuItem("InterAction Project/Global Debug Toogle - On")]
        public static void GlobalDebugToggleOn()
        {
            List<Component> componentsWithDebugModeMember = new List<Component>();

            GameObject[] allGameObjects = FindObjectsOfType<GameObject>();

            foreach (GameObject gO in allGameObjects)
            {
                Component[] components = gO.GetComponents(typeof(Component));
                foreach (Component component in components)
                {
                    Type typeOfComponent;

                    typeOfComponent = component.GetType();

                    var f = typeOfComponent.GetField("debugMode");

                    if (f != null)
                    {
                        foreach (FieldInfo propBase in component.GetType().GetFields())
                        {
     
                            if (propBase.Name == "debugMode")
                                propBase.SetValue(component, true);

                        }

                    }
                }
            }
        }

Then I can turn on only the Classes I actually need to display debug informations at the moment. Nothing fancy, but I think it may be useful for some of you out there. 🙂

I need an inventory for Interaction Project – Part 2

Actually, the Game Foundation package from Unity itself is pretty neat.

I just need the Inventory System from it for now. It also offers a currency system, a trade system with a transaction system and some kind of reward system.

There are some tutorials on the package page, yet they are not updated to the latest version and some things have changed, so one must think a bit.

It is pretty easy to use and the editor interfaces are very nice.

Example of an InventoryItem definition, on the left side the overview with all inventory item definition, well there is just this one at the moment, so 🙂

Since I want to be able to choose an item definition in an Action, so that the item can be instanced and given to the player, I need a way to list all item definitions in the catalog.

This is done by using one of the catalog API methods, as shown by a post on the unity forums. At the start I was not sure which type to use for the CatalogItemAsset ICollection which is of course an InventoryItemDefinition List.

    // You can use any type of catalog item for this list.
    List<InventoryItemDefinition> itemDefinitions = new List<InventoryItemDefinition>();
    GameFoundationSdk.catalog.GetItems(itemDefinitions);
 
    foreach (InventoryItemDefinition definition in itemDefinitions)
    {
        // Process your definition here ...
    }

My next problem is that I want a nice way to present the available ItemDefinitions in the custom Action Editor. Right now one could go into the catalag asset and open it and drag the containing InventoryItemDefinition Scritable into the Action ItemToAdd List, but yikes.

So what I really, really would like to have is that nice overview and filter/search listing element in the image above and let it pop up in a window so one can just doubleclick on an InventoryItemDefition and it would add it to the list in the custom Action inspector. Hmm. Onwards to adventure, maybe I can check out how to do this.

Between Lost Places – The Silent City Part 1

I am still working on a blue-orangish small city, surrounded by walls and mountins. Only one big street is passing through. One the one side there are several shops and people shopping. On the other side there is the traffic department and an inventor house.

The player has to cross the street to get through the busy city shopping area to the exit to the next area. BUT : The city shopping people have a virus and are spreading it. They do not wear masks. So the player has to find a way to cross the street, avoid being infected and find the exit.

Navigation of the shopping NPCS

I had several things to do here : First, a simple NPC AI System, which lets the shopping NPC spawn at several points like the shop doors or the subway entrances. Then they need to move to one another of these points.

I solved that with the build in Navigation System of Unity3D.

Pooling the shopping NPCs with kPooling

But the spawing of a lot of NPCs could not be done without a pooling system. Instanciating them every time would have slowed down it too much. I found this open source pooling system, kPooling, and it is really amazing. (thanks a lot to Kink3D, a former employe of Unity3D for that).

So everytime a NPC reaches a destionation, I give the NPC gameobject back to the pool and take one if one needs to spawn from it.

The Virus

There are two things with the virus : A Shopping NPC can be infected in various grades. But how to visuale this to the player ? I choose to make a graph shader, that uses a red gradient color to indicate how much the infection has progressed in an infected shopping NPC. Why is this important ? First, the player can aquire argumented reality glasses ingame, that show him this. And : the more a NPC is infected, the greater is the area in which peole get infected in front of him when he coughs.

Writing this shader was a bit tricky, I will publish it here for free use later, also I have to ask in the Unity Forums if there is a better way to do it, but for now I am happy that I found a way to actually do a shader that provides the needed functionality.

More in Part 2 soon.

Getting a human-readably entry (like a key) from your Input Map in Unity3D

I am using the „new“ Input System of Unity, which I really like.

For my Interaction Project I needed the mapping of an action in a human readable form.

First add

using UnityEngine.InputSystem;

Then, in your class where you need it, for example a config dialog, or in my case, to show the correct key for an action on an Actionable Object when the player looks on it.

	public PlayerInput playerInput;

	public InputActionMap actionMap;

You can either drop the PlayerInput component in your Game Gameobject into it in the Inspector or just let it be initialized in the Start method.

Also in the Start() method :

		if (playerInput == null)
			playerInput  = GetComponent<PlayerInput>();

		actionMap = playerInput.currentActionMap;

        

        ReadOnlyArray<InputBinding> actions = playerInput.actions["Interaction1"].bindings;

		foreach(InputBinding binding in actions)
        {
			Debug.Log(binding .ToDisplayString());
        }

Interaction1 is the action I am looking for. I then iterate through all the bindings and display them as a readable string. (In this case I only have one binding though)

The action is mapped to the keyboard key E, so I get a plain and nice E as result, which is exactly what I needed.

References :

Unity3D Input System Reference

Unity3D Input System Reference – ToDisplayString

Running Unity3D WebGL with a local Apache Server

Well, it is much easier than I thought. If you know Apache, that is.

I tried to use the Live Server Plugin from Visual Code first, but that has no gzip module, so it can not be used for compressed builds. Meaning : You always would have to compile twice, and that I find stupid.

So I installed the Windows Apache Binaries from here for example, which have libz and even the Brokoli ? compression modules enabled by default.

„Running Unity3D WebGL with a local Apache Server“ weiterlesen

2021. Happy new yeah.

While still working on perfecting my Interaction Project, a little framework to easily create interaction between objects based on a easy to manage flag system, I am running into old problems when creating a WebGL Build for the current mini-game.

  1. The script at (localhost:x) embroid1.framework.js.gz was loaded, even if its MIME-Typ („application/gzip“) is no valid MIME-Type for JavaScript
  2. Uncaught SyntaxError: illegal character U+001F embroid1.framework.js.gz:1
  3. Uncaught ReferenceError: unityFramework is not defined onload http://localhost:x/Build/embroid1.loader.js:1

I had this before. I solved it. But it was quite a long time ago last year.

I will find the solution again and then post it here.

Also hopefully more posts about my Interaction Project this month and some cc0 textures / materials I made with the Substance Suite, with which I have fallen in love.

The flag of Interaction – more about the FlagSystem of Interaction Project

To speed up the whole flag system handling, I wrote a custom inspector for the ActionableObject class.

The flags for the Actionable Object can easily be created/deleted in the custom inspector. Also the initial status can be set.

Important is here that by creating/deleting Flags for that ActionableObject they automatically get registered in the Flag System Manager.

With this other ActionableObjects as well every other Object that uses the flag system can access the flags in their Actions.

Every AO or any object that wants to use Flags need a FlagDependency List.

A custom property drawer for it handles everything inside it, so there is no need for any calls to the class which the FlagDependency List is part of.

But how to keep track of all the flags of all objects ? Here comes the „Add Flag Dependency“ Button into play. This button opens a menu that has a list of all available flags for all Objects that have registered flags.

So much for that now.