Noticed : XML Documentation Comments in Visual Code and Getter/Setter to Methods Shortcut

Two small things that I noticed today :

XML Style Documentation Comments in Visual Studio Code

If you want XML Style Documentation Comments in Visual Studio Code like in Visual Studio you have to enable them :

Go to File->Preferences->Settings

Then go to Formating and then turn on „Format on Type“ (its turned off by default)

  If you type then /// above a class or method definition, it will add the <summary> block for you and add the newline /// if you add a line inside it, just like it is default in Visual Studio Code ! I missed that so much.

    /// <summary>
    /// contains the written down notes and thoughs
    /// </summary>

Getter/Setter into Methods

If you need to use Getter/Setters (Properties) for any reason but you want to use actual methods, you can use Visual Code Actions to do that without writing.

First add a Getter/Setter with an action for your field. After that you can use a new action to convert the property from that syntax to actual methods ! (sorry for the german, „durch Methoden ersetzten“ means „replace with methods“)

After that you have neat real methods. I like that way more.

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.

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.

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)

More about Actionable Objects. ( InterAction Project Series )

Let’s have a look how this little system I am doing enables the player to open and close this power block door, as a simple example.

The orange door you see in the scene view in the picture above has a component called ActionableObject. If the layer „ActionableObjects“ exists, a GameObject with this component on it will be set to this layer. This is needed because the raytracing of the EyeModule only hits on objects in this layer. (If the layer does not exist, errors will be thrown, but there is a convient editor menu where you can create all needed layers without having to add them manually.)

„More about Actionable Objects. ( InterAction Project Series )“ weiterlesen

Rigging or Scripting – that is here the question.

My character is holding a flashlight.

My character is holding a flashlight. But I also have two animations in the animation controller running. One for the idle animation or walking in one layer, and one for the hand actions in another layer, seperated by a layer mask.

„Rigging or Scripting – that is here the question.“ weiterlesen

Not really a quest system (yet), rather a basic interaction system. #4

So this is growing, but its now a fully functional interaction system. The player (or other entities soon) can see objects they can interact with and get a menu that builds itself from the actions they can perform on that object.

This is not as flexible as I want it to be at all, yet. But I have to make a comprimise between getting it done and make it perfectly reusable.

Being seen is half the battle – a (very simple) Quest-System for Unity (#3)

This is the system now that makes it possible for the Actionable Object to track if its seen or not seen. Now it can give the Game System (ControllerGameScene in this case) all the actions or informations that the game system needs to present the player choices or possible actions. This will be done via a UI menu or hotkeys.

Unity, the Terrain and me, Part 2

After having the basics for this, see part 1, I created a plane and subdivided it a few times in Blender to have enough vertices in the mesh. I probably could use ProBuilder and do the subdivide there, but I try it first this way.

I imported the mesh as fbx into Unity3D and scaled it and moved it over the terrain. Now I want that every vertics of the mesh has the same y-axis height than the terrain at its x/z position.

Since I want to change vertices in the mesh, I have to set it to Read/Write Enabled in its importing settings on the model file.

First thing is to get the mesh data. But, and here I stucked last time I was trying this, the imported plane mesh asset only has a MeshFilter. What is a MeshFilter ?

„The Mesh Filter takes a mesh from your assets and passes it to the Mesh Renderer for rendering on the screen.“ (Unity3D – Documentation)

Since it is an instance, I am still not sure if I can change it at all. This is a basic flaw in my understanding of Unity3D. Please be patient with me here. 😀

But after reading the documentation, I noticed that last time I was trying this, I did it in editor mode. And there you are advised to use the sharedMesh field of the MeshFilter. And using that, you actually change the asset itself ! Unity3D clearly states, that you should not use sharedMesh for changing the mesh verticies.

If you use the mesh field of MeshFilter durching Run-Time, it creates a duplicate and every time you use mesh, this duplicate is returned. Also sharedMesh then points to this duplicate. So I will do that then. Here I only use one mesh, but for the planed used this is important, since there I will change a lot of instances of the same mesh.

And actually, this worked on the spot :

  MeshFilter meshFilter;
    Mesh mesh;

    meshFilter = terrainCoveringMesh.GetComponent<MeshFilter>();
    mesh = meshFilter.mesh;

    Vector3[] verts = mesh.vertices;

    Debug.Log("Found " + verts.Length + " Vertices for Tile " + terrainCoveringMesh.name);


    for (int i = 0; i < verts.Length; i++)
    {

        Vector3 vertPos = terrainCoveringMesh.transform.TransformPoint(verts[i]);

        Vector3 pos = vertPos;
        pos.y = Terrain.activeTerrain.SampleHeight(vertPos);

        vertPos.y = pos.y;

        Vector3 backToLocal = terrainCoveringMesh.transform.InverseTransformPoint(vertPos);

        verts[i] = backToLocal;

    }

    mesh.vertices = verts;

    meshFilter.sharedMesh = mesh;

    meshFilter.sharedMesh.RecalculateBounds();
    meshFilter.sharedMesh.RecalculateNormals();
I made the covering mesh smaller so you can see the underlaying structure.

Important here is that you convert the vertices position from local space to world space and then back to localspace, using the transform of the mesh you want to lay over the terrain.

So this is done. Now how to get this working in Editor Mode is another question and the final problem.