I could not get Finish Line script to work

Not sure why but the Finish Line script would not trigger. I ended up putting the code for the finish line in the Crash Detector instead. I had tried to add the Finish Line script as a component to both my Finish Line object and the box collider for it, neither made a difference. This is what the code was. Not sure why it wouldn’t work.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class FinishLine : MonoBehaviour
{

void OnTriggerEnter2D(Collider2D other) 
{
    if (other.tag == "Player")
    {
        SceneManager.LoadScene(0);
    }

}

}

I’d hazard a guess that “IsTrigger” isn’t set to true on your box collider… either that or the box collider isn’t sized to trigger with what’s crossing the finish line.

If you didn’t mean to check for a Trigger, you’ll want to use OnCollisionEnter2D(…)

IsTrigger is set on both the box collider for the Finish Line and the circle collider for the Player.

Like I said I ended up putting it in Crash Detector and works great(this of course has the namespace code in it):

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.SceneManagement;

public class CrashDetector : MonoBehaviour

{

[SerializeField] float crashDelay = 0.5f;

[SerializeField] float finishDelay = 1.2f;

void OnTriggerEnter2D(Collider2D other)

{

    if (other.tag == "Ground")

    {

        Debug.Log("You crashed!");

        Invoke(nameof(ReloadScene), crashDelay);

    }

    if (other.tag == "Finish Line")

    {

        Debug.Log("You Win!");

        Invoke(nameof(ReloadScene), finishDelay);

    }

}

void ReloadScene()

{

    SceneManager.LoadScene(0);

}

If your code solved the problem we wanted to solve in this lecture, that’s great. In many cases, there are multiple ways to do something in Unity. :slight_smile:


See also:

Thanks Nina! Yes I figured as much, I was curious why it wouldn’t work for me, but I must be missing something in particular, which OCD bugs me about, but I will move on! I also figured maybe posting my code/outcome might help someone else in the course.

You could add a few Debug.Logs to your code to figure out where the code stops working as expected. Maybe there is/was a typo in the tag or the string. That’s difficult to tell because the object (“code”) gets executed and fed with data during runtime. Just by looking at it, we do not know what exactly the OnTriggerEnter2D method is receiving when it is called during runtime.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.