# Character not collecting animated coins

I am trying to make a simple game where the player jumps and collects animated coins. After collecting all the coins, the scene is supposed to change. For some reason, my character collects the coins but the scene doesn't change.

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

public class Coins : MonoBehaviour
{
[SerializeField] private string newLevel;
public int coinAmount;
int coins ;

void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
coins += 1;

Destroy(gameObject);

}
}

{
coins++;

if (coins == coinAmount)
{
}
}
}


This is a screenshot of the game:

• Did you mean to nest your OnTriggerEnter2D function inside your Start function like that? – DMGregory Nov 5 '19 at 23:03
• @DMGregory No I did not, don't know how I let that slip. I have tried to fix the code now but it still isn't working. – user19964 Nov 5 '19 at 23:46
• Did you mean to spell OnTriggerEnter2D with an uppercase D as in the documentation? – DMGregory Nov 5 '19 at 23:59
• @DMGregory Yes🙈 I don't know why I am making such silly mistakes . So now the coins get destroyed but the next scene still doesn't load after all the coins have been destroyed, for some reason – user19964 Nov 6 '19 at 1:28
• can you share screen shot of then game play. so we could understand what sort of game it is, is it 2d or 3d. which type of collider is coin and player using. As 2d collider does not work with 3d collider. Also ther is uper Case D for OnTriggerEnter2D. – Swati Nov 6 '19 at 2:24

Since you have your OnTriggerEnter2D function in this script, it looks like this is the script you're placing on each individual coin.

That means that each individual coin has its own copy of the coins variable.

So you're not accumulating a total of how many coins are collected in your whole scene, you're just counting how many times this coin was collected.

To fix this, you can make the variable static, which makes it shared between all instances of the script. That might looks something like this:

public class Coin : MonoBehaviour {

static int _coinsLeftToCollect = 0;

[SerializeField]
string _nextScene;

// Keep a count of how many coins are still active in this scene.
// Doing this in OnEnable/OnDisable ensures each scene starts from zero.
void OnEnable() {
_coinsLeftToCollect++;
}

// When the count hits zero, trigger the load.
void OnDisable() {
// You may want to add an additional condition to skip triggering
if(--_coinsLeftToCollect == 0) {