如何修复“‘Transform’类型的对象已被销毁,但您仍在尝试访问它。” Unity 中的错误

问题描述 投票:0回答:0

好吧,所以我正在尝试创建一个 2.5D 横向卷轴游戏,在其中我有一个敌人向我射击,当玩家角色被击中时,它被摧毁并且场景重新开始。每当玩家被摧毁时,我都会收到提到的错误。我不知道如何解决这个问题,但我使用的代码如下。谢谢你的帮助。

public class DestroyPlayer : MonoBehaviour
{
    
    //Destroys Player Character On Contact

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("Player"))
        {
            Destroy(collision.gameObject);
        }
    }

}


This is the player spawn script as well:

public class SpawnScript : MonoBehaviour
{
    public GameObject player;
    public Transform spawnPoint;
    //When Player Character is Destroyed, Respawn Player at Point

    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            Scene currentScene = SceneManager.GetActiveScene();
            SceneManager.LoadScene(currentScene.name);
        }
    }

}



The Script in where the error is coming from:

public class TurretControl : MonoBehaviour
{
    private Transform _Player;
    private float dist;
    public float maxRange;
    public Transform barrel;
    public GameObject _projectile;

    public float fireRate, nextShot;
    public float cannonBallForce = 40.0f;
    

    void Start()
    {
        _Player = GameObject.FindGameObjectWithTag("Player").transform;
    }
    private void Update()
    {
        dist = Vector3.Distance(_Player.position, transform.position);
        if(dist <= maxRange)
        {
            if(Time.time >= nextShot)
            {
                nextShot = Time.time + 1f / fireRate;
                shoot();
            }
        }
    }
    

    void shoot()
    {
        GameObject clone = Instantiate(_projectile, barrel.position,transform.rotation);
        //Forward force
        clone.GetComponent<Rigidbody>().AddForce(-barrel.right * cannonBallForce);
        Destroy(clone, 20);
    }
}

unity3d
© www.soinside.com 2019 - 2024. All rights reserved.