1 回答
TA贡献1890条经验 获得超9个赞
因此,为了使代码正常工作,我必须从 Update() 内部删除代码。然后我创建了一个函数并将我的代码粘贴到它的 DropItem() 中。然后我不得不从代码中完全删除enemyHP <=0。
下一步是进入我的 EnemyDamage 脚本,创建一个新的变量 private ItemDrop getItem,最后,在 OnCollisionEnter2D() 的内部,我添加了一个在敌人死亡时快速检查 ItemDrop 的功能。源代码如下。
最终完成和工作的代码是:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemDrop : MonoBehaviour
{
[SerializeField]
private GameObject[] itemList; // Stores the game items
private int itemNum; // Selects a number to choose from the itemList
private int randNum; // chooses a random number to see if loot os dropped- Loot chance
private Transform Epos; // enemy position
private void Start()
{
// itemList = CamFollow.itemListPass;
Epos = GetComponent<Transform>();
Debug.Log(itemList);
}
public void DropItem()
{
randNum = Random.Range(0, 101); // 100% total for determining loot chance;
Debug.Log("Random Number is " + randNum);
if (randNum >= 95) // Star Tablet drop itemList[2] currently
{
itemNum = 2;// grabs the star tab
Instantiate(itemList[itemNum], Epos.position, Quaternion.identity);
}
else if (randNum > 75 && randNum < 95) // Extra life drop itemList[1] currently
{
itemNum = 1;// grabs the star tab
Instantiate(itemList[itemNum], Epos.position, Quaternion.identity);
}
else if (randNum > 40 && randNum <= 75)// Health Heart drop itemList[0] currently
{
itemNum = 0;// grabs the star tab
Instantiate(itemList[itemNum], Epos.position, Quaternion.identity);
}
}// End of drop item
}
*********************************** 现在在我的 EnemyDMG 脚本中:(下)****** ******************************
public class EnemyDMG : MonoBehaviour
{
private int enemyHP;
private ItemDrop getItem;
private void Start()
{
enemyHP = Random.Range(50, 200);
getItem = GetComponent<ItemDrop>();
}
// Below this code is inside of a simple OnCollisionEnter2D() function
// The enemy damage is calculated inside of this same function
// so I decided not to add any source code not directly relevant to my question
if(enemyHP <= 0)
{
if (getItem != null)
{
getItem.DropItem();
Debug.Log("Dropped an Item " + getItem);
}
Destroy(gameObject);
}
}
- 1 回答
- 0 关注
- 258 浏览
添加回答
举报
