0
\$\begingroup\$

I have a simple code that will be enabled when I kick, so I disable it right away but even though it is disabled, it works somehow. can it be because of his parent or something else I dont know of?

//this is the script Kick_Test, i dont reach it from anywhere else
private GameObject ball;
private Rigidbody2D rg2d;
public int power = 30;

void Start()
{
    ball = GameObject.FindGameObjectWithTag("Ball");
    rg2d = ball.GetComponent<Rigidbody2D>();
    this.enabled = false;
}

private void OnTriggerEnter2D(Collider2D col)
{
    if(col.tag == "Ball")
    {
        Debug.Log("KİCK");
        Vector2 pos = (transform.position - col.gameObject.transform.position).normalized;
        rg2d.AddForce(-pos * power, ForceMode2D.Impulse);
    }
}

Example

\$\endgroup\$
  • \$\begingroup\$ You say that it prints a console message, however you didn't show the console. You also haven't insured that this script isn't attached to another object (where it is enabled). \$\endgroup\$ – Draco18s no longer trusts SE Dec 16 '19 at 20:33
0
\$\begingroup\$

Consulting the documentation on OnTriggerEnter2D:

Trigger events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.

So, this behaviour is exactly what we'd expect based on the docs.

If you want to ignore these messages, just put:

if (this.isActiveAndEnabled == false)
    return;

at the top of your method to early-out when you're currently disabled.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ so disabling the script would be useless in my case. but how come it works on this video? youtube.com/… \$\endgroup\$ – ZozeR Dec 17 '19 at 21:35
  • \$\begingroup\$ Only as useless as you choose. As shown above, you can use the disabled state to skip the trigger handler if that's how you'd like it to work. \$\endgroup\$ – DMGregory Dec 17 '19 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.