如果应用 Force,Unity 中的 Pooled GameObject 会在 SetActive 后自行销毁

Pooled GameObject in Unity destroys itself after SetActive if Force is applied

当我从创建的对象列表中检索一个对象并重新激活它时,它会自行销毁,但前提是我施加了力使其开始移动。如果我从不施加力,一切都会按预期进行,我可以一遍又一遍地激活该对象。

生成代码:

    void CreateBullet(int GunID)
{
    GameObject ShotFired = Guns[GunID].GetComponent<Weapon>().FireWeapon();

    if (ShotFired == null)
    {
        ShotFired = Instantiate(Guns[GunID].GetComponent<Weapon>().Projectile,Guns[GunID].gameObject.transform);
        Physics.IgnoreCollision(ShotFired.GetComponent<SphereCollider>(), Guns[GunID].GetComponentInParent<CapsuleCollider>());
        Guns[GunID].GetComponent<Weapon>().AmmoPool.Add(ShotFired);
    }


    ShotFired.transform.position = Guns[GunID].transform.position; 
    ShotFired.transform.rotation = Guns[GunID].transform.rotation;

    ShotFired.SetActive(true);
}

弹丸代码:

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

public class Projectile : NetworkBehaviour
{
    public float Speed;
    public float LifeTime;
    public float DamagePower;

    public GameObject ExplosionFX;

    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Rigidbody>().AddRelativeForce(Vector3.up * Speed, ForceMode.VelocityChange);
        StartCoroutine(DeactivateSelf(5.0f));
    }

    private void OnDestroy()
    {
        Debug.Log("WHY!");
    }

    IEnumerator DeactivateSelf(float Sec)
    {
        yield return new WaitForSeconds(Sec);
        Explode();
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.GetComponentInChildren<Vehicle>())
        {
            collision.gameObject.GetComponentInChildren<Vehicle>().CmdTakeDamage(DamagePower);
        }

        Explode();
    }

    void Explode()
    {
        GameObject ExplosionEvent = Instantiate(ExplosionFX, this.transform.position, Quaternion.identity);
        NetworkServer.Spawn(ExplosionEvent);
        GetComponent<Rigidbody>().AddRelativeForce(Vector3.zero);

        gameObject.SetActive(false);
    }
}

欢迎任何想法。提前致谢!

万一其他人偶然发现了这个问题,下面是发生的事情,以及为什么给对象分配移动速度是导致问题的原因。

我的弹丸上有 'trailrenderer'。

默认 'Autodestruct' 为真。

Autodestruct 不破坏轨迹,而是轨迹消失时的游戏对象。所以如果你禁用任何有轨迹的东西,并通过移动激活它,当对象停止移动时(比如在对象池中重新定位)它会破坏父对象。

如果物体从不移动,它就永远不会产生轨迹,也永远不需要销毁。

要修复,只需取消选中自动销毁。

https://docs.unity3d.com/ScriptReference/TrailRenderer-autodestruct.html