Instantiate dont work well with destroyd

hi,
my game is 2d game that my bird need to collect coin.
every time when she get collision on the coin, i want to destroy the coin, and make a new one.
i try to do this with Instantiate, and i not succeeds. maybe couse my foor loop did good the work, but its for each coin, and it copy by exponential*. :eyes:*
this is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LifeAndCoinsScript : MonoBehaviour
{
    // Start is called before the first frame update
    public float speed = 5f;
    public int score = 0;
    private Rigidbody2D rb;

    private void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(-6, 0);
        SetPosition();
    }

    private void Update()
    {
        if (transform.position.x < -13) {SetPosition(); }
    }
    void OnCollisionEnter2D(Collision2D Collider )
    {
        Debug.Log(gameObject.name + "has colleted with " + Collider.gameObject.name);

        if (Collider.gameObject.tag.Equals("bird"))
        {
            score++;
            for(int i=1; i <= score; i++)
        {
            Instantiate(gameObject);
        }
            print("you have " + score + " points");
            Destroy(gameObject);          
        }
    }

    void SetPosition()
    {

        transform.position = new Vector3(Random.Range(20, 16), Random.Range(-2, 3), 0);
        transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, -3f, 3f), transform.position.z);

    }
}

Hello yacovm. For something like collecting coins, it might be better using Trigger instead of Collision. From the code above, it’s seems you tried to destroy a coin that you instantiated.
It will be better if you add a timer so the destroy function will destroy the coin you collected first and then instantiate a new coin.

void OnCollisionEnter2D(Collision2D Collider )
    {
        Debug.Log(gameObject.name + "has colleted with " + Collider.gameObject.name);
        if (Collider.gameObject.tag.Equals("bird"))
        {
            score++;
            for(int i=1; i <= score; i++)
        {
            Invoke("InstantiateCoin", 0.4f); //Timer so Destroy function will do it job first.
        }
            print("you have " + score + " points");
            Destroy(gameObject);         
        }
    }

void InstantiateCoin()
{
   Instantiate(gameObject);
}

or you can use Coroutine function.

1 Like