不知道如何获得敌人的健康
我有这个代码,我不知道为什么hit.collider.gameObject.GetComponent("health")
返回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 }
您需要获得对Enemy附带的脚本的引用。 然后使用该脚本来操纵健康状况。
找到GameObject。
GameObject g = hit.collider.gameObject;
获取脚本的引用。
EnemyAI e = g.GetComponent();
操纵健康。
e.health = 0f;
在一行中,如果你想成为坏蛋。
hit.collider.gameObject.GetComponent().health = 0.0f;
额外提示: health
应该是private
, EnemyAI
应该有一个setter和一个getter用于该变量。
你使用的是Unity,不是吗? 从您提供的代码看起来就是这样。 GetComponent()是一个返回对游戏对象组件的引用的方法。 这些是您在编辑器中拖动到游戏对象上的内容。 像Box-Colliders和Rigidbodys这样的东西。 您编写的代码不会返回任何内容,因为Unity中没有名为“health”的游戏组件。 为了获得敌人的健康,您需要设置对控制敌人的脚本的引用,并从那里获取其健康值。
但是,您必须获取附加到GameObject的脚本的引用。 为此,您需要使用以下代码。
GameObject target;
然后在你的拍摄方法中更新目标的参考。
if(hit.collider.gameObject != target) { target = hit.collider.gameObject.GetComponent(); }
我在其周围放置一个if()语句的原因是,如果目标尚未更改,则不会使用GetComponent请求重载CPU。
从这里你只需使用诸如之类的东西来改变价值
target.value = newValue; target.SomeFunction();