Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Coin pickup problems D:

Discussion in '2D' started by Whadafuxhup, Jun 28, 2019.

  1. Whadafuxhup

    Whadafuxhup

    Joined:
    Jun 28, 2019
    Posts:
    13
    I'm pretty new to this so any help would be much appreciated!
    I'm trying to setup coins with pickup animations in my 2D platformer, my current code is:

    Code (CSharp):
    1. public class CoinScript : MonoBehaviour
    2. {
    3.     public GameObject coinPickup;
    4.  
    5.  
    6.     void OnCollisionEnter2D (Collision2D col)
    7.     {
    8.         if (col.gameObject.tag.Equals ("Player"))
    9.         {
    10.             Instantiate(coinPickup, transform.position, transform.rotation);
    11.             Destroy(gameObject);
    12.         }
    13.     }
    It works fine when picking up the first coin ie the coin disappears and an animation is played (But only if it's coin1 o.o) however when I then move to pickup a second coin it tells me the game object has already been destroyed and I end up kicking the coin away (they all have Rigidbody's, I like em bouncy!)

    The code seems to be removing the effect associated with the Instantiate line from other coins using the same script after it's been ran once, is there an easy way to fix this?
     
    Last edited: Jun 28, 2019
  2. Magnumstar

    Magnumstar

    Joined:
    Oct 3, 2015
    Posts:
    304
    What does the instantiate do? You shouldn't need that. If each coin has coinscript it should only play animation and check for animation.isPlaying = false then destroy
     
  3. Whadafuxhup

    Whadafuxhup

    Joined:
    Jun 28, 2019
    Posts:
    13
    Sorry perhaps I wasn't clear, Instantiate triggers a particle effect. The problem is all other coins lose that effect and so the script can't complete when I run into a second coin.
     
  4. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    are the coins prefabs or duplicates ? Make the prefab from the coin and use it.
     
    Magnumstar and Whadafuxhup like this.
  5. Whadafuxhup

    Whadafuxhup

    Joined:
    Jun 28, 2019
    Posts:
    13
    Thanks vaka, that's fixed it!