目錄
前言
一、簡單的使用
新增ChestInteractableEvents,定義寶箱交互事件
新增Box
箱子掛載腳本,配置事件
運行效果
二、完善各種事件
1. 完善生成金幣事件
效果,金幣飛出
2. 完善生成敵人事件敵人
效果
3. 完善生成藥水事件
效果
最終效果
前言
如何在Unity中結合隨機功能和UnityEvent事件使用?下面通過一個具體示例來說明。
如果你對隨機數生成和UnityEvent事件系統感興趣,建議進一步深入學習。
(注:本文為學習筆記整理,希望能對你有所幫助)
下面開始具體講解:
一、簡單的使用
新增ChestInteractableEvents,定義寶箱交互事件
[System.Serializable] public class ChestInteractableEvents {[Header("寶箱事件名稱")]public string EventName;[Range(0f, 1f), Header("掉落幾率")]public float DropChance = 0.5f;[Header("寶箱交互事件")]public UnityEvent ChestInteractionEvent; }
新增Box
public class Box : MonoBehaviour {[Header("寶箱交互事件數組")][SerializeField] private ChestInteractableEvents[] _chestInteractionEvents;//測試執行private void Update(){if (Input.GetKeyDown(KeyCode.Space)){DetermineAndFireChestEvent();}}private void DetermineAndFireChestEvent(){// 計算總的掉落幾率float totalChance = 0f;foreach (ChestInteractableEvents interactableEvents in _chestInteractionEvents)totalChance += interactableEvents.DropChance;float rand = Random.Range(0f, totalChance); // 生成一個隨機數,范圍是0到總掉落幾率float cumulativeChance = 0f;foreach (ChestInteractableEvents interactableEvents in _chestInteractionEvents){cumulativeChance += interactableEvents.DropChance;if (rand < cumulativeChance){interactableEvents.ChestInteractionEvent.Invoke(); // 觸發寶箱交互事件return;}}}// 生成金幣public void SpawnCoins(){Debug.Log("生成了一個金幣");}// 生成敵人public void SpawnEnemies(){Debug.Log("生成了敵人");}// 生成生命藥水public void SpawnHealthPotion(){Debug.Log("生成了一個生命藥水");} }
箱子掛載腳本,配置事件
運行效果
二、完善各種事件
1. 完善生成金幣事件
[Header("生成金幣")] [SerializeField] private Rigidbody2D _coinToSpawn; // 要生成的金幣剛體 [SerializeField] private int _numberofCoinsTospawn = 100; // 要生成的金幣數量 [SerializeField] private float _explosionForce = 10f; // 金幣爆炸力度 [SerializeField, Range(0f, 0.5f)] private float _explosionArc = 0.5f; // 金幣爆炸角度范圍 [SerializeField] private bool _delayBetweenspawns = false; // 是否延遲生成金幣 [SerializeField] private Transform _spawnTransform; // 生成金幣的位置/// <summary> /// 生成金幣 /// </summary> public void SpawnCoins() {if (!_delayBetweenspawns){// 直接生成金幣for (int i = 0; i < _numberofCoinsTospawn; i++){Rigidbody2D coinRB = Instantiate(_coinToSpawn, _spawnTransform.position, Quaternion.identity);Explosion(coinRB);}}else{// 延遲生成金幣StartCoroutine(SpawnCoinsWithDelay());} }/// <summary> /// 延遲生成金幣 /// </summary> /// <returns></returns> private IEnumerator SpawnCoinsWithDelay() {for (int i = 0; i < _numberofCoinsTospawn; i++){Rigidbody2D coinRB = Instantiate(_coinToSpawn, _spawnTransform.position, Quaternion.identity);Explosion(coinRB);yield return null;} }/// <summary> /// 金幣爆炸效果 /// </summary> /// <param name="rb"></param> private void Explosion(Rigidbody2D rb) {Vector2 randDir = new Vector2(Random.Range(-_explosionArc, _explosionArc), 1f);Vector2 force = randDir.normalized * _explosionForce;rb.AddForce(force, ForceMode2D.Impulse); }
效果,金幣飛出
2. 完善生成敵人事件敵人
[Header("生成敵人")] [SerializeField] private GameObject[] _enemiesToSpawn; // 要生成的敵人數組 [SerializeField] private GameObject _enemySpawnParticles; // 敵人生成時的粒子效果 [SerializeField] private int _numofEnemiesToSpawn = 3; // 要生成的敵人數量 [SerializeField, Range(0f, 15f)] private float _enemySpawnoffset = 2f; // 敵人生成的偏移距離/// <summary> /// 生成敵人 /// </summary> public void SpawnEnemies() {for (int i = 0; i < _numofEnemiesToSpawn; i++){int randIndex = Random.Range(0, _enemiesToSpawn.Length);float randX = Random.Range(-_enemySpawnoffset, _enemySpawnoffset);float randY = Random.Range(-_enemySpawnoffset, _enemySpawnoffset);Vector2 spawnPos = ((Vector2)_spawnTransform.position + new Vector2(randX, randY)).normalized;GameObject enemy = Instantiate(_enemiesToSpawn[randIndex], spawnPos, Quaternion.identity);//生成粒子效果GameObject enemySpawnParticles = Instantiate(_enemySpawnParticles, spawnPos, Quaternion.identity);//粒子效果和敵人大小一致enemySpawnParticles.transform.localScale = enemy.transform.localScale;} }
效果
3. 完善生成藥水事件
[Header("生成生命藥水")] [SerializeField] private Rigidbody2D _healthPotionToSpawn; // 要生成的生命藥水剛體 [SerializeField] private float _upwardForce = 5f; // 生命藥水向上的力度/// <summary> /// 生成生命藥水 /// </summary> public void SpawnHealthPotion() {Rigidbody2D rb = Instantiate(_healthPotionToSpawn, _spawnTransform.position, Quaternion.identity);Vector2 force = Vector2.up * _upwardForce;rb.AddForce(force, ForceMode2D.Impulse); }