Unity – Programmatically Enable/Disable a Script Component

Last updated on September 23, 2021 Pennywise Loading... One comment

This short and straight-to-the-post post shows you how to programmatically enable or disable of C# file in Unity (not using the checkbox in the Inspector panel).

Let’s say we have a C# file named Rocket that was attached to one of our game objects (the name of the game object doesn’t matter). If you want to temporarily detach it based on some conditions, you can do like this:

GetComponent<Rocket>().enabled = false;

To enable it again from the code:

GetComponent<Rocket>().enabled = true;

When the currently active scene gets reloaded or a new scene is loaded, the C# script will automatically be turned on.

Reload scene:

int sceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(sceneIndex);

Load new scene:

int sceneIndex = SceneManager.GetActiveScene().buildIndex;
int nextSceneIndex = sceneIndex + 1;
if (nextSceneIndex < SceneManager.sceneCountInBuildSettings)
{
    SceneManager.LoadScene(nextSceneIndex);
}

Happy coding!

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
Kanevskyy
Kanevskyy
6 months ago

Thank you, it helps a lot

You May Also Like