• Stars
    star
    137
  • Rank 264,923 (Top 6 %)
  • Language
    C#
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

AssetPathAttribute is a Unity attribute used in Unity to allow you to have drag and drop asset references in the inspector but really use string paths for serialization.

AssetPathAttribute

AssetPathAttribute is a Unity attribute used in Unity to allow you to have drag and drop asset references in the inspector but really only serialize string paths.

Why?

If you use object references in Unity when you load one asset every asset it references is also loaded into memory and this is not really ideal. The other option is to load everything from resources by using it's path. So instead of having a direct reference you have a string field. These are really hard to work with as it's easy to make a mistake and if the asset moves and has become invalid you will not know. You also can't jump between objects very quickly. This is a huge hit to usability. Asset Path Attribute combines the best of both options into one using some inspector magic.

How it works

In the top box we have the inspector in normal mode. As you can see there are object references. However when you go to debug mode you will see we have string paths. This is what AssetPathAttribute does. The code for the asset path inspector drawn above is the following

[CreateAssetMenu]
public class ValueExample : ScriptableObject
{
   [AssetPath.Attribute(typeof(GameObject))]
   public string m_PlayerPrefab;

   [AssetPath.Attribute(typeof(Transform))]
   public string m_PlayerSpawn;

   [AssetPath.Attribute(typeof(AudioSource))]
   public string m_PlayerAudioSource;
}

As seen above all you need to do is add the AssetPath.Attribute(Type) above a string field. When Unity goes and draws that string field it will instead use the AssetPathDrawer.cs and create your object field. If you put the attribute above a invalid type (anything but a string) the inspector will show the following.

Instead of just defaulting back to the normal inspector (which would be really easy to do) I display a error just so you know you are currently referencing the object directly.

Valid Targets

Asset Path Attribute just piggybacks off the Unity serialization system and can't draw object fields for types that Unity does not support. Any type that inherits from UnityEngine.Object can be used with AssetPathAttribute.

Helper Functions

When working with Asset Path Attribute it store all paths as project paths i.e all start at the base Assets/ folder. In terms of runtime this is not useful to you since to load objects they need to be in a Resources folder. To convert a Project Path to a Resources path you can use the following.

public class UIManager
{
   [AssetPath.Attribute(typeof(UnityEngine.UI.Image))]
   public string m_UIImage;

   public void ConvertExample()
   {
       // Takes a path from 'Assets/Resources/Player/PlayerIcon.prefab'
       // and converts it to `Player/PlayerIcon.prefab'
       string resourcesPath = AssetPath.ConvertToResourcesPath(m_UIImage);
   }
}

You can then go ahead and load the asset using Resources.Load<T>(string path) There is a second function that you can also use that will load the object for you.

[AssetPath.Attribute(typeof(GameObject))]
public string m_PlayerPrefab;

public void CreatePlayer()
{
   // Converts our path to a resources path and then loads the object.
   GameObject player = AssetPath.Load<GameObject>(m_PlayerPrefab);
}

The advantage of using this function is it's much cleaner and also in the Editor if the object could not be find in a Resources folder an attempt to load it using AssetDatabase.Load(string path). This is really useful for any editor windows that might be using AssetPathAttribute.

TODO:

  • Validate that the type sent in to AssetPath.Attributes constructor is serializable. Display a error string if it's not.

Meta

Handcrafted by Byron Mayne [twitter β€’ github]

Released under the MIT License.

If you have any feedback or suggestions for AssetPathAttribute feel free to contact me.

More Repositories

1

Weaver

Weaver is a code weaving framework built right into Unity Engine. Based heavily off of Fody.
C#
138
star
2

UnityIO

An easy to use API that allows you to manipulate files inside of Unity without the headache of using AssetDatabase.
C#
69
star
3

ScriptForge

A simple tool to generate constants for Unity for your Layers, Tags, Sorting Layers, Animations, Scenes, and Resources.
C#
53
star
4

SourceGenerator.Foundations

A Source Generator for Source Generators. Gives out of the box support for transistent dependencies and logging right in Visual Studio
C#
26
star
5

Reflected-Inspector

Reflected Inspector is a system for Unity that works very much like Serialized Properties but works with non-Unity types and can serialize the values.
C#
20
star
6

StyleBrowser

A browser editor window to view all Unity built in styles.
C#
11
star
7

LoxSharp

The C# implementation of the Lox Tutorials written by @munificentbob found at http://www.craftinginterpreters.com/
C#
8
star
8

CaptureGroups

A editor tool used to take screenshots for documentation
C#
7
star
9

CallMeEasy

CallMeEasy is a series of Unity attributes that allow you to hook into some callbacks that Unity does not expose out of the box.
C#
7
star
10

Seed.IO

Seed.IO is a library containing a bunch of useful helpers types and class for working with IO
C#
5
star
11

IPool

IPool is an open source Unity pooling system. It's designed to be easy to use and full docmented.
C#
5
star
12

GUIGrid

A simple to use IMGUI grid class for editor windows in Unity
C#
4
star
13

Recoil.net

Recoil.net is the C# version of the Facebook's Recoil.js library. It's designed to handle managing state in WPF applications.
C#
4
star
14

JiffyEditor

Powerful unity editor to auto generate inspectors and property drawers.
C#
4
star
15

Parcel

Parcel is an open source project that is used to allow you to load from Asset Bundles in Editor without really building them. So when you build your game the logic flow stays the same.
C#
3
star
16

Extended.Collections

Library containg C# collections of verious types of collections.
C#
2
star
17

MUUG-Aug-2017

The source code for my Montreal Unity User Group talk that is happening on 8/16/2017
C#
2
star
18

Ninject.Extensions.AutoFactories

C#
1
star
19

SearchableList

C#
1
star
20

Redux.DotNet

A C# implemention of Redux but done in C#. This also contains a WPF abstraction
C#
1
star
21

AtomPackageManager

C#
1
star
22

AsyncApi-Generator-CSharp

A C# implemention of the AsyncApi generator used to create both client and servers.
TypeScript
1
star
23

clox

My implementation of the Byte Code Interpreter following the great book Crafting Interpreters by Bob Nystrom. Chapter starts http://www.craftinginterpreters.com/chunks-of-bytecode.html
C
1
star
24

Turnip

Turnip is a cross platform time timer library that adds full timer support in Unity. In 1702 based on the verge movement thick pocketwatches went out of fashion and were only worn by the poor and derisively referred to as "turnips".
C#
1
star
25

OpenApi.SourceGenerator

OpenApi.Generator uses a Source Generator to generate the boilerplate for an Asp.Net Core application that is based of a preexisting openapi definition
C#
1
star