- Home /
How do I make a clone of a prefab appear on the correct layer? [5.2.2f1]
So I'm making a 2D Space Shooter game, and I'm having my player shoot lots of types of bullets by using Instantiate to clone from a prefab, but the bullet keeps damaging my ship because even though the prefab is set to my "Player" layer (as well as my ship) and Player/Player collision is turned off, the bullet still hits me, which I eventually discovered is because it's cloning it onto the default layer instead of Player.
Is there any way I can force the bullet to clone onto the correct layer?
My full C# PlayerShooting.cs script (which is on the player) is this, in case it helps:
public class PlayerShooting : MonoBehaviour {
public GameObject bulletPrefab;
public float fireDelay;
float cooldownTimer = 0;
void Update () {
cooldownTimer -= Time.deltaTime;
if (Input.GetButtonDown ("Fire1") && cooldownTimer <= 0) {
// Bullet fires:
gameObject.layer = 10;
Instantiate(bulletPrefab, transform.position, transform.rotation);
gameObject.layer = 8;
Debug.Log("Fired!");
//Cooldown Timer is reset:
cooldownTimer = fireDelay;
}
}
}
gameObject.layer = Layer$$anonymous$$ask.NameToLayer("Player");
Try that.
Where do I put it in the script? I tried putting the bullet onto the player layer in my bullet movement script within Start() but by the time that script had the chance to run the bullet had of course been created, then destroyed by damaging my ship...
GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation) as GameObject;
bullet.layer = Layer$$anonymous$$ask.NameToLayer("Player");
Still not sure why it spawns it onto the default layer though...
Just added that then realised that whenever I press play it switches every object onto the default layer, not just the bullet. That seems even weirder... Any ideas?
Answer by phil_me_up · Dec 08, 2015 at 12:00 PM
As Vintar said above, you need to make sure you are setting the layer on your instantiated object.
However, as a general rule you don't want to be instantiating a bullet every time one is fired, instead you should consider making a bullet pool containing a number of bullets (depending on how many you expect to see on screen at any one time) and simply enable or disable these as you need them. A quick method for this is to just have an array of bullet game objects created. When you need to fire, find the next currently disabled bullet, enable it, position it correctly and then rather than destroying it when you don't need it anymore, just disable it.
Your answer
Follow this Question
Related Questions
Why is my Prefab Instantiating when the Scene is Loaded? 2 Answers
How to move Instantiated 2D objects by 0.5 using arrows(or mouse) 1 Answer
Instantied 2D Prefab Is Invisible 1 Answer
How to move Instantiated 2D objects by 0.5 using arrows 1 Answer
Instantiated clones arent behaving the same as the prefab 1 Answer