How to deal with activating/deactivating scripts (components)?

Hello!
I have general question, how to deal with method [Component].enabled. Is there commonly used function in games? Or is there any other way to deal with problems with deactiveting code for a while? On second thought, we can destroy a component and after a while we can create/attach the same component (but I think that it’s more CPU using or maybe I’m wrong, I’m new in Unity).

I thought and asked about it, because I have problems with my scripts and I don’t know is there a bug or only I do it in wrong way.

if(Input.GetButtonDown("Jump"))
{
	rollingScript.enabled = false;
	jumpingScript.enabled = false;
}

And it doesn’t work properly every time. Sometimes it doesn’t work.

In Unity, it is bad practice to destroy/recreate a component regulary during a normal game progress.

The reason is the same why you should avoid any code than creates or destroy ANYTHING regulary: Unity’s garbage collector is very bad, because a garbage collector run can cause the game to stutter.

So if you constantly allocate and free any memory, you might end up with a game that stutters and is overall sluggish.

So for your original question: Use enable = false instead of Destroy. However, be aware that disabling components might not completely turn them off. Most noticable, OnCollisionEnter events are still sent. So are user-called functions. Disabling a component just stops calling some few functions like Update().

You can also deactivate the whole gameObject with SetActive(false). This does not work on single components but only on the whole game object. On the other hand, deactivated game objects are far better “invisible” to the system than just disabled components. For example, GameObject.Find() will not return deactivated objects.

Finally, as Hellium pointed out: You should not call Input.GetButtonDown from within FixedUpdate. FixedUpdate may not be called within a frame, and GetButtonDown only returns true the frame that the user pressed the button.

The frame-rate independend correct way of grabbing input is:

bool jumpButtonPressed = false;
void Update() { if (Input.GetButtonDown("Jump")) jumpButtonPressed = true; }
void FixedUpdate()
{
    if (jumpButtonPressed)
    {
        ... // do your AddForce stuff here
        jumpedButtonPressed = false;
    }
}