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\$
1
  • \$\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\$ Dec 16, 2019 at 20:33

1 Answer 1

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.

\$\endgroup\$
2
  • \$\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, 2019 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, 2019 at 21:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .