Skip to content

nilpunch/interface-field

Repository files navigation

Interface Field for UnityEngine.Object

image

Unity package for serializing UnityEngine.Object using an interface field.
Leverages decompiled UnityEditor code, so stability may vary.

Refer to the samples for a quick start.

Installation

Make sure you have standalone Git installed first. Reboot after installation.
In Unity, open "Window" -> "Package Manager".
Click the "+" sign at the top left corner -> "Add package from git URL..."
Paste this: https://github.com/nilpunch/interface-field.git
See minimum required Unity version in the package.json file.

Overview

Currently supports only drag-and-drop. Object selection via a window is WIP.

What is allowed:

  • Renaming the interface field in your consumer
  • Renaming implementations of your interface

What is not allowed:

  • Renaming proxy classes
  • Renaming the interface (this may work in the latest Unity versions)

How to use

  1. Write proxy class for the interface (can be defined anywhere):
public interface IWeapon
{
	void Attack();

	public class Proxy : ObjectProxy, IWeapon
	{
		public void Attack()
		{
			((IWeapon)Object).Attack();
		}
	}
}
  1. Use SerializeReference with Proxy attribute for your interface consumer:
public class WeaponConsumer : MonoBehaviour
{
	[SerializeReference, Proxy(typeof(IWeapon.Proxy))]
	private IWeapon _weapon;

	[ContextMenu("Test")]
	public void Test()
	{
		_weapon.Attack();
	}
}
  1. Interface implementors only need to implement the interface — no additional setup required.
public class WeaponA : MonoBehaviour, IWeapon
{
	public void Attack()
	{
		Debug.Log("AAAAAAAAAA");
	}
}

public class WeaponSO : ScriptableObject, IWeapon
{
	public void Attack()
	{
		Debug.Log("SOOOOOOOO");
	}
}

About

Unity package for serializing UnityEngine.Object using an interface field.

Resources

License

MIT, Unknown licenses found

Licenses found

MIT
LICENSE
Unknown
LICENSE.meta

Stars

4 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages