Skip to content

Tutorial: basic usage

Robin van Ee edited this page Jan 22, 2023 · 1 revision

Creating the object

The following example goes over how to load data from objects and use it in code.

Firstly, we create a component using a basic code sample from the Components page.

public class ExampleComponent: IRPGComponent
{
    [AssetReference(typeof(Sprite))]
    public AssetReference MySprite { get; set; }
	
    [AssetReference(typeof(GameObject))]
    public AssetReference MyPrefab { get; set; }
}

We now add this component, and our data to an object and press Save image

Referencing RPGObjects from a Monobehaviour

In a MonoBehaviour add code as follows

public class TestMonoBehaviour: MonoBehaviour
{
	[SerializeField] private RPGObjectReference characterReference;

	private void Awake()
	{
		// Load the RPGObject from the reference
		// The first time the asset is loaded from disk and deserialized, but it's cached afterwards
		IRPGObject character = characterReference.GetObject();
		
		// Use GetComponent to retrieve our data from the RPGObject
		ExampleComponent component = character.GetComponent<ExampleComponent>();

		// Unity assets are referenced with the AssetReference type
		AssetReference prefabReference = component.MyPrefab;

		// Retrieve the prefab from our prefab reference
		// The first time this loads the asset from the disk, but is cached in memory afterwards
		GameObject prefab = prefabReference.GetAsset<GameObject>();
		
		// Instantiate a GameObject from our prefab, using the normal Unity method, add a sprite object
		GameObject myGameObject = Instantiate(prefab);

		// Load the Sprite using the same method as before with the prefab
		AssetReference spriteReference = component.MySprite;
		Sprite sprite = spriteReference.GetAsset<Sprite>();
		
		// Add a spriteRenderer so we can render our sprite
		SpriteRenderer spriteRenderer = myGameObject.AddComponent<SpriteRenderer>();
		spriteRenderer.sprite = sprite;
	}
}

Assigning RPGObject references in the inspector

Add our new MonoBehaviour to an object and go back to the Database Editor. Click the "Object Reference ID" to copy it to the clipboard and paste it into the "Character Reference" field on our new Unity component. If it works correctly, it will state the object name next to the reference field. image

Now press Play and watch as our sprite is rendered!

image