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

Help with Spawning a Prefab

Discussion in 'Scripting' started by AndrewMac26, Dec 9, 2015.

  1. AndrewMac26

    AndrewMac26

    Joined:
    Nov 24, 2015
    Posts:
    14
    So Im trying to spawn a bullet casing prefab next to my players gun here's the relevant code

    Code (CSharp):
    1. GameObject bulletSpawn = (GameObject)Instantiate(bulletPrefab, bulletSpawn.transform.position, Quaternion.identity);
    The only problem is that it spawns the bullet casing underneath my character(FPC)

    bulletSpawn is a empty object in the intended position for the casing to be spawned
    bulletPrefab is a prefab of the casing itself

    anyone got any idea whats going on?
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    check the position of the prefab's transform (from the project), it needs to 0,0,0 otherwise it'll be instantiated at an offset
     
  3. TimGS

    TimGS

    Joined:
    Apr 24, 2014
    Posts:
    70
    Wait. When you define the type (GameObject) of a variable it makes it local.
    How do you use that variable bulletSpawn in instantiation function without getting an error about using unasigned local variable?

    Rename your spawned object variable to something like this:
    Code (csharp):
    1. GameObject spawnedBullet =(GameObject)Instantiate(bulletPrefab, bulletSpawn.transform.position, Quaternion.identity);
     
  4. AndrewMac26

    AndrewMac26

    Joined:
    Nov 24, 2015
    Posts:
    14
    Yea sorry my bad I was trying to change the code to get it to work and I forgot to put it back it should read:
    Code (CSharp):
    1. GameObject bulletSpawn = (GameObject)Instantiate(bulletPrefab,transform.position, Quaternion.identity);
     
  5. AndrewMac26

    AndrewMac26

    Joined:
    Nov 24, 2015
    Posts:
    14
    No joy Im afraid still spawns under the FPC
     
  6. AndrewMac26

    AndrewMac26

    Joined:
    Nov 24, 2015
    Posts:
    14
    Thanks to everyone for the help, just figured it out there. for any one interested here's the correct code:

    Code (CSharp):
    1. Instantiate (bulletPrefab, GameObject.Find("bulletSpawn").transform.position, Quaternion.identity);