Firing bullet in 2D unsuccessful

I went on Googling on how to fire a bullet in 3D space, since firing one in 2D would be same, just with different coordinates. The script I found (original):

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

public class BulletItself : MonoBehaviour {  
    //the object that will be spawned
  
    public GameObject bulletPrefab;
  
  
  
    // Use this for initialization
    void Start () {
      
      
      
    }
  
    // Update is called once per frame
    void Update () {
      
        if (Input.GetButtonDown("Fire1")){//when the left mouse button is clicked
          
            print ("1");//print a message to act as a debug
          
            FireBullet();//look for and use the fire bullet operation
          
        }
    }
  
  
  
  
    public void FireBullet(){
      
      
      
        //Clone of the bullet
        GameObject Clone;
      
        //spawning the bullet at position
        Clone = (Instantiate(bulletPrefab, transform.position,transform.rotation)) as GameObject;
        Debug.Log ("Bullet is found");
      
      
        //add force to the spawned objected
        Clone.rigidbody.AddForce(1000,0,0);
      
        Debug.Log ("Force is added");
      
    }
  
  
  
  
  
  
  
}

So I instantly tried to modify it and clean it up (remove comments and remove the unnecessary [Enter]‘s).
But then what I see in MonoDevelop is:
Clone.rigidbody.AddForce(1000,0,0);
“AddForce” creates an error, MonoDevelop says
"UnityEngine.Component does not contain definition of AddForce.
Tried to fix it, by:
Clone.GetComponent.AddForce(1000,0,0);
But the error I get from it is: “?”, nothing else, just a funny question mark. So I went back to Unity, and it says:
"Assets/Scripts/Player/BulletItself.cs(24,23): error CS0119: Expression denotes a method group', where a variable’, value' or type’ was expected". (24,23), points exactly to this line.

And I’m so lost. Is there no easy way to do this? I’m not one of those that just copy, I copy, modify and learn, but heck, so many nice outdated too-specific JavaScript tutorials on how to do this, and not a single would be just “paste this script, put “Bullet” into slot, play with it until you learn, expand the code yourself”.

Back to the problem, how can I resolve it?

AddForce takes a Vector3, not three integers.

var rigidBody = clone.GetComponent<Rigidbody>();
var force = new Vector3(100f,0f,0f);

rigidBody.AddForce(force);

Familiarize yourself with this: Unity - Scripting API:
Very handy.

GetComponent()

you’re missing the ()

ben, there is an overload with x, y, z, (forcetype) as the parameters…

1 Like

BAHAH! I did not know this.
I guess I should ALSO familiarize myself with the ScriptReference :stuck_out_tongue:

using UnityEngine;
using System.Collections;

public class BulletItself : MonoBehaviour
{
    public GameObject bulletPrefab;

    void Update()
    {

        if (Input.GetButtonDown("Fire1"))
        {
            FireBullet();
        }
    }

    public void FireBullet()
    {
        GameObject newBullet = (GameObject)Instantiate(bulletPrefab, transform.position, transform.rotation);
        newBullet.GetComponent<Rigidbody>().AddForce(Vector3.forward * 1000); // assuming you want forward..
    }
}

You can no longer use a rigidbody directly by doing “someGameObject**.rigidbody.**AddForce(…)”, you must access components by using “someGameObject.GetComponent()” where would be the component name you want to access, for instance a BoxCollider or something. The code you found is probably just a bit old.

You may want to use a spawn point as well instead of “Instantiate(bulletPrefab, transform.position, transform.rotation)” so you might predefine a gameobject and reference it before the transform input there for position/rotation.

Also, you’ll probably want to do AddForce in a FixedUpdate method rather than just firing it one time at 1000 force…

If you are using Visual Studio, turn on Code Completion and it will help a lot. Also check the scripting reference frequently as they typically have examples for things you want to do anyway.

If you aren’t using Visual Studio, then start using Visual Studio. :slight_smile:

I did nothing but just copied someone’s script at tried to make it work, don’t be like that :frowning:

There’s actually no way of remembering them all and finding solution in there is quite hard, since you don’t know what these errors mean, so you don’t know where to find solution. Only I can do is Google first two pages of that error and attempt to find solution, in case it’s not successful, I’m seeking help here :expressionless:

MissingComponentException: There is no ‘Rigidbody’ attached to the “debullet(Clone)(Clone)(Clone)(Clone)(Clone)(Clone)(Clone)” game object, but a script is trying to access it.
You probably need to add a Rigidbody to the game object “debullet(Clone)(Clone)(Clone)(Clone)(Clone)(Clone)(Clone)”. Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody.AddForce (Vector3 force) (at C:/buildslave/unity/build/artifacts/generated/common/modules/NewDynamics.gen.cs:706)
BulletItself.FireBullet () (at Assets/Scripts/Player/BulletItself.cs:15)
BulletItself.Update () (at Assets/Scripts/Player/BulletItself.cs:9)
Before you start shouting, yes, I attached default rigidbody to GameObject, yes, I attached default rigidbody to prefab (mainly by dragging GameObject into it’s prefab), these messages grow exponentially (2^amount clicks).

Message says
"Or your script needs to check if the component is attached before using it."
And I feel it has more to ask then Debug.Log(rigidbody == TRUE);

Managed it get it to work, no errors, I can move, but, two strange things happen.

First of all, performance drops ridiculously low, within 8 shots, FPS drops to, hmm, 5?
Second of all, two bullets spawn in different directions, instead of going forward, they move little bit out of the ship, they form letter V instead of just one bullet forming a I.

Probably performances issue, due to unlimited “Fires”. I’ll try to limit it.
Unsuccessful:

using UnityEngine;
using System.Collections;

public class BulletItself : MonoBehaviour {
    public GameObject bulletPrefab;
    public bool allowedToShot = true;

    void Start() {
    }
    void Update() {
        if (Input.GetButtonDown("Fire1")) {
            FireBullet();
        }
        if (allowedToShot == false) {
            new WaitForSeconds(3f);
            allowedToShot = true;
        }
    }

    public void FireBullet() {
        GameObject newBullet = (GameObject)Instantiate(bulletPrefab, transform.position, transform.rotation);
        newBullet.GetComponent<Rigidbody2D>().AddForce(Vector2.right * 1000);
        //newBullet = (Instantiate(bulletPrefab, transform.position+1.0*transform.forward,transform.rotation));
        allowedToShot = false;
    }
}

Tried to put it asleep, in case it just shoot the bullet. Bullets don’t move, become big (same scale, visually bigger) and as soon as you release the left mouse button and you click again, every single bullet that you spawned, spawns it’s bullet, so instead of just spawning two, you just spawn 2^(amount of bullets already spawned). Record is 20.000 bullets in 1 second.

With everything I learned and found on the internet, I tried to craft more minimalistic one.

using UnityEngine;
using System.Collections;

public class BulletItself : MonoBehaviour {
    public GameObject bulletPrefab;
    public bool allowedToShot = true;
    public double time;

    void Update() {
        if (Input.GetButtonUp("Fire1")) {
            FireBullet();
        }
    }

    void FireBullet() {
        GameObject firedBullet = (GameObject)Instantiate(bulletPrefab, transform.position, transform.rotation);
        Rigidbody2D Rigid = firedBullet.GetComponent<Rigidbody2D>();
        Rigid.AddForce(new Vector2(5, 0));
    }
}

Still same thing happens, if I keep left mouse button pressed it keeps spawning them and they don’t move (both prefab and GameObject have their Rigidbody2D’s attached. And clones also have rigidbody’s. If you keep left mouse button pressed, they keep just spawning, if you release the mouse button, just twice as much spawn, and if you press left mouse button again, every single copy spawn their own bullets.

I found a working way!

using UnityEngine;
using System.Collections;

public class FireBullet : MonoBehaviour {
    public GameObject Bullet;
    public GameObject BulletPrefab;

    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButton (0)) {
            Vector2 originalPosition = new Vector2(Bullet.transform.position.x, Bullet.transform.position.y);
           
            Vector2 vec = new Vector2(0, 50);
            Quaternion rot = Quaternion.Euler(0, 0, 0);
            Vector2 rotVec = rot * vec;
            // Random Angle and Random Distance, the Vector3 out of it.
           
            Vector2 newPos = (Vector2)this.transform.position + rotVec;
            Debug.Log (newPos);
        }
    }
}

But then I need it to tell Unity, to not copy the bullets anymore, except if it’s from original bullet. The only issue now is, that it replicates every bullet fired, instead of just the original one, if you help me on this one. I’d be out in no time.