Unity3D – Shoot Projectiles

, , 79 Comments


In this video we’re going to make it so when we click, we’re going to shoot a little sphere. So first we need to make what we’re going to shoot. That’s, Game Object, Create Other, Sphere. We need this sphere to fall, not just go in a straight line or not move. It needs to fall, so that’s just adding a Rigidbody to the sphere. And we’re going to call it, “projectile”. It’s no capital P just, “projectile”. And we need to put this in our, resources folder. So in “Assets”, if you don’t have a folder just right click, Create Folder, “Resources” I think it has to be a capital R, I can’t remember. And when you go into there you just find your projectile on the top left. Click and drag, so left click, let go of left-click and now you’ve got your cookie cutter in here. So this is kind of a cookie, an instance. We don’t actually need this instance anymore, we can delete it because we have our cookie cutter, like the idea of a projectile is ready to go. So now we need a script to do this. So go into Scripts, right click, Create C# Script. Call it “projectile shooter” and open it up. So first we need to hold on to our cookie cutter. So we need a new variable of, type GameObject. I’m going to call it, prefab, because a prefab is what Unity calls a cookie cutter. And when we start prefab is going to equal something in our resources, it will load projectile. It’s an object that’s how you, do that. So now prefabs is ready to go, to be used to make more projectiles. And now every time we update we want to check, we’re going to check if we’re… What is it? MouseButton? GetMouseButtonDown. So if we just left clicked, then we’re going to shoot. So the way we’re going to do this, we’re going to make a new, GameObject, a new variable to hold on to our new projectile. And it’s going to be, type GameObject. Projectile, is going to be We’re going to instantiate that prefab. So now we have a new projectile but we need to put it in the right place and we need to make it moving in the right direction. So, first, projectile Our position is going to be what? Well we’re going to take the position of our player and since we’re attaching projectile shooter to our player This is going to be the position of our player. We’re going to add We’re going to take the direction that we’re looking And that’s going to be this. So in the camera, our main camera, its .transform which holds its position, rotation, all that, forward is going to be an arrow pointing in the direction that we’re looking It’s a unit vector in this case and I’m going to make it like Because we can’t have our projectile just appear inside our head, that’s what this would do. So we’re going to add just a little bit forward So it’s going to appear kind of in front of our face. Now we need to make it move and at the right speed so So velocity is something like that Rigidbody that’s what that what makes it move and everything so I’m going to make a new variable, of type Rigidbody. And it’s going to be called,”RB” We’re going to get this from projectile We’re going to, GetComponent(); And then we’re going to set the velocity to We’re going to set it to We’re going to take, where we’re looking, is that unit vectors, it’s the direction we’re looking But if we did just this, it’s not going to go very fast. So I’m just going to say 40 That’s the speed, I’ll just make that up. And that should be good, we’ll give it a shot. So you got to go back to your player, You got to add the component, Projectile Shooter and give it a shot. There you go now we’re shooting, shooting spheres.

 

79 Responses

  1. Lame_Duck

    September 29, 2014 10:06 am

    public class SpellProjectile : MonoBehaviour {

    //Mechanics

    GameObject prefab;

    void Start(){
    prefab = Resources.Load("FireBolt") as GameObject;

    }

    void Update (){
    if (Input.GetMouseButtonDown (0)) {
    GameObject FireBolt = Instantiate(prefab) as GameObject;
    FireBolt.transform.position – transform.position + Camera.main.transform.forward *2;
    Rigidbody rb = FireBolt.GetComponent<Rigidbody>();
    rb.velocity =Camera.main.transform.forward * 10;
    }

    }

    }

    On line 17 FireBolt.transform.position will not take the minus sign and causes this error: error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement. If I make it an = the code will work but my projectile shoots extremely fast and far

    Reply
  2. tiago costa

    December 16, 2014 5:10 pm

    Hi, your tut is awesome, but what if I want to use the direction of the mouse pointer instead of the camera position?

    Reply
  3. Thibault Potier

    March 31, 2015 5:25 am

    Hey ! Thanks for the tutorial but what about the destructions of the objects you are creating?

    Reply
  4. Dustin

    June 8, 2015 3:57 pm

    Thank you for the tutorial. Any idea how I could slightly modify the position the projectile spawns at? It is shooting from my char's foot, and I'd like to shift it up the Y axis a bit.

    Reply
  5. Sergio Andrés Salazar Bedoya

    June 20, 2015 3:53 am

    Thanks for the tutorial. How I do to destroy the bullet if it collides with other object?

    Reply
  6. Anderson Queiroz

    July 4, 2015 6:05 pm

    Hey guys, i dont know if i missed anything but if i did please help.
    Here is my script:

    using UnityEngine;
    using System.Collections;

    public class ProjectileShooter : MonoBehaviour {

    GameObject prefab;
    void Start () {
       prefab=Resources.Load("Projectile") as GameObject

    void Update () {
    if (Input.GetMouseButtonDown(0)){
    {
    GameObject projectile = Instantiate(prefab) as GameObject;
    projectile.transform.position = transform.position+Camera.main.transform.forward
    Rigidbody rb = projectile.GetComponent<Rigidbody>();
    rb.velocity = Camera.main.transform.forward * 40;
    }
    }

    Reply
  7. The Raj Show

    October 1, 2015 4:47 am

    Hi I'm not sure if you're still replying but I have a error

    NullReferenceException: Object reference not set to an instance of an object
    ProjectileShooter.Update () (at Assets/ProjectileShooter.cs:18)

    which is based around:

    projectile.transform.position = transform.position + Camera.main.transform.forward * 2;

    The projectiles still fires but they don't fly out, they fall to the ground once fired in a stationary place

    otherwise great video please do more!

    Reply
  8. Jonathan Clark

    March 8, 2016 6:29 pm

    Thanks! This was a lot more straightforward then the unity FPS tutorials. I needed to see something that was more simplified.

    Reply
  9. lightningsketcher

    June 7, 2016 12:06 am

    well, I'm doing a 3rd person game so this didn't really work for me. I tried attaching the script to just about everything but the projectile ( at best) instantiated miles away. I have several camera modes and even if FPS mode had issues. Still trying. I'm sure it's something on my end. In 3rd person the projectiles came from the players feet and put him in a freefall below the terrain – even with gravity off and Y translate locked

    Reply
  10. killermelga

    August 23, 2016 2:48 am

    you shouldnt set the elocity of a rigidbody, you should use AddForce instead. setting the velocity may result in unexpected behaviour

    Reply
  11. Jon Bucklin

    September 7, 2016 11:43 am

    Very helpful videos! thank you much for breaking it down and explaining the whys. definitely has helped me understand the beautiful language of C# and working with it in Unity 🙂

    Reply
  12. ThunderSoul97

    September 22, 2016 6:31 am

    Interesting, but how would I shoot a projectile without a target? e.g. given only angle and speed (and maybe air resistance)?

    Reply
  13. Alistair Monaghan

    November 2, 2016 11:26 pm

    Nice, quick, clean tutorial – thanks

    Is there a way to angle the shot so that it's the same as my gun barrell?

    Reply
  14. tangbein

    November 19, 2016 10:17 pm

    thanks for tutorial! Is it possible to implement the projectileshooter script into the built in first person controller in unity? I am assuming the way to do it is to switch out camera main with first person controller, but I haven't found any way to do it. reason I'm asking is because I can't get the scripts you have created for character movement to work.

    Reply
  15. Callum Wood-Brignall

    January 10, 2017 7:26 pm

    Will this work if I add it to Unity's Prefab of FPS or do I need to make my own? Either way Thanks for the help simple combat tool, well shooting tool that I can use in my college project

    Reply
  16. DanSparrow

    January 31, 2017 10:38 pm

    I must have tried 10 different ways to do this with the system I was using, and yours worked alike a charm! tyvm!

    Reply
  17. Fissle Wine

    March 16, 2017 1:06 am

    but how do optimise unity so the speed doesn't change on different systems? As if your system runs as 30 frames per second your game will be slower… As it is usual normal to divide clock speed by a number or etc..

    Reply
  18. Sushan Sudev

    April 24, 2017 1:03 pm

    Hey I kinda used a similar code for a ball projection. The velocity works fine when I use an object like a sphere. But when I use a body with ragdoll, it spawns but not projected. It just falls down rather than being projected like the spheres. Could someone pls help me?

    Reply
  19. Kevin

    May 21, 2017 12:08 am

    Nice Tut thanks. For anyone who is getting the null reference exception, it might be because you need to add a rigidbody component to your projectile. I personally just made the gameobject public and drug my prefab in. If you have something other than a perfect sphere, you probably want it to rotate correctly also, in which case add "projectile.transform.rotation = transform.rotation" after the transform position line.

    Reply
  20. Citrus

    June 29, 2017 2:48 am

    Assets/Scripts/ProjectileShooter.cs(7,5): error CS1519: Unexpected symbol `void' in class, struct, or interface member declaration

    Reply
  21. Oskar Simpson

    July 3, 2017 3:23 am

    How do i make the projectiles shoot out of a box for example? Im thinking of making a gun that shoots?

    Reply
  22. sniper x

    August 26, 2017 1:47 am

    WHAT IS WRONG WITH MY SCRIPT

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

    public class attack1 : MonoBehaviour {
    GameObject prefab;
    void Start () {
    prefab = Resources.Load(“ attack1 ”) as GameObject;
    }

    Void Update () {
    If (input.GetMouseButtonDown (0));

    GameObject attack1 = Instantiate(prefab) as GameObject;
    attack1 . transform.position=transform.position+Camera.main.transform.forward * 2;
    Rigidbody rb = attack1.GetComponent<Rigidbody>();
    rb.velocity = Camera.main.transform.forward * 13;

    }

    }

    Reply
  23. •Pixel• Arcane

    October 12, 2017 4:42 am

    No matter what i try i always get error CS0149: Method name expected. Whats wrong with my script

    public class Shoot : MonoBehaviour {

    GameObject prefab;

    void Start()
    {
    prefab = Resources.Load("Red Laser") as GameObject;
    }

    void Update()
    {

    if (Input.GetKeyDown("Space")(0))
    {
    GameObject Red_Laser = Instantiate(prefab) as GameObject;
    Red_Laser.transform.position = transform.position;
    Rigidbody rb = Red_Laser.GetComponent<Rigidbody>();
    rb.velocity = Camera.main.transform.forward * 40;
    }
    }
    }

    Reply
  24. Yolo GamerJack

    December 10, 2017 8:16 pm

    PLEASE, I'M STUCK

    Hey, my name is Jack, I'm currently 14, and I love programming,
    although I'm pretty new to it.

    I followed along the video, and i understood everything,
    but when i test the game, and try to shoot, the bullet doesn't move.
    In the console it says:

    "MissingComponentException: There is no 'Rigidbody' attached to the "Bullet(Clone)" game object, but a script is trying to access it.
    You probably need to add a Rigidbody to the game object "Bullet(Clone)". Or your script needs to check if the component is attached before using it.
    UnityEngine.Rigidbody.set_velocity (Vector3 value) (at C:/buildslave/unity/build/artifacts/generated/common/modules/Physics/DynamicsBindings.gen.cs:1260)
    ShootBullet.Update () (at Assets/Scripts/ShootBullet.cs:19)"

    I have rigidbody on the Bullet object, but i think, when it Instantiates the object,
    and makes the clone, the clone won't have the rigidbody component.
    Atleast that's what i think what happens.

    I've tried alot of different codes, and been searching online for hours,
    but I can't seem to get it fixed.

    Can someone help me? This is my code.

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

    public class ShootBullet : MonoBehaviour {

    GameObject prefab;
    void Start () {
    prefab = Resources.Load("Bullet") as GameObject;
    }

    void Update () {
    if (Input.GetMouseButtonDown(0))
    {
    GameObject Bullet = Instantiate(prefab) as GameObject;
    Bullet.transform.position = transform.position + Camera.main.transform.forward;
    Rigidbody rb = Bullet.GetComponent<Rigidbody>();
    rb.velocity = Camera.main.transform.forward * 40;
    }
    }
    }

    If you could help, even a little, I would apreciate that 🙂
    I know i'm a few years late, but I would love to be helped!

    Reply
  25. Quintin Castro

    March 18, 2018 11:21 am

    How can i make it do this if i am making an up down shooter that's in third person so that where i press the ball it goes in that direction

    Reply
  26. Scribble Sketches

    March 26, 2018 2:41 am

    Thank you it worked perfectly and for those that want this to go with a crosshair and have the projectile shoot straight under rigid body in the inspector add the constraints Freeze position- Y and Freeze rotation -X and Z

    Reply
  27. animeboy93

    May 19, 2018 11:00 am

    When I do this the prefab object ends up being attached and follows my players movement. How do we fix this?

    Reply
  28. opafritzsche

    July 19, 2018 12:51 am

    hm. Player:

    Void Update{)
    {
    If (Input.GetKeyDown("a")
    {
    Cannonscript.Attack();
    }
    }

    Cannonscript:

    Public GameObject Prijectile;

    Void Attack()
    {
    GameObject BulletObject = Instantiate(Prjectile);
    BulletObject.transform.position = transform.position + transform.forward;
    BulletObject.transform.forward = transform.forward;
    }

    and in Class Prjectile:

    Void Start()
    {
    GetComponent<Rigidbody>().velocity = transform.forward * 10f;
    }

    That s all.

    Reply
  29. Just ᴀʟᴇx

    February 26, 2019 4:51 am

    AssetsProjectileShooter.cs(17,38): error CS0103: The name 'prefab' does not exist in the current context
    and
    Cannot add script behavior AssemblyInfo. The script needs to derive from monobehavior

    Reply
  30. Seyyed Hamed Mahmoudzadeh

    May 26, 2019 12:35 am

    Hi to all my first course published on Udemy.com

    2D Archery Game In Unity3d
    https://www.udemy.com/2d-archery-game-in-unity-3d/?couponCode=MYFIRSTLESSON

    For the first 200 people we consider 36% discount.
    Dicsount Code: MYFIRSTLESSON

    In the next month other chapters wil be published

    Reply

Leave a Reply