【问题标题】:How can I switch between scenes without destroying (freeing) the scene I'm leaving?如何在不破坏(释放)我要离开的场景的情况下在场景之间切换?
【发布时间】:2020-02-03 19:26:58
【问题描述】:

嘿,在我的游戏中有战斗。目前战斗是一个单独的场景,当玩家走到一个 NPC 面前时,我们有一点过渡,然后离开场景,我们进入战斗场景。一旦战斗场景完成,我想回到我们之前的场景,一切都完全一样。我目前有一个名为 scene_switcher 的场景切换单例,当前设置

extends Node

var _params = null

func change_scene(next_scene, params = null):
    _params = params

    # global_data is another singleton I use for storing state and other global data
    global_data.previous_scene = get_tree().get_current_scene()
    get_tree().change_scene(next_scene)

func return_to_previous_scene(params = null):
    _params = params
    get_tree().get_current_scene().free()
    get_tree().get_root().add_child(global_data.previous_scene)
    get_tree().set_current_scene(global_data.previous_scene)

func get_param(name):
    if _params != null and _params.has(name):
        return _params[name]
    return null

当我们进入战斗时我会使用

scene_switcher.change_scene("res://battlescene.tcsn", {players_deck, opponents_deck})

它完全按原样存储当前场景并将玩家数据传递给战斗场景。

战斗结束后,我会拨打return_to_previous_scene(),当满足其中一个胜利条件时,我会拨打此电话

scene_switcher.return_to_previous_scene()

但是我得到了错误:

Attempted to free a locked object (calling or emitting).

我尝试根据此代码 on the singleton autoload page of the docs 将呼叫推迟到空闲时间,但是当我这样做时:

 call_deferred("scene_switcher.return_to_previous_scene") 

它永远不会被调用(game_over 函数工作,它打印出结果,我的其他测试让它与下面的代码一起工作,我认为场景永远不会空闲,这意味着代码永远没有机会触发)

现在我可以使用了:

scene_switcher.change_scene("res://map.tcsn", {})

但这会将场景恢复到其原始状态并且扩展性不是很好(如果我可以在 12 个不同级别与人战斗,我怎么知道要加载哪个场景?)

那么我怎样才能停止当前场景。离开,然后带着一切回到之前的场景,我怎么离开了呢?谢谢:)

【问题讨论】:

    标签: scene godot gdscript


    【解决方案1】:

    我问了这个same question on reddit 并得到了解决我问题的答案。复制到这里以供将来可能会发现此问题的任何人使用。全部归功于/u/thomastc

    Their answer:

    call_deferred takes a method name only, so:
    
    scene_switcher.call_deferred("return_to_previous_scene")
    
    Alternatively, just use queue_free instead of free, to defer only the freeing.
    

    我没有正确使用 call_deferred。

    我还在change_scene 的场景中使用duplicate() 进行了轻微修改,以保留未释放的副本。

    所以

    global_data.previous_scene = get_tree().get_current_scene()
    

    成为

    global_data.previous_scene = get_tree().get_current_scene().duplicate()
    

    现在按预期工作:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 2016-09-09
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多