繁体   English   中英

Unity3D异步游戏对象实例化

[英]Unity3D async game object instantiation

我现在正在用Unity3D创建我的第一个项目。 这是一个2D游戏。 这是一种runner ,但玩家有可能回到某个距离。 为了暂时实现此功能,我正在执行以下操作:

  • 创建两个带有内容的屏幕(第一个在游戏开始时看到,第二个在玩家超过第一个屏幕后显示)
  • 当玩家进入下一个屏幕时,我正在计算当前屏幕的位置和尺寸以在其后创建一个新屏幕(因此从一开始就是2,而当玩家进入第二个屏幕时,第三个正在创建,依此类推)

当我在PC上对其进行测试时,一切都很好,但是由于某种原因,当创建下一个屏幕时,这会使我的手机延迟大约一秒钟,现在代码是如何运行的:

在脚本的Start()方法中,我将初始化两个场景:

    Scene scene = new Scene ();
    scene.setSceneBounds (screenBounds);
    scene.createBackground (cameraOffsetOnStart, sceneSize);
    scene.createContent ();

    sceneNumber++;
    currentScenePosition = sceneSize * sceneNumber;
    Vector2 nextScenePosition = new Vector2 (cameraOffsetOnStart.x + currentScenePosition.x, cameraOffsetOnStart.y);

    Scene scene2 = new Scene ();
    screenBounds.min = new Vector2(min.x + currentScenePosition.x, min.y);
    screenBounds.max = new Vector2(max.x + currentScenePosition.x, max.y);
    scene2.setSceneBounds (screenBounds);
    scene2.createBackground (nextScenePosition, sceneSize);
    scene2.createContent ();

然后在Update()我检查播放器是否超出当前场景并创建新场景:

void Update () {
    if (player.transform.position.x - playerOffset > sceneNumber * (max.x - min.x)) {
        Debug.Log("current scene is : " + (++sceneNumber));
        currentScenePosition = sceneSize * sceneNumber;
        Vector2 nextScenePosition = new Vector2 (cameraOffsetOnStart.x + currentScenePosition.x, cameraOffsetOnStart.y);
        Scene scene = new Scene();
        screenBounds.min = new Vector2(min.x + currentScenePosition.x, min.y);
        screenBounds.max = new Vector2(max.x + currentScenePosition.x, max.y);
        scene.setSceneBounds (screenBounds);
        scene.createBackground(nextScenePosition, sceneSize);
        scene.createWebs();
        sceneManager.Scenes.Add(scene);
    }
}

以及用于创建内容的代码:

public void createBackground(Vector2 position, Vector2 size) {
    background = new Background (position, size);
}

public void createContent() {
    Vector2[] positions = Utilities.generateRandomPositions(5, sceneBounds, 4f);

    for (int i = 0; i < positions.Length; i++) {
        Web web = ScriptableObject.CreateInstance<Web>();
        web.init(positions[i]);
    }
}

滞后的问题来自createContent方法。 init代码:

    public void init(Vector2 position) {
        if (position != Vector2.zero) {
            obj = Instantiate (Resources.Load ("Textures/web", typeof(GameObject)), position, Quaternion.identity) as GameObject;
        }
    }

很明显, Instantiate方法连续对5个对象调用5次会导致这种现象。

如果需要,可以在“纹理/纤维网”上获得更多详细信息:这是一个带有圆形碰撞器和刚体的预制件,将设置为运动学的

问题:为什么只剩下5个项目? 我使用错误的方式Instantiate了吗? 我怎样才能使其更快? 有没有一种方法可以称之为异步?

如评论中所讨论。

排队:

obj = Instantiate (Resources.Load ("Textures/web", typeof(GameObject)), position, Quaternion.identity) as GameObject;

每次调用此代码时,都从设备内存中加载资源。 只需将GameObject存储在某个变量中,例如在Start()方法中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM