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

问题描述 投票:0回答:1

我想实例化某些东西,使它在制作时没有刚体约束,但在几秒钟后再出现。

c# unity3d instantiation
1个回答
0
投票

进行对象预制,并添加带有此代码的脚本作为组件。(我制作了一个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;在[开始]方法中。

© www.soinside.com 2019 - 2024. All rights reserved.