How to handle animation of multiple Coins?

Hi There!

I’ve been working on a 2d game, where the Character needs to pick up coins, and when a coin is picked up, it should make a simple animation in terms of movement, rotation and scale.

It looks like this: (The script is attached to the character)

using UnityEngine;
using System.Collections;

public class ScoreManager : MonoBehaviour {

	bool triggerAnimation = false;
	int triggerTimer;
	GameObject Coin;

	void Start () {
		triggerTimer = 300;
	}

	void FixedUpdate () {
		if (triggerAnimation && triggerTimer < 29) {
			if (Coin != null) {
				Coin.transform.Translate (0, 0.1f, 0, Space.World);
				Coin.transform.Rotate (0, 0, 20, Space.World);
				Coin.transform.localScale /= 1.05f;
			}
		}
		triggerTimer++;
	}

	void OnTriggerEnter2D(Collider2D trigger) {
		if (trigger.gameObject.tag == "coinSimple") {
			Coin = trigger.gameObject;
			triggerAnimation = true;
			triggerTimer = 0;
			Destroy(trigger.gameObject, 0.3f);
		}
	}
}

Thing is, as expected, only one coin at a time can have an animation, when another coin gets picked up, the previous coin stop its animation midway.

I’m reluctant to make a script for every coin, as there will be tons of them in the scene, and I fear it might have a heavy effect on performance.

I know why there is this problem, but I don’t know how to fix it, is there any feature I can use that will prevent this?

Thanks a bunch in advance :smiley:

One solution would be to make a Mecanim animation clip for the coin being collected, and just activate that when the coin is touched. I don’t know what is the effect on performance of all the coins being animated (the animator for each coin would be running even when the coin wasn’t being picked up), but animators have a setting only to run when the object is currently visible, which would help I suppose.
Animate Anything With Mecanim

Another solution would be to turn your variables (triggerAnimation, triggerTimer, Coin) into Lists, so that each one could values for a bunch of coins. That way, instead of FixedUpdate running that code for one coin, it would see how many are in the list, and run it for each one.
MSDN List Class Documentation

If you’ve used lists before, you may as well use that. Otherwise, it’s probably best to use Mecanim - it will be simpler, and will allow you to easily add other animations like making them spin before they get picked up.