Raycast Not Casting!

I’m making a 2D platformer and I’m making a part where the player has a raycast go out of their head and I have the raycast code but it doesn’t work! I know it isn’t the code for it not being activated because a debug.log shows that it is and I have tried to debug this for hours and I can’t find the reason why it won’t work!

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

public class Talking : MonoBehaviour
{
    [SerializeField]
    private Text t;
    public Text h;
    public GameObject tb;
    public float Health = 100;
    public bool trialone;
    public bool trialtwo;
    public bool trialthree;
    public int CanMove = 0;
    public GameObject platform;
    public float bhv;
    public GameObject butterhead;
    public GameObject humanhead;
    public Movement m;
    Scene currentScene;
    string sceneName;
    public bool whiteprivelege;
    public bool floordanger;
    public GameObject bread;
    public GameObject knife;
    public bool finale;
    public Transform body;
    RaycastHit2D Hit;

    // Data miners, don't judge me this is a joke and don't leak this code or I will find your home adress :)

    void Update()
    {
        currentScene = SceneManager.GetActiveScene();
        sceneName = currentScene.name;

        if (finale == true)
        {
            RaycastHit2D hit = Physics2D.Raycast(body.position, Vector2.up);
            if (hit.collider.gameObject.CompareTag("God"))
            {
                Debug.Log("Pew Pew");
            }
        }

        if (sceneName == "Butterland")
        {
            h.text = $"Health: {Health}";
        }

        if(bhv == 0)
        {
            butterhead.SetActive(false);
            humanhead.SetActive(false);
        }

        if(bhv == 1)
        {
            humanhead.SetActive(false);
            butterhead.SetActive(true);
        }

        if(bhv == 2)
        {
            butterhead.SetActive(false);
            humanhead.SetActive(true);
        }

        if(CanMove == 0)
        {
            tb.SetActive(true);
        }

        if(CanMove == 1 && whiteprivelege == false)
        {
            tb.SetActive(false);
        }
    }

    IEnumerator Start()
    {
        finale = false;
        whiteprivelege = false;
        currentScene = SceneManager.GetActiveScene();
        sceneName = currentScene.name;
        CanMove = 0;
        Health = 100;
        floordanger = false;

        if (sceneName == "Butterland"){
            bhv = 0;
            tb.SetActive(false);
            bool trialone = true;
            Scene currentScene = SceneManager.GetActiveScene ();
            string sceneName = currentScene.name;
            Health = 100;
            CanMove = 0;
            bread.SetActive(false);
            h.gameObject.SetActive(false);

            yield return new WaitForSeconds(1.3f);
            CanMove = 0;
            bhv = 1;
            t.text = "I am the god of butter you insolent fool!\nHow dare you consume my offspring!\nYou will be eaten if you don't undergo three trials!";
            yield return new WaitForSeconds(4);
            bhv = 2;
            t.text = "Wait wait wait!\nDon't eat me please!\nWhat are the trials?";
            yield return new WaitForSeconds(3);
            bhv = 1;
            t.text = "In the first trial You must avoid touching extremely hot butter falling from\nthe sky! If you fail you will die!";
            yield return new WaitForSeconds(4);
            t.text = "In the second trial it is of upmost importance that you avoid falling off\nthe slippery surface and not fall on the extremely hot floor!";
            yield return new WaitForSeconds(4.7f);
            t.text = "It is absolutely crucial that you understand that for the final trial\nyou will be placed on a slice\nof bread and must avoid butter knives trying to slice you!";
            yield return new WaitForSeconds(3.3f);
            bhv = 2;
            t.text = "Is this gonna be hard?";
            yield return new WaitForSeconds(1.5f);
            bhv = 1;
            t.text = "Of course this will prove to be extremely difficult! You have devoured\nmy offspring!";
            yield return new WaitForSeconds(2);
            bhv = 2;
            t.text = "I'll try my best!";
            yield return new WaitForSeconds(2.3f);
            h.text = $"Health: {Health}";
            h.gameObject.SetActive(true);
            t.text = "Hey what's that number up there?";
            yield return new WaitForSeconds(2.3f);
            bhv = 1;
            t.text = "I must inform you that the numerical value displayed on the top right corner\nrepresents your health bar.\nif this value reaches zero,\nit will result in your demise.";
            yield return new WaitForSeconds(2.3f);
            bhv = 2;
            t.text = "I'll try to win the trials!";
            yield return new WaitForSeconds(2.3f);
            bhv = 1;
            t.text = "Let The First Trial Begin!";
            yield return new WaitForSeconds(1.5f);
            bhv = 0;
            CanMove = 1;
            t.text = "";
            One();
            yield return new WaitForSeconds(45);
            OneOver();
            CanMove = 1;
            bhv = 1;
            tb.SetActive(true);
            whiteprivelege = true;
            t.text = "How could you of possibly survived that?";
            yield return new WaitForSeconds(1.5f);
            t.text = "I've had multiple people try that trial and they all failed!\nI'm suprised you are still alive! This trial will destroy you!";
            yield return new WaitForSeconds(1);
            t.text = "Get ready!";
            yield return new WaitForSeconds(4);
            whiteprivelege = false;
            tb.SetActive(false);
            bhv = 0;
            Two();
            yield return new WaitForSeconds(5);
            floordanger = true;
            yield return new WaitForSeconds(50);
            TwoOver();
            floordanger = false;
            t.text = "I have never had someone able to survive this how did you manage to do that?";
            yield return new WaitForSeconds(5f);
            t.text = "Get ready!";
            yield return new WaitForSeconds(5f);
            bread.SetActive(true);
            knife.SetActive(true);
            Three();
            yield return new WaitForSeconds(50f);
            ThreeOver();
            t.text = "This is outrageous I'm just going to kill you myself!";
            CanMove = 0;
            whiteprivelege = false;
            bhv = 1;
            yield return new WaitForSeconds(4);
            bhv = 2;
            t.text = "Wait don't kill me please! I'm sorry for eating butter!";
            yield return new WaitForSeconds(5);
            t.text = "Wait I remember now! I forgot to give grandpa his shotgun back!";
            yield return new WaitForSeconds(6);
            bhv = 1;
            t.text = "Wait what? You have a shotgun? Don't shoot me!";
            bhv = 2;
            t.text = "Well bad day for you buckaroo you're gonna die!";
            yield return new WaitForSeconds(4);
            bhv = 0;
            finale = true;
    }   }

    void One()
    {
        trialone = true;
    }

    void OneOver()
    {
        trialone = false;
    }

    void Two()
    {
        trialtwo = true;
    }

    void TwoOver()
    {
        trialtwo = false;
    }

    void Three()
    {
        trialthree = true;
    }

    void ThreeOver()
    {
        trialthree = false;
    }
}

You are in the information gathering stage.

If in doubt, drag a collider and raycast script in, watch it work.

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Humor is great, but generally this sort of thing isn’t appropriate for a public forum:

I’m sorry for that line I added it and I forgot to remove it before I posted it, and thank you for the information!

First off, I think you should take a step back and try to understand Clean Code principles and the SOLID principles.

Clean Code Explained – A Practical Introduction to Clean Coding for Beginners (freecodecamp.org)

(67) Learn SOLID Principles with CLEAN CODE Examples - YouTube

Download the e-book Unity provides here: Level up your code with game programming patterns (unity.com)

It will make debugging and testing SIGNIFICANTLY easier. Your script you shared is a mess, to be frank.

To briefly try and assess what your code is doing, you are only raycasting if Finale is true. Which, as far as i can tell, is never set to true until after your Start coroutine completes. However, you aren’t even calling your Start coroutine in this script.

Some other small things: Why is CanMove an int if it can only be 0 or 1? That is basically a bool (true or false). Your variable names of t, h, bhv, m, etc. are all so ambiguous that you have no idea what they are. Maybe you do at this moment, but lets say you go on vacation for 2 weeks and come back. It’ll make very little sense. Or if you start to collaborate with someone, they will have no idea what those variables are related to. If you read/watch those resources i sent you, you will see what i mean.