【问题标题】:Unity Freezes When I Press The Play Button With The Instantiate Syntax C#当我使用实例化语法 C# 按下播放按钮时,Unity 冻结
【发布时间】:2020-05-26 01:12:48
【问题描述】:

每次我统一按下播放按钮时,它只是坐在那里什么都不做,我认为它与实例化语法有关,这是我的代码,这是我运行的唯一脚本。我正在尝试简单地制作我的游戏对象的网格。如果有人知道为什么那会很棒,或者如果不是,也许您知道更好的方法。谢谢!!

    using UnityEngine;

public class Script2 : MonoBehaviour
{
    public GameObject Sprite;

    void Start()
    {
        Generate();
    }
    public void Generate()
    {
        float width = Sprite.transform.lossyScale.x;
        float height = Sprite.transform.lossyScale.y; 
        for (int y = 0; y <= 100; y += 10)
        {
           for (int x = 0; x <= 100; y += 10)
            {
                GameObject Square = Sprite;
                Instantiate(Square, new Vector2(x * width, y * height), Quaternion.identity);
            }
        }
    }
}

【问题讨论】:

  • for (int x = 0; x &lt;= 100; y += 10) 应该是 for (int x = 0; x &lt;= 100; x += 10) .. 我怀疑是错字

标签: c# unity3d instantiation


【解决方案1】:

您的 x 循环有一个错误,因此它进入了无限循环。 应该是 x+=10

for (int x = 0; x <= 100; x += 10)
{
    GameObject Square = Sprite;
    Instantiate(Square, new Vector2(x * width, y * height), Quaternion.identity);
}

【讨论】:

  • 谢谢你这个工作我是编程新手,所以我怀疑这种情况会发生更多,但还是谢谢你!
【解决方案2】:

我拥有的最佳解决方案是我在创建预制网格时使用的方法,即这种方法

using UnityEngine;

public class Class1 : MonoBehaviour
{
    public GameObject Prefab;

    private void Start ()
    {

        Generate ();

    }

    public void Generate ()
    {

        float width = Prefab.transform.lossyScale.x;
        float height = Prefab.transform.lossyScale.y;

        for ( int y = 0; y < 100; y++ )
        {

            for ( int x = 0; x < 100; x++ )
            {

                Vector3 position = new Vector3 ( x * width, y * height );

                Instantiate<GameObject> ( Prefab, position, Quaternion.identity );

            }

        }

    }

}

【讨论】:

  • 请注意,lossyScale 不一定等于对象宽度......使用例如会更安全Renderer.bounds。另请注意,当您创建 100 * 100 时,OP 会创建 10 * 10 对象;)
  • 谢谢你,虽然其他人发现了我的错误,但很可能使用了你的一些代码,谢谢你的帮助
  • @derHugo 感谢您的注意,我在阅读问题时一定会误读数字,阅读时需要更加小心。
  • @BenPhil 没问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-11
  • 2019-10-20
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多