How do I swap gameObjects in a single-player game using C#?

I’m making a 2.5D platformer and my character has two different forms of movement: one is an avatar with regular walking/jumping and the other is a rolling sphere. They’re meant to act as a single character and I would like to be able to swap from one GameObject to another whenever [space] is pressed down, maintaining the same location as before. I believe it’s just a matter of switching the mesh rendering on and off between the two objects, however, they would move at different speeds. I’m still pretty new to Unity and C# so I’m not sure how to make this happen in the script.

I appreciate any help.

I think this would work but it’s complex. Also if the gameobject has children or components you’d like to keep each time it’s created this could be very useful

-create an empty gameobject rename it to whatever (I’m going to call it playerContainer)

–(if you already have not created the Resources folder for Resources.Load go ahead and do that in the assets folder

-drag the player form gameobjects you’ve already made into the Resources folder


-Implement the following into the script on playerContainer
int form = 1;
float speed = 1f;

void Start(){
    Instantiate(Resources.Load("playerForm1"));
}

void Update(){
    if(Input.GetKeyDown(KeyCode.Space)){
        if(form == 1){
            form++;
            Destroy(gameObject.transform.GetChild(0));
            Instantiate(Resources.Load("playerForm2") as GameObject);
            //since you mentioned speed reduction I'm guessing you want the speed to be changed. Change the code if this isn't the speed you want
            speed = 0.5f;
        }else{
            form--;
            Destroy(gameObject.transform.GetChild(0));
            //Resouces.Load basically looks for the prefab in the Resources folder. Just for reference
            I called the form gameobject playerForm1 and playerForm2. You can keep what you already 
            have just change the names
            Instantiate(Resources.Load("playerForm1") as GameObject);
            speed = 1f;
        }
    }
}

-Make sure that any movement scripts are on the playerContainer GameObject.

I really hope this can help you somehow, if you have any questions or comments please contact me!