I want to make a game where you have to continue on to get more scores. As the game goes on and more coins spawn in the game, the game starts to lack.
In order to fix it, I want to destroy prefabs (coins) after they are far from the player. But every spawned coin has the position (0,0,0) although they are spawned around the player.
How can I give cloned prefab position? Or how can I destroy them, as it is outside from the main camera?
this was the code I used:
`
for (int i = 0; i < 100; i++)
{
Vector3 ForwardPos = new Vector3(Random.Range(EndDis.x - 100, EndDis.x + 100), Random.Range(0, 500),0);
Instantiate(CirclePrefab, ForwardPos, Quaternion.identity);
}
`
Also note that you can try to fix your first problem too (the spawn overload).
I’m not very familiar with the implementation, but I’m sure you’re smart enough to get it quickly.
The problem you have could might be solved with object pooling.
If you want to destroy them then you can do the following.
First, you need to create a GameObject called ‘Coins’ and a reference to the ‘Player’ character in the script…
Then change your script to this
for (int i = 0; i < 100; i++)
{
Vector3 ForwardPos = new Vector3(Random.Range(EndDis.x - 100, EndDis.x + 100), Random.Range(0, 500),0);
Coins *= Instantiate(CirclePrefab, ForwardPos, Quaternion.identity);*
}
foreach (GameObject Coin in Coins)
{
if (Vector2.Distance(Coin.transform.position, MainPlayer.tranform.position) > 5f) //You change the value ‘5f’ to anything you like
{
Destoy(Coin);
}
}
Refer to the Object.Instantiate reference inside the documentation.
This is probably what you’re looking for:
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);