- Home /
Objects instantiate at prefab location instead of playtime location
When I instantiate my bullets from my gun at my gun barrel in the Shoot() function it instantiates at the (0,0,0) location it is on my prefab object. But when I instantiate it in the Update function it instantiates the bullets at the runtime barrel actual location. If I print the barrel position in the Shoot function it says (0,0,0) but in the update function, it does the live position.
using UnityEngine; public class Weapon : MonoBehaviour { public int damage; public int range; public int speed; public Transform barrel; //shotgun public float spread; public int bulletCount;
public Camera fpsCam;
public GameObject bullet;
private void Start()
{
barrel = gameObject.GetComponentInChildren<Transform>();
}
public void Shoot()
{
Transform bt = barrel.transform;
for (int i = 0; i < bulletCount; i++)
{
print("L" + barrel.transform.position);
var randomNumberX = Random.Range(-spread, spread);
var randomNumberY = Random.Range(-spread, spread);
GameObject b = Instantiate(bullet, transform.position, transform.rotation);
b.transform.Rotate(randomNumberX, randomNumberY, 0);
Rigidbody rb = b.GetComponent<Rigidbody>();
rb.AddForce(transform.forward * speed * Time.deltaTime);
}
}
private void Update()
{
}
}
This`GameObject b = Instantiate(bullet, transform.position, transform.rotation);` should be this GameObject b = Instantiate(bullet, bt.position, bt.rotation);
it is still is instantiating them at (0,0,0) :(
Just a quick guess on my part, but try using localPosition and see if that makes a difference...
GameObject b = Instantiate(bullet, bt.localPosition, bt.rotation);
Answer by Lazdude17 · Dec 08, 2019 at 07:00 PM
I would just get rid of the Start function. You name the Transform in Shoot().
public void Shoot()
{
//no need for transform. you only use the position
Vector 3 bt = barrel.transform.position;
for (int i = 0; i < bulletCount; i++)
{
print("L" + barrel.transform.position);
var randomNumberX = Random.Range(-spread, spread);
var randomNumberY = Random.Range(-spread, spread);
//You made a bt variable for barrel transform and never used it
GameObject b = Instantiate(bullet, bt.position, Quaternion.Identity);
b.transform.Rotate(randomNumberX, randomNumberY, 0);
Rigidbody rb = b.GetComponent<Rigidbody>();
rb.AddForce(transform.forward * speed * Time.deltaTime);
}
}
May be the problem, but Idk how your prefab is set up.
And you need to run Shoot() in your Update() so that everytime Shoot() is called it will update bt.
Your answer
Follow this Question
Related Questions
How do I make it so that my bullet projectile for my gun does damage? 1 Answer
Bullets going wrong direction 1 Answer
Bullets aren't firing / Bullet holes not instantiating correctly 0 Answers
Add 0.5f to Vector.Right on next instantiated object ? 1 Answer
Combine objects instantiated at runtime 2 Answers