Search code examples
c#2dcollision-detectionlevels

How to make the next level accessible only after a certain amount of coins are collected?


I'm currently programming a short game in Unity using c# where the player collects 10 coins to get to the next level. I'm having trouble making my DoorController script recognise the number of coins that have been collected.

My goal is to have heavengate locked until the Player can reach a coinValue of 10, at that point it will unlock heavengate which the player can walk through to load the next level. Using this script I receive no errors but the door doesn't act how I'm expecting it to as it still let's me pass through without collecting all the coins.

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

public class DoorController : MonoBehaviour
{
public int index;
public string levelName;
public int coinValue;

void  OnTriggerEnter2D(Collider2D heavengate)
{
    if (heavengate.gameObject.CompareTag("Player") && coinValue >= 10)
    Debug.Log("Coins collected" + coinValue);
    {
        SceneManager.LoadScene("EndScreenScene");
    }
}

'heavengate' is the name of the door to the next level and is set to 'Is Trigger', while the'Player' is the tag for the Player, obviously, and is not set as a trigger!

The Player and heavengate both have Box Collider 2d's and Rigidbody 2d's. heavengate is set as Kinematic also while Player is Dynamic.

I also have a CoinCollector script on my Player to destroy the coins on collision and add up the coins collected, I'll throw that in incase it can help!

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

public class CoinCollector : MonoBehaviour
{
public int coinsCollected;

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Coin"))
    {
        coinsCollected++;
        Destroy(other.gameObject);
    }
}

}

If anyone can help me that'd be greatly appreciated I've been stuck on this for a couple days, watching tutorials and reading posts from here and other forums, nothing seems to be working :( It is probably something very simple but I can't see it! Thank you!!


Solution

  • Hmm, for me that doesnt make much sense unless you still forgot to show something. In the second script you assign a variable the script itself, I cant think of any case where this is usefull. Than you wrote a method which you never call (Change Score) and in the CoinCollector Class you assign the coins collected to an int, but never use it in any of the other scripts. Heres how I would do it:

    1. Reference Coincollector in DoorController public CoinController coincontroller;

    2. Set coinsCollected to public static int coinsCollected;

    3. In onTrigger you do coinValue = CoinCollector.coinsCollected; before the if statement

    That should work perfectly fine, you don't even need the second script, but i dunno, maybe its usefull for you. Hope that helped.