- Home /
How to swap gameObjects on the press of a button?
I feel like I have the script right but there's something off on the Unity side rather than the c# side. When I do testing with
gameobject.SetActive(true);
it seems to freak out on the change and have no camera attached to the model. When I attach a camera to the model that it is going to be swapped for (a prefab) everything about the prefab gets wiped ei. the model, the camera attached and the scripts. It becomes an empty :(
.
Is there a way of changing JUST the model, I don't want to change anything else. I want all scripts to keep running like it's the same model, the camera to keep following it like it's the same model. All I want is for it to be the exact same but the model changes AND NOTHING ELSE.
Answer by Nick15104 · Jun 16, 2018 at 06:28 AM
You will want to add a camera component to your prefab so you will be able to see after the main camera is disabled. By pressing the E button on your keyboard the camera will be disabled. You will want to create an empty game object and put the camera and the prefab into it so you can have the same position. Don't forget to assign your camera and prefab into the public gameobjects to know which object to use.
public gameObject camera;
public gameObject prefab;
void Update()
{
if(Input.GetKeyDown(KeyCode.E)
{
camera.gameObject.SetActive(false);
prefab.gameObject.SetActive(true);
}
// Other Possibility of on button released
if (Input.GetKeyUp(KeyCode.E)
{
camera.gameObject.SetActive(true);
prefab.gameObject.SetActive(false);
}
}