【问题标题】:how to stop continous firing of automatic turrets after the enemies cross the collider?敌人越过对撞机后如何停止自动炮塔连续射击?
【发布时间】:2014-12-16 18:03:18
【问题描述】:

我有一个炮塔,作为一个游戏对象,当敌人进入它的碰撞箱时,炮塔开始向它射击,逻辑是当敌人离开对撞机时,它应该停止射击,另一个问题是当再次一个敌人进入 collison 框,即第二个敌人,它给了我一个异常,“MissingReferenceException:'transform' 类型的对象已被破坏,但您仍在尝试访问它。您的脚本应该检查它是否为 null 或你不应该破坏它”,但我正在检查我的代码中的列表是否不为空。这是我的代码

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TurretScript : MonoBehaviour {

public float shotInterval = 0.2f; // interval between shots
public GameObject bulletPrefab; // drag the bullet prefab here
public float bulletSpeed;

private float shootTime = 0.0f;
private List<Transform> targets;
private Transform selectedTarget;
private Transform myTransform;
private Transform bulletSpawn;

void Start(){
    targets = new List<Transform>();
    selectedTarget = null;
    myTransform = transform;
    bulletSpawn = transform.Find ("bulletSpawn"); // only works if bulletSpawn is a turret child!
}

    void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "enemy"){ // only enemies are added to the target list!
        targets.Add(other.transform);

    }
}

void OnTriggerExit2D(Collider2D other){
    if (other.tag == "enemy"){
        targets.Remove(other.transform);
        Debug.Log("gone out");
    }
}

void TargetEnemy(){
    if (selectedTarget == null){ // if target destroyed or not selected yet...
        SortTargetsByDistance();  // select the closest one
        if (targets.Count > 0) selectedTarget = targets[0];
    }
}

void SortTargetsByDistance(){
    targets.Sort(delegate(Transform t1, Transform t2){ 
        return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
    });
}

void Update(){
    TargetEnemy(); // update the selected target and look at it
    if (selectedTarget)
     { 
        // if there's any target in the range...
        Vector3 dir = selectedTarget.position - transform.position;
        float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);// aim at it
        if (Time.time >= shootTime){// if it's time to shoot...
            // shoot in the target direction
            Vector3 lookPos = new Vector3(bulletSpawn.position.x,bulletSpawn.position.y,0);
            lookPos = lookPos - transform.position;
            float ang = Mathf.Atan2(lookPos.y,lookPos.x)*Mathf.Rad2Deg;
            GameObject b1 = Instantiate(bulletPrefab,new Vector3(transform.position.x,transform.position.y,5),transform.rotation)as GameObject;
            b1.rigidbody2D.velocity = new Vector3(Mathf.Cos(ang*Mathf.Deg2Rad),Mathf.Sin(ang*Mathf.Deg2Rad),0)*bulletSpeed;

            shootTime = Time.time + shotInterval; // set time for next shot
        }
    }
}
}

这是我的敌人脚本

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyScript : MonoBehaviour {

public Transform target;
public float speed = 2f;

public int Health;

public float GetHealth()
{
    return Health; 
}


void Update ()
{
    transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);                                                                     
}

void TakeDamage(int damage){
    Health -= damage;
    if (Health <= 0) 
        Destroy(gameObject);
}


void OnTriggerEnter2D(Collider2D otherCollider)
{
    PlayerControl shot = otherCollider.gameObject.GetComponent<PlayerControl>();
    if (shot != null)
    {
        SpecialEffectsHelper.Instance.Explosion(transform.position);
        Destroy(shot.gameObject); 
    }
}

}

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    您需要检查所选目标是否是离开对撞机的目标。您从目标列表中删除了目标,但仍会填充 selectedTarget 变量。

    对于空引用异常。你是在使用Destroy() 杀死目标吗? Destroy() 不会引起 OnTriggerExit()OnCollisionExit() 事件调用,对象就消失了。

    编辑:您可以通过将OnDestroy() 函数添加到将其位置设置为玩家关卡/视图之外的东西的垂死对象来解决缺少调用的问题。这样目标就会离开对撞机然后消失,而不仅仅是原地消失。

    【讨论】:

    • selectedTarget 仍然像 in 一样填充?你能帮我吗,我被这两件事困住了,是的,我正在使用 destroy() 方法来杀死敌人脚本类中的对象。,更新敌人类的代码
    • “填充”不为空。您只需要在OnTriggerExit2D(...) 中添加一个if(other.transform == selectedtarget) {selectedtarget = null;}
    • 它给了我同样的缺失参考异常。
    • 您是否按照建议完成了OnDestroy() 的更改?如果可以,我们可以看到更新后的代码吗?
    • 但是,我也在从列表中删除敌人并检查该值是否为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多