- Home /
How to instantiate prefabbed objects via array in c# ?
There are two prefabbed objects in my game namely stone and water. I want to spawn them randomly at random position after the previously spawned object is destroyed. I managed to spawn as i wanted them but the problem is few of the spawned objects are colliding with the cup placed below but some are just passing through the cup without colliding even though they are the same prefabs. Iam not getting what caused that. I would very much appreciate some help.
water and stone scripts are the same .
----water.cs----
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class water : MonoBehaviour
{
bool collidedwithcup = false;
public spawnpool spawnerscript;
// Start is called before the first frame update
void Start()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
collidedwithcup = true;
}
// Update is called once per frame
void Update()
{
if (collidedwithcup == true)
{
collidedwithcup = false;
spawnpoolcaller();
Destroy(gameObject);
}
}
void spawnpoolcaller()
{
spawnerscript.Spawner();
}
}
-----spawnpool.cs-----
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnpool : MonoBehaviour
{
public GameObject[] spawnPool = new GameObject[2];
public void Spawner()
{
Instantiate(spawnPool[Random.Range(0, 3)], new Vector3(Random.Range(-2.5f, 2.5f), 5.55f, 0), Quaternion.identity);
}
}alt text
Answer by logicandchaos · Sep 10, 2021 at 03:57 PM
Rather than destroy and instantiate, when there is a collision just randomly teleport the object, it will look like a new one just spawned in and is way more efficient.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Physics2D.OverlapBox not working as expected. 1 Answer
physics for 2D game 1 Answer
OnCollisionExit problem 1 Answer