不知道如何获得敌人的健康 [英] Don't know how to get enemy's health
本文介绍了不知道如何获得敌人的健康的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码,我不知道为什么hit.collider.gameObject.GetComponent("health")
返回空值
I have this code and I don't know why hit.collider.gameObject.GetComponent("health")
is returning null
void Shoot() {
Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition - firePointPosition, bulletRange, whatToHit);
if (Time.time >= timeToSpawnEffect) {
Effect ();
timeToSpawnEffect = Time.time + 1/effectSpawnRate;
}
if (hit.collider != null) {
if (hit.collider.name == "Enemy") {
Debug.Log(hit.collider.gameObject.GetComponent("health"));
}
//Debug.Log("We hit " + hit.collider.name + " and did " + damage + " damage");
}
}
这是我的敌人剧本
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour
{
public float health = 100f;
//... rest of the code
}
推荐答案
您需要获得对附加到敌人的脚本的引用.然后使用该脚本来控制运行状况.
You need to get a reference to the script attached to the Enemy. Then use that script to manipulate the health.
找到GameObject.
Find the GameObject.
GameObject g = hit.collider.gameObject;
获取对脚本的引用.
EnemyAI e = g.GetComponent<EnemyAI>();
控制健康.
e.health = 0f;
如果想成为坏蛋,请一行.
In one line if you want to be badass.
hit.collider.gameObject.GetComponent<EnemyAI>().health = 0.0f;
奖金提示:health
应该是private
,而EnemyAI
应该具有该变量的设置器和获取器.
Bonus tip: health
should be private
and EnemyAI
should have a setter and a getter for that variable.
这篇关于不知道如何获得敌人的健康的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文