-3
\$\begingroup\$

So the code down below is supposed to load the next scene once the player touches the flag which the code is attached to. I've made sure that is trigger is checked and yet I'm still getting errors from the console log like expecting '(' found 'OnCollisionEnter2D' and unexpected token: theCollision. I really tried to solve the problem on my own and searched the web for an answer but failed. Thanks in advance.

#pragma strict

function Update () {
    function OnCollisionEnter2D(theCollision : Collider2D) {
        if (theCollision.gameObject.name == "Player") {
            Application.LoadLevel("scene2");
        }
    }
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You've written your OnCollisionEnter2D function inside your Update function. You want it written after it:

function Update() {
 // Your update code goes here.
}

function OnCollisionEnter2D(collision : Collision2D)
{
 // Your collision response code goes here.
}

Also note that if you've marked the collider as a trigger, then it will never call OnCollisionEnter2D - for triggers you'll want OnTriggerEnter2D instead.

\$\endgroup\$
2
  • \$\begingroup\$ Why is it supposed to be written outside of the update function ?! I mean shouldn't this function run over and over until it's met true and how code any code work outside of update and start function anyway ? \$\endgroup\$ Commented Jun 25, 2015 at 6:01
  • \$\begingroup\$ @Harry, Unity uses an event-based model. By having an OnCollisionEnter2D method present in the class, you're telling it "call me when something happens." It's then the engine's job to check for collisions each time objects move, so you don't need to put that in your update loop - it's something the engine is doing anyway, for all objects. All it needs from you is an entry point to call when collisions do occur with this object, which is what defining an OnCollisionEnter2D method gives it. \$\endgroup\$ Commented Jun 25, 2015 at 12:07

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.