我得到了这样的脚本,可以从主摄像机创建光线投射并击中敌人。
void FixedUpdate(){
if (fire) {
fire = false;
RaycastHit hit;
if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range)){
if (Enemy.distance < 80) {
if (hit.collider.tag == "body") {
Debug.Log ("Bullet in the body.");
Enemy.bodyshot = true; //Changing other script variable.
} else if (hit.collider.tag == "head") {
Debug.Log ("Bullet in the head.");
Enemy.headshot = true; //Changing other script variable.
}
}
}
}
}
敌人脚本更新中;
if (headshot) { //headshot variable is static to reach from other script.
anim.SetTrigger ("isDying");
speed = 0;
death = true;
}
if (bodyshot) { //bodyshot variable is static to reach from other script.
anim.SetTrigger ("isSore");
}
所以,当我射杀一个敌人时,所有的敌人都会同时死亡。因为这些脚本附加到所有敌人身上。我需要在不使用静态的情况下更改身体射击和爆头变量。我该怎么做才能将它们分开?
对于光线投射,您只需要将光线投射脚本附加到空游戏对象。它不必附加到要对其执行光线投射的每个对象。
只有当您使用Unity 事件系统检测对对象的点击时,您才必须将脚本附加到要检测点击的游戏对象。
因此,请从其他游戏对象中删除此脚本,并将其附加到一个游戏对象。
注意:
如果要访问光线刚刚击中的游戏对象或对其执行某些操作,则游戏对象存储在命中变量中。
RaycastHit hit;...
Destroy(hit.collider.gameObject);
您还可以访问附加到对象命中的脚本:
hit.collider.gameObject.GetComponent<YourComponent>().doSomething();
您可以先检查以确保碰撞体是附加到对象的碰撞体之一,而不是检查碰撞体的标签是什么,然后检查标签的主体位置。例如:
public Collider[] coll;
void Start() {
coll = GetComponents<Collider>();
}
void FixedUpdate(){
if (fire) {
fire = false;
RaycastHit hit;
if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range)){
if (Enemy.distance < 80) {
if (hit.collider == coll[0] || hit.collider == coll[1]) {
if (hit.collider.tag == "head"){
或者为了简化起见,您可以将 coll[0] 设为头部和 [1] 主体,并忽略检查标签。
编辑:正如程序员所提到的,这不是一种有效的方法,因为您将为每个具有此脚本的对象投射光线,而您实际上只想投射一条光线。