Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Help...

Discussion in 'Scripting' started by ShaunChad99, May 9, 2020.

  1. ShaunChad99

    ShaunChad99

    Joined:
    Apr 23, 2020
    Posts:
    26
    i need help trying to find out how i can set mt raycast to false after i have moved my raycast of a object. i have set it up with a bool, but it doesn't uncheck when i move of the object




    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player : MonoBehaviour
    6. {
    7.  
    8. public float Maxdistance = 10;
    9.     public LayerMask layermask;
    10.     public bool ObjectHit = false;
    11.  
    12. void Update()
    13.     {
    14.         RaycastHit hit;
    15.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    16.  
    17.         if (Physics.Raycast(ray, out hit, Maxdistance, layermask))
    18.         {
    19.             if (hit.collider != null)
    20.             {
    21.                 ObjectHit = true;
    22.                 print(hit.transform.name);
    23.             }
    24.         }
    25.         if (Physics.Raycast(ray, out hit, Maxdistance, layermask))
    26.         {
    27.             if (hit.collider == null)
    28.             {
    29.                 ObjectHit = false;
    30.             }
    31.         }
    32.      }
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    You have two raycasts. If no object is hit, the second check is skipped, thus if hit.collider == null, the check for that is not even executed and ObjectHit = false is never set.. Just set ObjectHit = hit.collider != null behind the first raycast and remove the second.
     
  3. ShaunChad99

    ShaunChad99

    Joined:
    Apr 23, 2020
    Posts:
    26
    t
    thanks you just needed that little bit of help on my first raycast script