【问题标题】:Unity Editor freezing every time player shoots a bullet每次玩家射击子弹时,Unity 编辑器都会冻结
【发布时间】:2021-03-12 01:50:14
【问题描述】:

好的,这就是发生的事情:当我点击播放并左键单击拍摄时,统一编辑器冻结,我必须执行旧的 Ctrl + Alt + Del,现在,我几乎可以肯定这个脚本是问题的根源,因为当子弹射出时,这个脚本会立即添加到它上面,所以这是脚本(它叫BulletLife.cs,只是让你知道)

using System.Timers;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class BulletLife : MonoBehaviour
{
    public GameObject bullet;

    public double bulletLifeSpan = 3;
    bool bulletLifeEnded;

    public LayerMask targetMask;
    bool hasHitTarget;

    // Start is called before the first frame update
    void Start()
    {
        var bulletAge = new System.Timers.Timer(bulletLifeSpan * 1000);
        bulletAge.Elapsed += OnTimedEvent;
        bulletAge.AutoReset = false;

        while(hasHitTarget == false && bulletLifeEnded == false) {
            hasHitTarget = Physics.CheckSphere(bullet.transform.position, bullet.transform.localScale.y, targetMask);
        }

        Destroy(bullet);

        Debug.Log("Finish");
    }

    private void OnTimedEvent(System.Object Source, ElapsedEventArgs e) {
        bulletLifeEnded = true;
    }
}

另外,这是 Shoot.cs 脚本:

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

public class Shoot : MonoBehaviour 
{
    public Transform gun;
    public GameObject bullet;

    public LayerMask targetMask;

    public float bulletSpeed = 1000f;

    bool hasHitTarget = false;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetButtonDown("LeftClick")) {
            GameObject bulletInstance;
            bulletInstance = Instantiate(bullet, gun.position, new Quaternion(gun.rotation.w, gun.rotation.x, gun.forward.y, gun.rotation.z));
            bulletInstance.AddComponent<Rigidbody>();
            bulletInstance.GetComponent<Rigidbody>().useGravity = false;
            bulletInstance.GetComponent<Rigidbody>().AddForce(gun.up * bulletSpeed);
            bulletInstance.AddComponent<BulletLife>();
            bulletInstance.GetComponent<BulletLife>().bullet = bulletInstance;
        }
    }
}

注意:我使用的是 Unity 2019.4.15f1

【问题讨论】:

    标签: c# unity3d timer scripting


    【解决方案1】:

    每次你在 Start 中实例化一个子弹时,你都会这样做

    while(hasHitTarget == false && bulletLifeEnded == false) 
    {
        hasHitTarget = Physics.CheckSphere(bullet.transform.position, bullet.transform.localScale.y, targetMask);
    }
    

    这个循环永远不会结束,因为循环内部的条件都没有改变。有没有命中.. 但是光线投射的参数永远不会改变,位置不会更新,因为你仍然在同一帧中 => 无限循环 => 完全冻结主线程。


    你宁愿做的是将那个东西移动到Update,它会像例如一帧那样被调用一次

    //public GameObject bullet; // not needed
    
    public double bulletLifeSpan = 3;
    //bool bulletLifeEnded; // not needed
    
    public LayerMask targetMask;
    //bool hasHitTarget; // not needed
    
    void Start()
    {
        var bulletAge = new System.Timers.Timer(bulletLifeSpan * 1000);
        bulletAge.Elapsed += OnTimedEvent;
        bulletAge.AutoReset = false;
    }
    
    private void Update()
    {
        if(Physics.CheckSphere(transform.position, transform.localScale.y, targetMask))
        {
            Destroy(gameObject);
    
            Debug.Log("Finish");
        }
    }
    
    private void OnTimedEvent(System.Object Source, ElapsedEventArgs e) 
    {
        Destroy(gameObject);
    
        Debug.Log("Finish");
    }
    

    或将其设为单个 Coroutine

    // If Start returns IEnumerator it is automatically started as Coroutine
    // So no need to start an extra routine
    private IEnumerator Start()
    {
        // Keeps track of how long your bullet exists already
        var bulletAge = 0f;
    
        while(bulletAge < bulletLifeSpan && !Physics.CheckSphere(transform.position, transform.localScale.y, targetMask)) 
        {
            // Increase by the time passed since last frame
            bulletAge += Time.deltaTime;
     
            // "Pause" this routine, render this frame
            // and continue from here in the next frame
            yield return null;
        }
    
        Destroy(gameObject);
    
        Debug.Log("Finish");
    }
    

    顺便说一句,在Shoot 你可以缩短很多

    void Update()
    {
        if(Input.GetButtonDown("LeftClick")) 
        {
            // Note that your quaternion made no sense -> simply pass in the gun.rotation
            var bulletInstance = Instantiate(bullet, gun.position, gun.rotation);
            var rb = bulletInstance.AddComponent<Rigidbody>();
            rb.useGravity = false;
            rb.AddForce(gun.up * bulletSpeed);
            var life = bulletInstance.AddComponent<BulletLife>();
    
            // Assigning the gameObject reference is completely unnecessary 
            // within BulletLife simply use "gameObject" as show before
        }
    }
    

    您可以通过确保这些组件已经存在于您的预制对象上并正确配置来进一步缩短此时间。那么你就不需要这些行了,只需要实例化它。


    最后,您根本不应该使用 thisCheckSphere,而是让 Unity 自己处理其碰撞检测并使用 OnCollisionEnter 并根据您的需要配置您的 Collision Layers!

    您的解决方案的问题是:如果您的子弹移动速度很快,它可能只是通过一个目标而您的CheckSphere 没有注意到它,即如果它的速度高于localScale.y * 2。

    【讨论】:

    • 我是四元数和 3D 建模的新手,所以我不得不尝试一些东西......
    • 另外,由于某种原因,这段代码无法销毁游戏对象(子弹),我尝试添加 bulletAge.Start() 但没有用
    【解决方案2】:

    您的Start 方法被阻塞,从而冻结了您的游戏。 您必须使用Update 或Coroutine 进行命中测试。

        public class BulletLife : MonoBehaviour
    {
        public GameObject bullet;
    
        public double bulletLifeSpan = 3;
        bool bulletLifeEnded;
    
        public LayerMask targetMask;
        bool hasHitTarget;
    
        // Start is called before the first frame update
        void Start()
        {
             StartCoroutine(CheckHit(0, bulletLifeSpan));
        }
    
        private IEnumerator CheckHit(float interval, float lifetime){
            bool checkEveryFrame = interval <= 0;
            WaitForSeconds wait = checkEveryFrame ? null : new WaitForSeconds(interval);
            while(lifetime > 0){
                yield return wait;
                lifetime = lifetime - (checkEveryFrame ? Time.deltaTime : interval);
                hasHitTarget = Physics.CheckSphere(bullet.transform.position, bullet.transform.localScale.y, targetMask);
            
            }
            bulletLifeEnded = true;
            
            Destroy(bullet);
    
            Debug.Log("Finish");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      相关资源
      最近更新 更多