- Home /
Instaniate Prefab
so i have a problem both bullets are instantiating perfectly except bullet2 only ever instantiates once and when the button is pressed again it doesn't instantiate bullet 2 ever, only bullet 1 always instantiates properly.
if(facingRight && Input.GetKeyDown(KeyCode.Q))
{
Rigidbody2D bullet1Prefab;
anim.SetBool("shoot",true);
bullet1Prefab = Instantiate(bulletPrefab, BulletSpawn.position, BulletSpawn.rotation) as Rigidbody2D;
bullet1Prefab.AddForce(BulletSpawn.right * 100);
shootHappened();
}
if(!facingRight && Input.GetKeyDown(KeyCode.Q))
{
Rigidbody2D bullet2Prefab;
anim.SetBool("shoot",true);
bullet2Prefab = Instantiate(bullet3Prefab, BulletSpawn2.position, BulletSpawn2.rotation) as Rigidbody2D;
bullet2Prefab.AddForce(BulletSpawn2.transform.position = go * 100);
shootHappened();
}
Any help would be appreciated. (also the bulletspawn2.transform.position = go is assigning the bullet to go left not right since for some reason unity technologies thinks in 2D the player is ever only going to go right)
Can you show where the variable facingRight is being changed? If the bullet1 is the one instantiating every time, it seems the problem is there.
Answer by vanshika1012 · Sep 19, 2014 at 02:05 PM
You can use array and store your bullets in that. Initially each bullet is setActive false. So at a point of initiation check which one is false. The one which is false , make it active. Next time second bullet chance will come. When the bullet goes off the screen make it false again.
GameObject arr[] = new GameObject[5];
void InstantiateObject()
{
for( int i = 0 ; i < 5 ; i++)
{
arr[i] = Instantiate(bullet) as GameObject;
arr[i].SetActive(false);
}
}
void activeObject()
{
for(int i = 0 ; i<5 ; i++)
{
if(arr[i].activeInHierarchy == false)
{
arr[i].setActive(true);
//Do whatever you want like the position or scale etc.
//arr[i].GetComponent<Script>().enable = true;
break;
}
}
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Instantiating on Input 1 Answer
Need help with instantiating a prefab in c# 2 Answers
Multiple Cars not working 1 Answer
Instantiate prefab (button, texture) with attached script 1 Answer