Sitemap
Sean Duggan

Sean Duggan

Everyone Loves Large Chests^K^K Treasure — Make It Exciting

2 min readJan 24, 2025

Let’s set up a treasure chest. I have this sci-fi container from Filebase that conveniently has a lid with an appropriate pivot point (I wish that every one of them had that set up properly…)

Let’s set up some loot for the player to grab. We’ll create a script for chests and attach it. Functionally, it’s going to look a lot like our door.

public class ChestScript : MonoBehaviour
{
Animator _animator;
int _isOpenHash;
[SerializeField] bool _isOperable = true;
[SerializeField] string _cannotOperateMessage = "Can't do that, boss";

private void Awake()
{
_animator = GetComponent<Animator>();
Assert.IsNotNull(_animator);
_isOpenHash = Animator.StringToHash("IsOpen");
}

public void OperateChest(bool isOpen)
{
if (_isOperable)
{
_animator.SetBool(_isOpenHash, isOpen);
}
else
{
Debug.Log(_cannotOperateMessage);
}
}

public void ToggleChest()
{
if (_isOperable)
{
bool isOpen = _animator.GetBool(_isOpenHash);
_animator.SetBool(_isOpenHash, !isOpen);
}
else
{
Debug.Log(_cannotOperateMessage);
}
}

public void SetChestOperable(bool isOperable)
{
_isOperable = isOperable;
}
}

We’ll add an Interactable component to it and set it to toggle the Chest state of being open or not.

Get Sean Duggan’s stories in your inbox

Join Medium for free to get updates from this writer.

That works. Next, let’s add some treasure. We only want it to spawn once, upon opening. There’s a number of ways to do this, but I’m going to spawn the items in a list, one by one, at a spawn point.

public class TreasureScript : MonoBehaviour
{
[SerializeField] GameObject[] _treasureList;
[SerializeField] Transform _spawnPoint;
[SerializeField] [Range(0.1f, 5f)] float _spawnInterval;

private WaitForSeconds _spawnTimer;

private bool _hasDispensed = false;

private void Awake()
{
_spawnTimer = new WaitForSeconds(_spawnInterval);
}

public void SpawnTreasure()
{
if (_hasDispensed) return;

_hasDispensed = true;

StartCoroutine(SequentiallySpawn());
}

private IEnumerator SequentiallySpawn()
{
foreach (GameObject treasure in _treasureList)
{
Instantiate(treasure, _spawnPoint);
yield return _spawnTimer;
}
}
}

We’ll set our chest up with some cubes with particle effects and a spawn point.

And, on interaction…

OK, kind of goofy, but it suffices.

--

--