【问题标题】:Why my unity editor crash? with using Instantiate为什么我的统一编辑器崩溃了?使用实例化
【发布时间】:2021-07-18 10:35:14
【问题描述】:

我运行了这段代码。 团结停止了。 1到10分钟后统一关闭 当我删除 Instantiate 时,此代码运行良好! 如何让这段代码运行良好?

Unity Editor.log 文件:https://github.com/Oein/UnityBuilds/blob/main/Editor.log.zip

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MakeGround : MonoBehaviour
{
public Sprite ground;
public Sprite leftGround;
public Sprite rightGround;

string[] map = {
    "aaaaaaaaaa",
    "aaaaaaaaaa",
    "aaaaaaaaaa",
    "zxxxxxxxxc"
};
// Start is called before the first frame update
void Awake()
{
    for (int y = 0; y < map.Length; y++)
    {
        for (int x = 0; x < map[0].Length; x++)
        {
            print(x.ToString() + "  At  " + y.ToString());
            this.transform.position = new Vector3(x, y, 0);
            if (map[map.Length - 1 - y][x] != 'a')
            {
                Instantiate(gameObject , transform);
            }

        }
    }
}

// Update is called once per frame
void Update()
{

}
}

【问题讨论】:

    标签: unity3d crash instantiation


    【解决方案1】:

    您正在实例化 gameObject,这是此脚本附加到自身的对象!

    那么会发生什么:

    • 第一个Awake被调用
    • 您实例化ngameObject
    • n 新对象也附有此脚本 MakeGround
    • 所以另一个nAwake 被调用
    • 你生成 n x ngameObject
    • ..... => 无限指数实例化

    您可能更愿意使用一个专用的单独的 Prefab,它没有附加该脚本并通过例如引用它

    [SerializeField] GameObject prefabToInstantiate;
    

    然后做

    Instantiate(prefabToInstantiate, transform);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2023-03-29
      • 2015-03-02
      • 1970-01-01
      相关资源
      最近更新 更多