我以前从未做过,对类的真正理解也不是很好。但是,我计划在此项目之后掌握它!我想做的是创建一个类,通过TAG确定敌人的类型:Enemy1或Boss。 (我已经设计了一个将Enemy1统计信息随机化的系统,所以没有两个会是相同的。但是,在这里,我只想学习如何正确设置敌人的统计信息,所以这是我的代码)
using System.Collections;
public class Enemies : MonoBehaviour {
public float MaxHp;
public static float Hp;
GameObject enemy = GameObject.Find("Enemy1");
GameObject boss = GameObject.Find("Boss");
void Awake()
{
AssignStats(enemy, MaxHp);
}
public static void AssignStats (GameObject en, float MaxHp)
{
if (en.tag == "Enemy1")
{
MaxHp = 50;
Hp = MaxHp;
Debug.Log(Hp);
}
if (en.tag == "Boss")
{
MaxHp = 500;
Hp = MaxHp;
Debug.Log(Hp);
}
}
}
此代码似乎无效。为什么?
答案 0 :(得分:3)
敌人类:Enemy.cs(不是Monobehavior)
array.each { |e| puts e.last }
# => gl_personal_care_appliances
# => gl_drugstore
# => gl_pantry
# => gl_pet_products
# => gl_grocery
}
敌人类别:管理所有敌人并在敌人之间随机分组的Enemies.cs
using UnityEngine;
[System.Serializable]
public class Enemy
{
public EnemyType EnemyType;
public GameObject EnemyPrefab;
public string EnemyTag;
public int MaxHealth;
public int EnemyDamage;
public Vector3 SpawnPos;
private int _currentHealth;
public void Init()
{
_currentHealth = MaxHealth;
}
public void UpdateHealth(int newHealthValue)
{
_currentHealth = newHealthValue;
}
public void ReceiveDamage(int damage)
{
var updatedHealth = _currentHealth - damage;
UpdateHealth(updatedHealth > 0 ? updatedHealth : 0);
}
您可以看到我在检查器中分配了所有敌人数据,这些数据来自敌人类别中的敌人阵列,它具有敌人预制件,位置,伤害等。
如果您有任何疑问,请随时提问:)
干杯!
答案 1 :(得分:2)
如果我理解错误。
您不需要将参数传递给AssignStats
方法,因为类中所有您需要的属性。
我将使用gameObject.tag
来获取当前的附加对象标签。
如果附加到Enemy1
组件,则将执行gameObject.tag == "Enemy1"
条件。
如果附加到Boss
组件,则将执行gameObject.tag == "Boss"
条件。
您只需将脚本附加到角色组件并标记正确的标记即可。
using System.Collections;
public class Enemies : MonoBehaviour {
public float MaxHp;
public float Hp;
void Awake()
{
AssignStats();
}
public void AssignStats ()
{
if (gameObject.tag == "Enemy1")
{
MaxHp = 50;
Hp = MaxHp;
Debug.Log(Hp);
}
if (gameObject.tag== "Boss")
{
MaxHp = 500;
Hp = MaxHp;
Debug.Log(Hp);
}
}
}
答案 2 :(得分:1)
我会这样:
//enum contains all your enemies
public enum EnemyType
{
Enemy1,
Boss
}
public class Enemies : MonoBehaviour
{
//This will be assigned in the inspector
public EnemyType CurrentEnemyType;
//You don't need them to be public since you are hardcoding them.
private float MaxHp;
private float Hp;
void Awake()
{
AssignStats();
}
public void AssignStats()
{
if (gameObject.CompareTag(CurrentEnemyType.ToString()))
{
if (CurrentEnemyType == EnemyType.Enemy1)
{
MaxHp = 50;
Hp = MaxHp;
Debug.Log(Hp);
}
// instead of doing separated if blocks, you need to do if else for less code execution
else if (CurrentEnemyType == EnemyType.Boss)
{
MaxHp = 500;
Hp = MaxHp;
Debug.Log(Hp);
}
/*
More simplified way instead of the if else, if you assume that all your enemies except the boss have 50 hp.
MaxHp = CurrentEnemyType == EnemyType.Boss ? 500 : 50;
Hp = MaxHp;
Debug.Log(Hp);
*/
}
}
}
干杯!