我有这个代码,但我不知道为什么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
}
您需要获取附在敌人身上的脚本的参考。然后使用该脚本来操纵健康状况。
找到游戏对象。
GameObject g = hit.collider.gameObject;
获取脚本的参考。
EnemyAI e = g.GetComponent<EnemyAI>();
操纵健康。
e.health = 0f;
如果你想成为坏蛋,就一句话。
hit.collider.gameObject.GetComponent<EnemyAI>().health = 0.0f;
额外提示:health
应该private
and EnemyAI
该变量应该有一个 setter 和一个 getter。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)