Spawned objects on death scale fix

Cheo

Active member
Hello, if you ever tried destroying crates of various scales then you must have seen that the destroyed crate prefab keeps its own scale. Here's a video showing the issue and explaining how I fixed it :


Here are the pieces of code needed in Health :

C#:
        [SerializeField] protected ObjectSpawnInfo[] m_MySpawnedObjectsOnDeath;
        public ObjectSpawnInfo[] MySpawnedObjectsOnDeath { get { return m_MySpawnedObjectsOnDeath; } set { m_MySpawnedObjectsOnDeath = value; } }

C#:
            // Spawn any objects on death, such as an explosion if the object is an explosive barrel.
            if (m_MySpawnedObjectsOnDeath != null)
            {
                for (int i = 0; i < m_MySpawnedObjectsOnDeath.Length; ++i)
                {
                    var spawnedObject = ObjectPoolBase.Instantiate(m_MySpawnedObjectsOnDeath[i].Object, m_Transform.position, m_Transform.rotation);
                    if (m_MySpawnedObjectsOnDeath[i].KeepParentScale)
                    {
                        spawnedObject.transform.localScale = m_Transform.localScale;
                    }

                    Explosion explosion;
                    if ((explosion = spawnedObject.GetCachedComponent<Explosion>()) != null)
                    {
                        explosion.Explode(gameObject);
                    }
                    var rigidbodies = spawnedObject.GetComponentsInChildren<Rigidbody>();
                    for (int j = 0; j < rigidbodies.Length; ++j)
                    {
                        rigidbodies[j].AddForceAtPosition(force, position);
                    }
                }
            }

Next here's what the top of Object Spawn Info in Unity Engine Utility should look like :

C#:
    [System.Serializable]
    public class ObjectSpawnInfo
    {
#pragma warning disable 0649
        [Tooltip("The object that can be spawned.")]
        [SerializeField] private GameObject m_Object;
        [Tooltip("The probability that the object can be spawned.")]
        [Range(0, 1)] [SerializeField] private float m_Probability = 1;
        [Tooltip("Should a random spin be applied to the object after it has been spawned?")]
        [SerializeField] private bool m_RandomSpin;
        [SerializeField] private bool m_KeepParentScale = true;
#pragma warning restore 0649

        public GameObject Object { get { return m_Object; } }
        public float Probability { get { return m_Probability; } }
        public bool RandomSpin { get { return m_RandomSpin; } }
        public bool KeepParentScale { get { return m_KeepParentScale; } }

And finally you'll just need to add this in Health Inspector in the Death foldout :

C#:
EditorGUILayout.PropertyField(PropertyFromName("m_MySpawnedObjectsOnDeath"), true);

Once again, if you're a gamer you should understand that this change I'm proposing is not superfluous at all and deserves to be present by default. Hope this is useful.
 
Top