help i cannot find anything on this.

hi im really confused because i was using a Dave game developer video about costume projectiles and it said in my error thing that. camera does not have a definition for ViewportPointToRay. I’ve looked it up but found nothing. this is the only error in my script, and it will not go away please help. I really want guns for my game, and this is stopping me :frowning:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! See above.

It’s hard to intuit what is wrong with your code when we cannot see it…

That said, perhaps, you’re doing this?

Camera.ViewportPointToRay

ViewportPointToRay is an instance method, and can only be called on a specific instance of a camera, rather than the Camera class itself. So, you’d probably want to do this, instead:

Camera.main.ViewportPointToRay

…since Camera.main is the main camera (and thus a specific camera, that you can ask to convert a viewport point into a ray!)

However, the error you quoted – “X does not contain a definition for Y” – would not appear in this situation. You’d see an error like “An object reference is required for the non-static field, method, or property […]”.

So, show your code, please.

ok look up Dave / game development on YouTube and go into the tutorials playlist and it is the first video that says about costume projectiles. there’s two parts but parts one is about just shooting. I even downloaded the code, and I still did not get the error so go away. and Kurt… NOT HELPING, I MIGHT BE NEW AT THIS BUT IM NOT STUPID. I LOOKED THROUGH THE VIDEO 5 TIMES. AND I KNOW THIS STUFF I DO MY RESEARCH. I HAVE NO IDEA WHY MY EDITOR IS SAYING ITS WRONG. IT DID THIS WITH A “FieldOfView” STATMENT AND IT WAS WRONG THERE TOO. AND I LOOK AT ALL THE UNITY DOCUMENTATION AND OTHER STUFF BUT NOTHING WORKS. I’m really mad and I do not need this right now. and i do not know how to show code on forms. I’m new to these forms too.

Calm down, take an hour break. Come back to it The chemical has answered your question. Just take a load off the stress and come back 1 hour. What’s 1 hour. It’s time to de-stress.
He has answered the question. You are just so frustrated right now you can’t see that. (YouTube Tutorials do that, they frustrate, because the guy is milking your time consuming your life)

To do a viewpoint ray from the camera the camera needs to be referenced either as Camera.main, or - by dragging a game object with a camera into your inspector with your script.

Do us a favour when you get back from your break, and screenshot your inspector with the script. To use code tags there is a small written Code: with an image.


it’s on the right hand side near the floppy disc icon.

1 Like

ok so i do have a public camera. i can put it in the inspector. or if it worked i could and heres my code

using UnityEngine;
using TMPro;

/// Thanks for downloading my projectile gun script! :smile:
/// Feel free to use it in any project you like!
///
/// The code is fully commented but if you still have any questions
/// don't hesitate to write a yt comment
/// or use the #coding-problems channel of my discord server
///
/// Dave
public class ProjectileGunTutorial : MonoBehaviour
{
    //bullet
    public GameObject bullet;

    //bullet force
    public float shootForce, upwardForce;

    //Gun stats
    public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
    public int magazineSize, bulletsPerTap;
    public bool allowButtonHold;

    int bulletsLeft, bulletsShot;

    //Recoil
    public Rigidbody playerRb;
    public float recoilForce;

    //bools
    bool shooting, readyToShoot, reloading;

    //Reference
    public Camera fpsCam;
    public Transform attackPoint;

    //Graphics
    public GameObject muzzleFlash;
    public TextMeshProUGUI ammunitionDisplay;

    //bug fixing :smile:
    public bool allowInvoke = true;

    private void Awake()
    {
        //make sure magazine is full
        bulletsLeft = magazineSize;
        readyToShoot = true;
    }

    private void Update()
    {
        MyInput();

        //Set ammo display, if it exists :smile:
        if (ammunitionDisplay != null)
            ammunitionDisplay.SetText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap);
    }
    private void MyInput()
    {
        //Check if allowed to hold down button and take corresponding input
        if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
        else shooting = Input.GetKeyDown(KeyCode.Mouse0);

        //Reloading
        if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
        //Reload automatically when trying to shoot without ammo
        if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();

        //Shooting
        if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
        {
            //Set bullets shot to 0
            bulletsShot = 0;

            Shoot();
        }
    }

    private void Shoot()
    {
        readyToShoot = false;

        //Find the exact hit position using a raycast
        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //Just a ray through the middle of your current view
        RaycastHit hit;

        //check if ray hits something
        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;
        else
            targetPoint = ray.GetPoint(75); //Just a point far away from the player

        //Calculate direction from attackPoint to targetPoint
        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        //Calculate spread
        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        //Calculate new direction with spread
        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction

        //Instantiate bullet/projectile
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); //store instantiated bullet in currentBullet
        //Rotate bullet to shoot direction
        currentBullet.transform.forward = directionWithSpread.normalized;

        //Add forces to bullet
        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

        //Instantiate muzzle flash, if you have one
        if (muzzleFlash != null)
            Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);

        bulletsLeft--;
        bulletsShot++;

        //Invoke resetShot function (if not already invoked), with your timeBetweenShooting
        if (allowInvoke)
        {
            Invoke("ResetShot", timeBetweenShooting);
            allowInvoke = false;

            //Add recoil to player (should only be called once)
            playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
        }

        //if more than one bulletsPerTap make sure to repeat shoot function
        if (bulletsShot < bulletsPerTap && bulletsLeft > 0)
            Invoke("Shoot", timeBetweenShots);
    }
    private void ResetShot()
    {
        //Allow shooting and invoking again
        readyToShoot = true;
        allowInvoke = true;
    }

    private void Reload()
    {
        reloading = true;
        Invoke("ReloadFinished", reloadTime); //Invoke ReloadFinished function with your reloadTime as delay
    }
    private void ReloadFinished()
    {
        //Fill magazine
        bulletsLeft = magazineSize;
        reloading = false;
    }
}

i did download this. but only after i could not find my mistake.

i am claim now. i played some Minecraft and feel better. also that one guy just sounded really rude. also i did what he said. and still nothing. but pls tell me whats wrong with my code

You seem perhaps confused about how this works.

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

8932380--1224594--thescript.png

I got your script to work myself

public class PROJECTILEGUNTUTORIAL : MonoBehaviour

when you created your script in unity project folder if you named the script anything other than the intended name then the inspector wont display it.

When i made the script i named it PROJECTILEGUNTUTORIAL in all caps. But the original is ProjectileGunTutorial, if you created the script and removed from the cs file name ProjectileGunTutorial then none of your variables or objects can be set in that inspector.

As you see the inspector you’ll end up with when you fix this, you can drag the camera in. I had to remove TMPRO references in my version because i don’t use text mesh pro, and the assemblie definitions are not in my project.

SO MAKE SURE!!! YOU TITLED YOUR SCRIPT TO WHATEVER IS WRITTEN WHEN THE CLASS IS SPECIFIED :slight_smile:

make sure that public class is referencing the correct name of the script you created. Without the .cs on the end

No problem with the Viewport unless those names didn’t match.

Let us know how you get on fella.

ok thanks but just pls help me. i will remember that for next time

ok umm… i tried your suggestion and it did not work? I’m confused a lot now. I’ve redownloaded it then changed the name but. it still says no scripts are there, I’m goanna try the tutorial again. maybe i can fix it? I hate that I’m doing the tutorial for the 6th time now.

using UnityEngine;
//using TMPro;

/// Thanks for downloading my projectile gun script! :smile:
/// Feel free to use it in any project you like!
///
/// The code is fully commented but if you still have any questions
/// don't hesitate to write a yt comment
/// or use the #coding-problems channel of my discord server
///
/// Dave
public class ProjectileGunTutorial : MonoBehaviour
{
    //bullet
    public GameObject bullet;

    //bullet force
    public float shootForce, upwardForce;

    //Gun stats
    public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
    public int magazineSize, bulletsPerTap;
    public bool allowButtonHold;

    int bulletsLeft, bulletsShot;

    //Recoil
    public Rigidbody playerRb;
    public float recoilForce;

    //bools
    bool shooting, readyToShoot, reloading;

    //Reference
    public Camera fpsCam;
    public Transform attackPoint;

    //Graphics
    public GameObject muzzleFlash;
    //public TextMeshProUGUI ammunitionDisplay;

    //bug fixing :smile:
    public bool allowInvoke = true;

    private void Awake()
    {
        //make sure magazine is full
        bulletsLeft = magazineSize;
        readyToShoot = true;
    }

    private void Update()
    {
        MyInput();

        //Set ammo display, if it exists :smile:
        //if (ammunitionDisplay != null)
        //    ammunitionDisplay.SetText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap);
    }
    private void MyInput()
    {
        //Check if allowed to hold down button and take corresponding input
        if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
        else shooting = Input.GetKeyDown(KeyCode.Mouse0);

        //Reloading
        if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
        //Reload automatically when trying to shoot without ammo
        if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();

        //Shooting
        if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
        {
            //Set bullets shot to 0
            bulletsShot = 0;

            Shoot();
        }
    }

    private void Shoot()
    {
        readyToShoot = false;

        //Find the exact hit position using a raycast
        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //Just a ray through the middle of your current view
        RaycastHit hit;

        //check if ray hits something
        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;
        else
            targetPoint = ray.GetPoint(75); //Just a point far away from the player

        //Calculate direction from attackPoint to targetPoint
        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        //Calculate spread
        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        //Calculate new direction with spread
        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction

        //Instantiate bullet/projectile
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); //store instantiated bullet in currentBullet
        //Rotate bullet to shoot direction
        currentBullet.transform.forward = directionWithSpread.normalized;

        //Add forces to bullet
        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

        //Instantiate muzzle flash, if you have one
        if (muzzleFlash != null)
            Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);

        bulletsLeft--;
        bulletsShot++;

        //Invoke resetShot function (if not already invoked), with your timeBetweenShooting
        if (allowInvoke)
        {
            Invoke("ResetShot", timeBetweenShooting);
            allowInvoke = false;

            //Add recoil to player (should only be called once)
            playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
        }

        //if more than one bulletsPerTap make sure to repeat shoot function
        if (bulletsShot < bulletsPerTap && bulletsLeft > 0)
            Invoke("Shoot", timeBetweenShots);
    }
    private void ResetShot()
    {
        //Allow shooting and invoking again
        readyToShoot = true;
        allowInvoke = true;
    }

    private void Reload()
    {
        reloading = true;
        Invoke("ReloadFinished", reloadTime); //Invoke ReloadFinished function with your reloadTime as delay
    }
    private void ReloadFinished()
    {
        //Fill magazine
        bulletsLeft = magazineSize;
        reloading = false;
    }
}

Thats all i did. make sure the name of the file in the folder matches the Class name whichever way around will work. My version, i did not delete lines! but i // commented out TM pro, which is only one line in update to display ammo count using a text asset.

if your script in inspector looks like this! then the names of class and file do not match.
8932410--1224600--namesdontmatch.png

umm it had the speech bubble and I tried without that stuff at the top but nothing. I’m doing the tutorial over so it might work. if not, I give up. btw I’m on 2021.3 if that makes a difference.

.<

ProjectileGunTutorial

just rename the script in the project folder to ProjectileGunTutorial, it will work as is. 2021.3 is what I’m on as well.

umm I tried that like you said. but… it did not work. :frowning: I’m trying everything. and it’s still coming up btw. I got to the part where the codes put in. and BOOM, error. also, I had problems with cam stuff before.

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

public class projectilegunscript : MonoBehaviour
{
   public GameObject bullet;

   public float shootForce, upwardForce;

   public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
   public int magazineSize, bulletsPerTap;
   public bool allowButtonHold;
   int bulletsLeft, bulletsShot;

   bool shooting, readyToShoot, reloading;

   public Camera fpsCam;
   public Transform attackPoint;

   public bool allowInvoke = true;

   private void Awake()
   {
        bulletsLeft = magazineSize;
        readyToShoot = true;
   }

   private void Update()
   {
        MyInput();
   }

   private void MyInput()
   {
        if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
        else shooting = Input.GetKeyDown(KeyCode.Mouse0);

        if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
        {
            bulletsShot = 0;

            Shoot();
        }
   }

   private void Shoot()
   {
        readyToShoot = false;

        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;

        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;
        else
            targetPoint = ray.GetPoint(75);
       
        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0);

        bulletsLeft--;
        bulletsShot++;
   }
}

this is where i am so far. and i got the error

You need to be more specific. Provide the exact error you are getting. Give the line number and the file name. Is it the same as before, or has something changed?

“It did not work” is not helpful. We can’t do anything with that.

“It did not work” is not helpful. We can’t do anything with that.[/QUOTE]

Assets\projectilegunscript.cs(52,26): error CS1061: ‘Camera’ does not contain a definition for ‘ViewportPointToRay’ and no accessible extension method ‘ViewportPointToRay’ accepting a first argument of type ‘Camera’ could be found (are you missing a using directive or an assembly reference?)

there you go

Did you make your own script called Camera ? If so , don’t do that.

1 Like