0
\$\begingroup\$

I have a GameObject with a ragdoll in it. Gameobject comes from a prefab which is pooled. So whenever the enemy is killed it's disabled then enabled when spawn.

Problem is that the ragdoll settings and it's condition cannot be reset by enabling. i.e. enemy stays dead even though respawned.
Is there a way to easily reset a GameObject to prefab state?

Solution online is to keep all the transforms and re-apply them by code. Is this the only way?

\$\endgroup\$
  • 1
    \$\begingroup\$ It sounds like you found your solution. Have you run into any trouble putting this into practice? \$\endgroup\$ – DMGregory May 31 at 23:40
1
\$\begingroup\$

In general, its how pooling works. But there are some triks. For example, you can create a simple script, which will cahe its transform state on Awake(), and then restore every time when OnEnable called. This can be a bit heavy to have additional scripts on every bone. Som better solution is to have another, only one, which will iterate all root transform`s childs.

Like this:

using System.Collections.Generic;
using UnityEngine;

public class RestoreTransforms : MonoBehaviour
{
    private List<Transform> _transforms = new List<Transform>();
    private List<Vector3> _positions = new List<Vector3>();
    private List<Quaternion> _rotations = new List<Quaternion>();

    private void Awake()
    {
        var allTransforms = GetComponentsInChildren<Transform>();
        foreach(var t in allTransforms)
        {
            _transforms.Add(t);
            _positions.Add(t.position);
            _rotations.Add(t.localRotation);
        }
    }

    private void OnEnable()
    {
        for (int i = 0; i < _transforms.Count; ++i)
        {
            _transforms[i].position = _positions[i];
            _transforms[i].localRotation = _rotations[i];
        }
    }
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.