"Specified cast is not valid." Error when instancing a node.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 9BitStrider

Been having trouble instancing the next scene in my game during the fade-to-black transition.

    public void animDone(string animName)
    {
        //Get the animation node again.
        var animNode = GetNode("anim") as AnimationPlayer;

        //Perform actions based on the completed animation.
        if(animName.Equals("toBlack"))
        {
            //Emit the signal to let sceneManager know to swap scenes.
            EmitSignal("transitioned");
            //Fade the screen back in.
            animNode.Play("toNormal");
        }
        if(animName.Equals("toNormal"))
        {
            //Grab global input again to renew player control.
            var globalInput = (globalInput)GetNode("/root/globalInput");

            //Allow player input again.
            if(!globalInput.allowCtrl)
            {
                globalInput.allowCtrl = true;
            }
        }
    }

All of the above works as it should. I’ve narrowed down the problem to the transitioned() loop.

public void transitioned()
{
    //Grab currentScene.
    var currScene = GetChild(0);

    //Set the appropriate scene ID. This will be expanded later for additional screens.
    if(sceneID == 0)
    {
        sceneID += 1;
    }

    //Remove the old scene.
    currScene.GetChild(0).QueueFree();

    //Load the new scene as an instance.
    var loadScene = (PackedScene)ResourceLoader.Load(Convert.ToString(sceneDict[sceneID]));

    //Be sure to set the right node type.
    if(sceneID == 1)
    {
        Control newScene = (Control)loadScene.Instance();
        currScene.AddChild(newScene);
    }
}

Everything works fine until I get to the Control newScene = (Control)loadScene.Instance(); line. That’s when I encounter the above error and nothing I do seems to help. What can I do?

EDIT: Also, yes. The class in the script for the new scene is set to Control.

Does this work ?

currScene.AddChild(loadScene.Instance());

5pectre7 | 2021-11-23 00:07

Nope. I ended up making an all new scene and testing it that way. Despite the root of the scene being control, it wouldn’t load. (It was originally a Node2D by mistake before I changed the type to Control). Making an all new scene with the correct node type from the get-go fixed the issue. An oversight maybe?

9BitStrider | 2021-11-23 00:10