当玩家对其中一个游戏对象进行攻击时,所有游戏对象(敌人)都会被摧毁。我希望它能够摧毁游戏对象(敌人),如果它与当前的游戏对象发生碰撞,而其他的则不会被摧毁。所有的敌人都有相同的剧本。
这是附加在 MainCharacter 游戏对象中的运动脚本..
public class Movement : MonoBehaviour
{
public float movementSpeed = 6.0f;
public GameObject player;
public int jumpHeight = 350;
private bool onGround = false;
private bool afterMovingPlatform = false;
Animator anim;
//// Use this for initialization
void Start()
{
anim = GetComponent<Animator>();
player = GetComponent<GameObject>();
}
void Update()
{
//these are the codes for keyboard inputs when walking, attacking, etc...
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Ground")
{
onGround = true;
if (afterMovingPlatform)
{
transform.parent = null;
afterMovingPlatform = false;
}
}
if ((coll.gameObject.tag == "Respawn" || coll.gameObject.tag == "Enemy") && (this.anim.GetCurrentAnimatorStateInfo(0).IsName("Attack Right") || this.anim.GetCurrentAnimatorStateInfo(0).IsName("Attack Left")))
{
EnemyHealth.giveDamage();
}
else if (coll.gameObject.tag == "Respawn" || coll.gameObject.tag == "Enemy")
{
CoinScore.score = 0;
Health.health = 3;
EnemyHealth.enemyHealth = 1;
SceneManager.LoadScene("LevelF");
Debug.Log("RESPAWN");
}
if (coll.gameObject.tag == "MovingPlatform")
{
onGround = true;
afterMovingPlatform = true;
transform.parent = coll.transform;
}
}
//void onCollisionExit2D(Collision2D coll)
//{
// Debug.Log("EXIT");
// if (coll.gameObject.tag == "MovingPlatform")
// {
// transform.parent = null;
// }
//}
}
脚本附加到敌人身上。他们都统一输入了敌人生命值:1。
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
public static int enemyHealth = 1;
public Transform explosion;
public int enemyHealths;
CircleCollider2D coll;
// Use this for initialization
void Start () {
coll = GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
enemyHealths = enemyHealth;
if (enemyHealths <= 0)
{
Instantiate(explosion, transform.position, transform.rotation);
Destroy(coll.gameObject);
}
}
public static void giveDamage()
{
enemyHealth -= 1;
}
}
仅仅因为函数
giveDamage
被声明为static
(敌人健康成员也是如此)
使用static修饰符来声明静态成员,该成员属于类型本身而不是特定的对象。
因此,每个敌人都有相同的生命值,当你伤害一个敌人时,事实上,你伤害了所有敌人。
每个敌人都必须有自己的生命值。删除
static
关键字并在播放器脚本中执行以下操作
if ((coll.gameObject.tag == "Respawn" || coll.gameObject.tag == "Enemy") && (this.anim.GetCurrentAnimatorStateInfo(0).IsName("Attack Right") || this.anim.GetCurrentAnimatorStateInfo(0).IsName("Attack Left")))
{
coll.gameObject.GetComponent<EnemyHealth>().giveDamage();
}