- Home /
How to disable and re-enable components in the same function?
Possibly not the best way to ask my question, which is pretty simple but I can't figure out how to do it
I have a custom 2D controller on a player sprite that uses its own forces, however I'd like to disable this motor and use Unity physics to perform a knockback when it takes damage, like so:
public void DoKnockback()
{
motor.enabled = false;
rb.AddForce(new Vector3(-1, 1, 0) * 200);
rb.isKinematic = false;
}
But then after that's done I need to immediately re-enable the motor and isKinematic or else the character will fall through the scenery. I was thinking WaitForSeconds but that's only useable in an IEnumerator and I couldn't for the life of me figure out how to do this in a coroutine. Any suggestions?
Answer by Inok · Nov 03, 2015 at 03:57 PM
If you want force affect body you need wait some time before you reenable kinematic body:
IEnumerator DoKnockback()
{
motor.enabled = false;
rb.isKinematic = false;
rb.AddForce(new Vector3(-1, 1, 0) * 200 , ForceMode.Impulse); // impulse mode optional if you want to push more quickly in less time.
yield return new WaitForSeconds(time); // here you set delay to give force do it job. If you not give delay and instantly reenable kinematic body it stop move by physics before it achieve all force. Delay depend on Force mode that you set (for "impulse" you can set lower delay, for "force" - higher).
rb.isKinematic = true;
motor.enabled = true;
}
Thank you! Works perfectly. I'm glad you pointed out the the custom controller taking over the Unity physics when re-enabling it, that completely slipped my $$anonymous$$d. It's a very smooth transition now. Thanks again
Answer by knudsjef · Nov 03, 2015 at 04:18 AM
Just disable it and re enable it by motor.enabled = true and rb.isKinematic = true. I don't think it should be a problem.
But I was under the impression that lines in a function don't execute sequentially