- Home /
Bullet Prefab spawning in multiple random positions and rarely the correct one (Unity 3D)
If I don't make the Bullet Spawn position a child of my gun it spawns bullets in the correct position but when i make it a child of my gun it spawns in random positions.
Here's the bullet script:
public class GunScript : MonoBehaviour
{
public GameObject BulletPrefab;
public Transform BulletSpawn;
int Firing;
// Start is called before the first frame update
void Start()
{
//BulletSpawn = GameObject.FindWithTag("BulletSpawn").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Firing == 0)
{
//GameObject bullet = Instantiate(BulletPrefab, BulletSpawn.position, Quaternion.identity) as GameObject;
//bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 100);
StartCoroutine(Fire());
}
}
IEnumerator Fire()
{
Firing = 1;
GameObject bullet = Instantiate(BulletPrefab, BulletSpawn.position, BulletSpawn.rotation);
//bullet.transform.position = BulletSpawn.position;
yield return new WaitForSeconds(0.15f);
Firing = 0;
}
If you've got the bullet spawn point as the child then try using BulletSpawn.localPosition ins$$anonymous$$d of BulletSpawn.position, similarly with rotation.
I've tried this, it spawns in a random position that is not where it is set
As a test, track the position of BulletSpawn.
In update, when a specific key (a dev key of your choice) is pressed output BulletSpawn.position to the console.
If the player character moves constantly in your game, disable that feature temporarily.
Stand still and press the dev key a couple of times (check that the position stays the same because it should).
$$anonymous$$ove and rotate a bit then stand completely still and press the dev key a couple of times again.
Answer by LOSTSOUL86 · Jan 06, 2020 at 04:49 AM
Dear, I dont see where you assign bullet as a child. Maybe you should send 2 versions of code. One that is working and one that is not working.
I think the problem is how you assign the parent to the child. Do you use method parent or set parent? and when you change child coordinates, after assigning parent or before.
What I would suggest is to change your bullet coordinates first to your gun coordinates. And then just change parent with parent method.
But more I would be able to say after seeing the code.
Your answer
Follow this Question
Related Questions
transforming a prefab randomly at runtime 3 Answers
How to reference a prefab to the script that doesn't exist in Hierarchy 0 Answers
Prefab Puzzle 1 Answer
Saving customized transform in game 1 Answer
Why Transform and not Prefab? 2 Answers