What is the correct way to instantiate a projectile with initial velocity?

Hi, I’m having a lot of trouble tracking down this problem. I am instantiating a bullet a certain distance away from my character intending to move along a path following the mouse. I know that the mouse tracking works because I was testing before with a line renderer. I was using bullet.velocity but I found a thread that said that that doesn’t work with Unity 5 so I tried the suggested bullet.GetComponent().velocity and that isn’t working either. Any suggestions would be very appreciated thank you!

    private void Attack()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            aimAtMouse();
            RaycastHit2D hit;
            
            // Offsets origin point for bullets outside the player's collider
            Vector2 rayOrigin = new Vector2(transform.position.x + aimDirection.x * offset,
                                            transform.position.y + aimDirection.y * offset);

            //Debug.DrawRay(origin, aimDirection * 100f, Color.green, 0.5f);
            hit = Physics2D.Raycast(rayOrigin, aimDirection, 100f);

            Vector3 bulletPos = new Vector3(rayOrigin.x, rayOrigin.y);
            Instantiate(bullet, bulletPos, Quaternion.identity);
            bullet.GetComponent<Rigidbody2D>().velocity = new Vector2(aimDirection.x, aimDirection.y) * 10.0f;


            //Debug.Log(aimDirection);
            //Debug.Log(bulletPos);
            Debug.Log(bullet.GetComponent<Rigidbody2D>().velocity);
        }
    }

I think you have to change this:

             Instantiate(bullet, bulletPos, Quaternion.identity);
             bullet.GetComponent<Rigidbody2D>().velocity = new Vector2(aimDirection.x, aimDirection.y) * 10.0f;

to:

GameObject newBullet = Instantiate(bullet, bulletPos, Quaternion.identity);
                 newBullet.GetComponent<Rigidbody2D>().velocity = new Vector2(aimDirection.x, aimDirection.y) * 10.0f;

Because in your script you are getting the prefabs rigidbody and set its velocity.
Everything else seems fine.
You should rename the varaible “bullet” to “bulletPrefab” to avoid this in other methods / future projects.