Instantiated prefab - wrong position

Hi guys,
I’m making a star shooter and I’ve got a problem with instantiating bullets. I’ve got four Game Objects tagged “Shoot” that specify bullets starting postition. Everything seems to be ok, but sometimes one of the bullets appears in the middle of the camera and doesn’t move like on the picture.

Here is the code:

using UnityEngine;
using System.Collections;

public class PlayerShooting : MonoBehaviour {

    public GameObject bulletPrefab;
    public float bulletSpeed = 400f;
    public float delay = 0.1f;

    private GameObject[] shootPoints;
    private float shootTime;

    private GameObject[] bullets;

	// Use this for initialization
	void Start () {
        shootPoints = GameObject.FindGameObjectsWithTag("Shoot");
        shootTime = Time.time;
	}

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Time.time > shootTime + delay)
        {
            if (Input.GetKey(KeyCode.Space))
            {
                foreach (GameObject shoot in shootPoints)
                {
                    GameObject bullet = Instantiate(bulletPrefab, shoot.transform.position, shoot.transform.rotation) as GameObject;
                    Rigidbody2D rg2d = bullet.GetComponent<Rigidbody2D>();
                    rg2d.velocity = new Vector2(0f, bulletSpeed);
                }
                shootTime = Time.time;
            }
        }
    }
}

I hope someone could suggest a solution. :slight_smile:

well… it’s hard to tell without seeing the rest of your code, but this can happen easily with instantiate. Whenever you declare a new GameObject Unity literally makes a new GameObject in the scene, even if you just want to use it for referencing purposes. There’s got to be somewhere that your defining the bulletPrefab? (or are you assigning it in the editor?) or instantiating unwated prefabs as they clearly aren’t getting the position and velocity assignment.

try adding a debug.log to the bullet prefab awake and it might show you what script is generating it like when you get an error and it says what line of what script caused the error it will show you the chain of events that led to the debug.log being called.

Thanks for your advices! I found that the problem was in rigidbody2D component attached to my bullet prefab - I changed Sleeping mode to “Never sleep” instead of “Start Awake” and now all works fine :slight_smile: