Raycasting problem, colliders not being recognized?

Can anyone tell me why this script isn’t working please?

The ray should be changing the skybox in the scene when hit but it doesn’t even debug collisions, cubes are tagged correctly and have colliders.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class raycaster : MonoBehaviour {
 
    // --- Raycast
    public float rayDistance = 15.0f;
 
    // --- Skyboxes
    public Material skybox1;
    public Material skybox2;
    public Material skybox3;
 
    // Use this for initialization
    void Start ()
    {
       
    }
 
    void FixedUpdate()
    {
        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;
 
        Debug.DrawLine(transform.position, transform.position + transform.forward * rayDistance, Color.red);
 
        if (Physics.Raycast(transform.position, transform.forward, out hit, rayDistance))
        {
            if (hit.transform.tag.Equals("Cube1"))
            {
                Debug.Log("Hit " + hit.collider.name);
                RenderSettings.skybox = skybox1;
            }
            else if (hit.transform.tag.Equals("Cube2"))
            {
                Debug.Log("Hit " + hit.collider.name);
                RenderSettings.skybox = skybox2;
            }
            else if (hit.transform.tag.Equals("Cube3"))
            {
                Debug.Log("Hit " + hit.collider.name);
                RenderSettings.skybox = skybox3;
            }
        }
    }
 
}

@vonbetelgeuse

Your code works fine for me.

Here some Tips/Suggestions which could help you to realize what you are doing wrong:

  • ray you are defining in your code is unsused (just remove it to keep things clear)

  • Debug.DrawLine is only visible in your Scene tab - not in the Game one

  • On which object do you attaching this script? - Check that forward direction is exactly what you want. To check that your direction is right, you can do the following:

     public Transform YourCube1;
     void FixedUpdate()
     {
     transform.LootAt(YourCube1);
     
     Physics.RayCast ...
     }
    
  • Make sure that the ray distance is long enough to reach your tagged objects

  • Not the topic, but it is recommended to use Update as much as possible instead of FixedUpdate