创建处理生成次数和生成几率的类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable] class LootSetting
{
public GameObject prefab;
[SerializeField, Range(0f, 100f)] public float dropPercentage;//生成率
[SerializeField, Range(0f, 100f)] public int numebr;//生成个数
public void Spaw(Vector3 postion)
{
for(int i=0; i<numebr; i++)
{
if(Random.Range(0f,100f)<=dropPercentage)
{
poolManager.Release(prefab,postion);
}
}
}
}
创建跟随人物的类,这个物体在人物右边,向左边人物靠近
挂在在物体预制体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LootItem : MonoBehaviour
{
protected Player player;
[SerializeField] float minSpeed;
[SerializeField] float maxSpeed;
[SerializeField] protected AudioData pickUpSFX;
protected Text LootText;
Animator animator;
int pickUpStateID = Animator.StringToHash("PickUp");
private void Awake()
{
animator = GetComponent<Animator>();
player =FindObjectOfType<Player>();//找到挂有Player的物体的脚本
LootText= GetComponentInChildren<Text>(true);//true 获得禁用时的组件
}
private void OnEnable()
{
StartCoroutine(nameof(MoveCorotine));
}
//跟随玩家移动
IEnumerator MoveCorotine()
{
float speed=Random.Range(minSpeed,maxSpeed);
Vector3 direction = Vector3.left;//向左
while(isActiveAndEnabled)
{
if(player.isActiveAndEnabled)
{
direction=(player.transform.position-transform.position).normalized;
}
transform.Translate(direction*speed*Time.deltaTime);
yield return null;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
PickUp();
}
protected virtual void PickUp()
{
StopAllCoroutines();
animator.Play(pickUpStateID);
AudioManager.instance.PlaySFXaudio(pickUpSFX);
}
}
创建可以生成不同战利品的类,在敌人预制体上挂着
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LootSpawner : MonoBehaviour
{
[SerializeField] LootSetting[] lootSettings;
public void Spaw(Vector2 position)
{
foreach (var item in lootSettings)
{
item.Spaw(position+Random.insideUnitCircle);//insideUnitCircle在单位圆范围内 取一个 随机坐标。范围为1
}
}
}
后面在敌人死亡时调用即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : Character
{
LootSpawner lootSpawner;
protected virtual void Awake()
{
lootSpawner= GetComponent<LootSpawner>();
}
public override void Die()
{
lootSpawner.Spaw(transform.position);//生成奖品
}
}