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

Bullet prefab not instantiated in the correct rotation

Discussion in 'Scripting' started by seanseanseanseansean, Jan 10, 2021.

  1. seanseanseanseansean

    seanseanseanseansean

    Joined:
    Jun 27, 2020
    Posts:
    3
    Screenshot (16).png
    Can anybody explain how I can instantiate the bullet prefab at the correct rotation? It's coming out vertically when it's supposed to be a horizontal sprite.

    Here's my script if necessary
    Code (CSharp):
    1. public class Shooting : MonoBehaviour
    2. {
    3.     public Transform firePoint;
    4.     public GameObject bulletPrefab;
    5.  
    6.     [SerializeField] float bulletForce = 20f;
    7.  
    8.     void Update()
    9.     {
    10.         if (Input.GetButtonDown("Fire1"))
    11.         {
    12.             Shoot();
    13.         }
    14.     }
    15.  
    16.     void Shoot()
    17.     {
    18.         GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    19.         Rigidbody2D bulletRB = bullet.GetComponent<Rigidbody2D>();
    20.         bulletRB.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
    21.  
    22.         GetComponent<AudioSource>().Play();
    23.     }
    24. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    Looks like zero rotation on your gun is different from zero rotation on your bullet.

    I usually address this by rotating the graphics inside the prefab, often by inserting an extra GameObject above it, then rotating the sprite beneath it. The hierarchy would look like:

    Code (csharp):
    1. BulletPrefab
    2.     RotationToAlignSpriteProperly
    3.         ActualGraphicalSpriteHere
     
  3. seanseanseanseansean

    seanseanseanseansean

    Joined:
    Jun 27, 2020
    Posts:
    3
    This helped thanks!
     
    Kurt-Dekker likes this.
  4. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    685
    Another option is to change the rotation when you instantiate:

    Code (CSharp):
    1. GameObject bullet = Instantiate(bulletPrefab, firePoint.position,
    2.             Quaternion.Euler(firePoint.rotation.x, firePoint.rotation.y, firePoint.rotation.z + 90));
    3.         // could also be -90, depends on your sprite's original orientation
     
    Poukys likes this.