- Home /
Instantiate and time problem
So I'm trying to achieve something like Fruit Ninja's frenzy mode where you slice the special fruit and there will be lots of fruits spawning out. I already made a prefab. And the trigger to instantiate numerous prefabs is done as well. Now my problem is that when I touch the trigger, there is only one prefab spawning out. I want it to instantiate 20 of them one by one. Here is my script, any help would be greatly appreciated!
public GameObject LikeButton;
float randX;
Vector2 wheretoSpawn;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
Collider2D col;
void Start()
{
col = GetComponent<Collider2D>();
}
public void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
if (touch.phase == TouchPhase.Began)
{
Collider2D touchedCollider = Physics2D.OverlapPoint(touchPosition);
if (col == touchedCollider)
{
Destroy(gameObject);
CreateLikeButtons(20);
}
}
}
}
public void CreateLikeButtons(int buttons)
{
for (int i = 0; i < buttons; i++)
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
}
randX = Random.Range(-2f, 2f);
wheretoSpawn = new Vector2(randX, transform.position.y);
Instantiate(LikeButton, wheretoSpawn, Quaternion.identity);
}
}
$$anonymous$$ake sure that you do not have any script on the prefab that destroys it. Also, the variable nextSpawn in your code is not playing any role. Also, Camera.main.ScreenToWorldPoint take Vector3 argument and Touch.position is vector2
Actually I'm a beginner in C#, the script that I used are from different tutorials, I'm not sure how to implement the variable nextSpawn to the code, can you perhaps give me some suggestion on how I can make that variable work? Thank you so much for the advice.
Answer by xxmariofer · Oct 31, 2019 at 08:00 AM
public GameObject LikeButton;
float randX;
Vector2 wheretoSpawn;
public float spawnRate = 2f;
Collider2D col;
void Start()
{
col = GetComponent<Collider2D>();
}
public void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
if (touch.phase == TouchPhase.Began)
{
Collider2D touchedCollider = Physics2D.OverlapPoint(touchPosition);
if (col == touchedCollider)
{
Destroy(gameObject);
StartCoroutine(CreateLikeButtons(20));
}
}
}
}
public IEnumerator CreateLikeButtons(int buttons)
{
for (int i = 0; i < buttons; i++)
{
randX = Random.Range(-2f, 2f);
wheretoSpawn = new Vector2(randX, transform.position.y);
Instantiate(LikeButton, wheretoSpawn, Quaternion.identity);
yield return new WaitForSeconds(spawnRate );
}
}