using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collectable : MonoBehaviour
{
[SerializeField] int rotateSpeed = 1;
[SerializeField] AudioSource coinFx;
[SerializeField] GameObject coins;
[SerializeField] int Totalcoins = 20;
void Start()
{
SpawnCoin();
}
private void SpawnCoin()
{
for (int i = 0; i < Totalcoins; i++)
{
Vector3 randomPosition = new Vector3(Random.Range(-5, 5), 1, Random.Range(-5, 5));
Instantiate(coins, randomPosition, Quaternion.identity);
}
}
private void OnTriggerEnter(Collider other)
{
if(coinFx != null)
{
coinFx.Play();
}
CollectableControl.coincount += 1;
Destroy(gameObject);
SpawnCoin();
} private void Update()
{
transform.Rotate(0, rotateSpeed, 0, Space.World);
}
}
1 Like
....
CollectableControl.coincount += 1;
Destroy(gameObject);
SpawnCoin();
...
become
....
CollectableControl.coincount += 1;
SpawnCoin();
Destroy(gameObject);
...
1 Like
However, I would avoid such way at all.
- Destroying is Runtime is not the best option to operate with memory.
- Instead of that, you can use GameObject.SetActive to avoid performance issues in running scene. When the Level is over, and you load the new level (I guess this way you use in your game), and then Unity automatically destroys what needed.
1 Like