Search code examples
c#unity-game-engineinstantiation

Unity C# How do I Instantiate an object with the rigid body constraints unchecked


I want to instantiate something so that when it's made it doesn't have the rigid body constraints on but after a few seconds on again.


Solution

  • Make an object prefab and add a script with this code as a component. (I made a 2D one, just remove the 2D parts if you want to use 3D rigidbody)

    using System;
    using UnityEngine;
    
    public class DelayedConstraints : MonoBehaviour
    {
       private Rigidbody2D rb;
       private DateTime now;
       private DateTime momentToFreeze;
    
       public int secondsDelayToFreeze;
    
    
       void Start()
       {
           rb = GetComponent<Rigidbody2D>();
           now = DateTime.Now;
           momentToFreeze = DateTime.Now.AddSeconds(secondsDelayToFreeze);
       }
    
       void Update()
       {
           now = DateTime.Now;
           // we compare the hour, minute and second of the 2 times (all 3 for accuracy)
    
           if (now.Hour == momentToFreeze.Hour && now.Minute == momentToFreeze.Minute && now.Second == momentToFreeze.Second)
            rb.constraints = RigidbodyConstraints2D.FreezeAll;
           /* Possible options for constrains are:
               .FreezeAll
               .FreezePosition
               .FreezePositionX
               .FreezePositionY
               .FreezeRotation
           */
       }
    }
    

    Then, make an empty object and attach this code to it.

    using UnityEngine;
    
    public class Spawner : MonoBehaviour
    {
        public GameObject ourPrefab;
    
        void Start()
        {
            GameObject obj = Instantiate(ourPrefab, transform.position, transform.rotation);
        }
    }
    

    So, what all of this does is: You have a spawner and at the beginning of the game's runtime, it instantiates an object that you have set as a prefab. After the Seconds-delay you have set on that prefab's script passes, its RigidBody's constraints will Freeze.

    I mostly focused on the time delay, for more rigidbody constraints, I suggest you read the documentation at https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.html

    **EDIT: I forgot to mention, the prefab by default should have the constraints off. Another way is to write rb.constraints = RigidbodyConstraints2D.None; in the Start method.