How to turn off a collider when I activate it (Basic Sword mechanic) [2D]

Hey guys,

I am looking to turn off the box collider 2D of my characters weapon. Currently I have it to where: When the player left clicks, it will activate the box collider and when the player releases the left click, it turns off the box collider. I want it to where it activates it on left click and automatically turns it back off no matter what. I do have a cool down system to where the player can’t click for another second, but as of now the player can just hold down the mouse key to simply avoid the cool down.

This is all within the same script: PlayerSM

//Where player activates mouse click
void MeleeHandler () 
	{
		if (Input.GetKeyDown (KeyCode.Mouse0) && meleeCDbool == false) 
		{
			MeleeBox.SetActive (true);
			meleeCDbool = true;
		}

		if (Input.GetKeyUp (KeyCode.Mouse0)) 
		{
			MeleeBox.SetActive (false);
		}
	}
---------------------------------------------------------------------------------------------------------
//Cooldown for the attack

void Timers() 
	{
		if (meleeCDbool == true) 
		{
			meleeCD -= Time.deltaTime;

			if (meleeCD <= 0) 
			{
				meleeCDbool = false;
				meleeCD = MaxMeleeCD;
			}
		}
	}

Perhaps you will have better luck using the mouse functions like: https://docs.unity3d.com/ScriptReference/Input.GetMouseButtonDown.html

Maybe I don't understand your question, but if you only want the box collider to be active for a second after you click, why not just make another timer that will disable the collider after it runs out?

2 Answers

2

Colliders are components, not GameObjects. Therefore, assuming MeleeBox is a Collider it should be enabled and disabled like this:
MeleeBox.enabled = false;
Additionally, I am assuming you are calling MeleeHandlers and Timers in your Update function.
If you do that, your code should work.

My advice would be to use a co-routine here. If I understand you correctly when you click, you want the the collier to turn on then after x amount of time turn off.

 private IEnumerator MeleeHandler ()
 {
     if (Input.GetKeyDown (KeyCode.Mouse0) && meleeCDbool == false) 
     {
         MeleeBox.SetActive (true);
         meleeCDbool = true;
         yield return new WaitForSeconds(1.0f); // whatever time you want between on and off in seconds put in brackets so 1.0 would be on for 1 second then turn off 0.1 would be a tenth of a second
          MeleeBox.SetActive(false);
     }
     yield return null;
 }

This should make the collier turn off regardless of whether they hold the button or not. Just remember to make sure that you initiate the co-routine where ever you do as:

StartCoroutine("MeleeHandler"); // Rather than MeleeHandler()

Hey thanks for commenting! THIS is what I have been looking for, I don't know why I never thought of having a Coroutine! I even have some in my code from earlier, wow. Once again, thank you for this answer, I have been stuck on this for 2 days now lol Thanks!