Imagine, Code, Create

Tag: unity

Asset Variables

Source Files

On my Patreon page, you will find a Unity Package containing everything covered here and a number of pre-created Asset Variable scripts and a List variant for each.

Reusability is quite important in almost any development scenario, and the same applies to games as well. One technique I have adopted are Asset Variables or shared variables. These are based on ScriptableObjects in Unity, hence my name for them: Asset Variables.

The concept is simple. Instead of using, let’s say a public Color variable, your would create an Asset Variable for Color, let’s call it ColorVariable. You would then proceed to use that ColorVariable as your type. The only challenge is making it integrate as seamlessly as possible and that is what I would like to show you today.

To start we need 2 C# scripts: BaseAssetVariable & AssetVariable.

using UnityEngine;

namespace AssetVariables.Base
{
    public abstract class BaseAssetVariable : ScriptableObject { }
}

BaseAssetVariable is an abstract class and inherits from ScriptableObject. It doesn’t have any variables or methods of its own, because we only need it for convenience later. For now this is all we need of this class.

using AssetVariables.Base;

namespace AssetVariables
{
    public abstract class AssetVariable<T> : BaseAssetVariable
    {
        public T value;

        public static implicit operator T(AssetVariable<T> a)
        {
            return a.value;
        }
    }
}

AssetVariable is somewhat more complicated. Firstly, it inherits from BaseAssetVariable, but is also marked as abstract itself. Next, we are using generics with <T> to then declare our generic variable value. Lastly, we have the method public static implicit operator T(AssetVariable<T> a){...}. This method allows us to simply use instances of our variables as the type <T> that they represent, eg. as a float or Color.

With our base scripts created, we can now create our variables. For the beginning, let’s create a variable for Color.

using AssetVariables;
using UnityEngine;

[CreateAssetMenu]
public class ColorVariable : AssetVariable<Color> {}

Thanks to our work previously, creating a new variable is as easy as inheriting from AssetVariable<T> where T is the type we want to use. I added the [CreateAssetMenu] attribute, so we can actually create an asset. To do so, just right-click in your project window or go to Assets/Create and select Color Variable and set its value in the inspector.

Finally, let’s use our new ColorVariable. Create a script called SetColor. Then create a Cube in your scene and attach the script to it.

using UnityEngine;

public class SetColor : MonoBehaviour
{
    public ColorVariable myColor;

    // Start is called before the first frame update
    void Start()
    {
        MaterialPropertyBlock mpb = new MaterialPropertyBlock();
        mpb.SetColor("_Color", myColor);
        // alternative:
		// mpb.SetColor("_Color", myColor.value);

        GetComponent<Renderer>().SetPropertyBlock(mpb);
    }
}

We declare our ColorVariable as myColor. After that create a new MaterialPropertyBlock and call SetColor() on it, with the property name “_Color” with our variable myColor. Usually it would require to use the Color type by Unity, but our method public static implicit operator T(AssetVariable<T> a){...} allows us to use our Asset Variable directly as if it were of type Color. Of course you can also use myColor.value to make sure to use your variable value type (in this example: Color).

As a last step, we need to assign our ColorVariable Asset to our variable field in the inspector. Select your cube and drag the ColorVariable into its field.

If you play, you will see the cube getting recoloured to whatever colour you’ve set in the inspector previously.

That’s it. You can now reuse this ColorVariable anywhere you like. If you’re familiar with CSS, this workflow might be somewhat familiar to you. Otherwise, it’s slightly comparable to Unity’s nested prefab system and definitely plays well with it.

As a follow up, I will add a few other example scripts for AssetVariables, but you can find a lot more on my Patreon Page:

Scripts
using AssetVariables;
using UnityEngine;

[CreateAssetMenu(menuName = "Asset Variables/Float")]
public class FloatVariable : AssetVariable<float> {}
using AssetVariables;
using UnityEngine;

[CreateAssetMenu(menuName = "Asset Variables/Int")]
public class IntVariable : AssetVariable<int> {}
using AssetVariables;
using UnityEngine;

[CreateAssetMenu(menuName = "Asset Variables/String")]
public class StringVariable : AssetVariable<string> {}

Quick Search

Installing the Quick Search Package

A while ago, I created an Editor Tool for Unity, which allowed to search for anything in the menus, the assets and in your opened scenes. Shortly after however Unity released their Quick Search package in the Package Manager. Simply find Quick Search and install it from the Package Manager.

After installing it, you can open it with the default keybind of Alt+' or Option+' on Mac.
If you’re using Unity 2019.3 and up, you can change this binding easily in the Shortcut Manager, found in the Edit/Shortcuts... menu.

Changing the Shortcut binding

Simply find the Shortcuts for Quick Search, by entering the name in the search field.

Find the line with the command name Main Menu/Help/Quick Search.

Double click the Shortcut Alt+' (or Option+'), then hit the key combination you would like to use instead.
I prefer Ctrl+Space.

Using Quick Search

When you are ready, open the Quick Search window, by pressing your set shortcut. All you have to do it type the name of whatever you are looking for. It will show your assets as well as GameObjects in your scene. It can even solve simple mathematical expressions. To use them prepend = and enter your expression.

There are many more things you can do with it, and I suggest you have a look at the Documentation page for Quick Search. There are also a number of settings in the preferences window, where you can set your own priorities for your search results, or if you decide that you don’t need to see assets in your searches, so you can disable those results entirely.

© 2020 Toorah's Blog

Theme by Anders NorĂ©nUp ↑