Unity C# 如何在未选中刚体约束的情况下实例化对象

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

我想实例化一些东西,这样当它被制作出来时就没有刚体约束,但几秒钟后又开始了。

制作一个对象预制件并添加一个包含此代码的脚本作为组件。 (我做了一个2D的,如果要用3D刚体就去掉2D的部分)

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
       */
   }
}

然后,制作一个空对象并将此代码附加到它上面。

using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject ourPrefab;

    void Start()
    {
        GameObject obj = Instantiate(ourPrefab, transform.position, transform.rotation);
    }
}

因此,所有这一切所做的是:您有一个生成器,在游戏运行时开始时,它实例化一个您已设置为预制件的对象。在您为该预制件的脚本设置的秒延迟通过后,其 RigidBody 的约束将冻结。

我主要关注时间延迟,对于更多刚体约束,我建议您阅读 https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.html

上的文档

**编辑:我忘了说,默认情况下预制件应该关闭约束。另一种写法是 rb.constraints = RigidbodyConstraints2D.None;在 Start 方法中。