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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Need help with my gun shooting script!

Discussion in 'Scripting' started by Cheeseboat, Sep 29, 2020.

  1. Cheeseboat

    Cheeseboat

    Joined:
    Oct 2, 2019
    Posts:
    8
    Hello everyone, I hope you are having a good day! I am new to C# and Unity in of it's self, and I am slowly learning C#, but I found a video on youtube from Brackeys on how to shoot with Raycasts. I think I followed the script, but I get the error "The type or namespace name 'Target' could not be found (are you missing a using directive or an assembly reference?)". Here is the code and help would be most appreciated!:
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class Gun : MonoBehaviour
    5. {
    6.  
    7.     public float damage = 10f;
    8.     public float range = 100f;
    9.  
    10.     public Camera fpsCam;
    11.  
    12.     // Update is called once per frame
    13.     void Update()
    14.     {
    15.         if (Input.GetButtonDown("Fire1"))
    16.         {
    17.             Shoot();
    18.  
    19.         }
    20.  
    21.     }
    22.  
    23.     void Shoot ()
    24.     {
    25.         RaycastHit hit;
    26.         if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range));
    27.         {
    28.             Debug.Log(hit.transform.name);
    29.  
    30.           Target target = hit.transform.GetComponent<Target>();
    31.             if (target != null)
    32.             {
    33.                 target.TakeDamage(damage);
    34.             }
    35.         }
    36.     }
    37. }
    38.  
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    The error tells you that the compiler does not know what "Target" is. Do you have a Target script?

    Also, not necessary here, but in the future i'd advice to post the full error message including the line^^
     
  3. Cheeseboat

    Cheeseboat

    Joined:
    Oct 2, 2019
    Posts:
    8
    Awesome, thanks! I think it might be because I named my enemy "enemy" and not target, let me see if that is the problem....
     
  4. Cheeseboat

    Cheeseboat

    Joined:
    Oct 2, 2019
    Posts:
    8
    okay, I fixed, thank you for your help, and have a wonderful day!