I had to work closely and deviate from the course material, using ChatGPT after the lesson on if
statements and tags. To summarize the issues found in Delivery.cs
:
The provided Unity C# script contains several problems that may cause compilation errors or unexpected behavior. The first issue is an incorrect class declaration, where the script defines two classes, Collision
and Delivery
, without proper structure. The Delivery
class should be the only class in the script or placed in a separate file. Another critical issue is that OnTriggerEnter2D(Collider2D other)
is mistakenly nested inside OnCollisionEnter2D(Collision2D other)
, which is not valid in C#. Each method should be independent, and OnTriggerEnter2D
must not be placed inside another function. Additionally, the OnCollisionEnter2D
method is completely empty, meaning it serves no purpose. If it is meant to be included, it should at least contain a Debug.Log()
statement for testing; otherwise, it should be removed to avoid confusion.
Another issue is the use of other.tag == "TagName"
to compare object tags. While this works, the recommended approach is to use other.CompareTag("TagName")
, which is optimized for performance and prevents potential errors if an object has no tag assigned.
The corrected version of the script ensures that OnTriggerEnter2D
is properly structured as its own method, OnCollisionEnter2D
is either implemented or removed, and CompareTag("TagName")
is used instead of other.tag == "TagName"
. These fixes will ensure the script follows best practices and functions correctly in Unity.
Here is an updated version of the code that actually works. I highly recommend that the course creator updates this lesson, as it caused a lot of confusion while trying to learn. Moving forward, I am concerned that future lessons may conflict with the corrections I have made. Unfortunately, this experience has led me to lose some trust in the course, as I shouldn’t have to rely on ChatGPT to correct fundamental mistakes in the material. Now, I feel like I don’t have as solid an understanding of how tags and collisions work as I should.
Here is the updated code that worked for me:
using UnityEngine;
public class Delivery : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other) // 🔥 FIXED: Changed Collision2D to Collider2D
{
if (other.gameObject.CompareTag("PowerUp"))
{
Debug.Log("I am a PowerUp, I make you go zoom zoom");
}
else if (other.gameObject.CompareTag("Package"))
{
Debug.Log("I am a Package, thank you for picking me up <3");
}
else if (other.gameObject.CompareTag("Customer"))
{
Debug.Log("Hey! Where's My Package?");
}
}
}