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.

I need an Inventory. To put stuff in. And take stuff out. You know. A first look.

I need an inventory system. Mainly for the Interaction Project. Of course an inventory system consists of two parts, the Inventory Data and the Inventory UI.

Let me check my option here first :

Option 1 : Write one myself.
Option 2 : Use a free one
Option 3 : Try to utilize Unitys Game Foundation
Option 4: Buy one on the Asset Store

Option 1 is tedious. I already wrote one for Interaction Project. But besides the fact that it was poorly designed, it was bound to the Interaction Project way to close. While something like that is done fast, doing it right is not done fast.

Option 2 is ok, there are several open source inventory systems. But the learning curve, the quality check and also checking if there is still active development also takes time. And it has to be adaptable to the Interaction Project, which I plan to do by using an interface.

Option 3 is interesting. The Game Foundation seems high quality and provides one part of the Inventory, the Data Layer for it. It also has a currency system. Mainly done for making predatory mobile games, nevertheless it seems to be what I need. Will definitly try it out.

Option 4 requires a bit of research and of course money. (which is totally ok for an external quality asset that saves time and/or enhances the posibilites)

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.

The Generic Menu – bon appetité – Part 1

(this article is more for myself and for future documentation, but it might be interesting for people struggling with Generic Menus.)

For my Interaction Project one main goal is that you can add Flags easily to an Actionable Object Flag Dependency.

Meaning : If there is a chest which can be opened, then you add a flag to it like „open“. The open and the close action then depend and act on the state of that flag.

For adding a flag dependency to an Actionable Object, I wanted a fast, organized and quick way to choose a flag. For this I use an Generic Menu in the Editor Script for the Flag Dependency Class, a custom Property Drawer.

(Of course, if you have multiple chest this gets a bit confusing when they have the same name, but I will add a menu entry for the flags in the current editied AO. Also there are some more ways to group AOs, like region, area, group, scene…)

My first approach used simply the flag names. But this did not work out. I need a unique identifier for each flag. That is necessary cause Actionable Objects Flag Dependencies can depend on flags from other AOs. Also to be able to clone an Actionable Object easily, for example windows or doors, you need to be able to create the flags with the same name but with another unique identifier.

Also there was one small problem I solved for this to work : Since there can be more than one Action in an AO logically, the menu in each of these has to report to the AO which Action actually used a menu to create a new flag dependency.

I solved this by adding the unique property path to the return value of the selected menu item.

flagNameToAdd = property.propertyPath + "\n" + flagNameToAdd;

Here I still use the flag name instead of the flag uniquie uint identifier.

Then the next „trick“ I used is to place the selected menu item string into an member of the FlagDependencyDrawer. In the next OnGUI the drawer checks if the member variable is empty, if not, it parses the content and creates the Flag Property accordingly. It also makes sure that the string is for this drawer, which seems a bit redundent, but seemed necessary at the time.

if (property.propertyPath == propertyPath)

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