0

I am making a game, similar to the one in this tutorial: https://www.youtube.com/watch?v=r5NWZoTSjWs&list=PLPV2KyIb3jR53Jce9hP7G5xC4O9AgnOuL&index=11

I am trying to implement collectable "objects" that give you more points (3 of them on one level) So I used a variable gemCounter, that increases by one every time the player collides with the "gem"

What's wrong? On every trigger, the code returns 1 as the result...

Screenshot


using UnityEngine;
using UnityEngine.UI;

public class GemTrigger : MonoBehaviour
{
    public SphereCollider Sc;
    public MeshRenderer Mr;

    public int gemCounter = 0;

    private void OnTriggerEnter()
    {
        gemCounter += 1;
        Mr.enabled = false;
        Debug.Log("Gem " + gemCounter + " detected");
    }
}

M. Lake
  • 3
  • 2

2 Answers2

1

Another option you have would be to attach gemCounter to the player object. Then you could tag the player with "Player" and add a script potentially called "PlayerController" and use

GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>().gemCounter+= 1;

This will allow you to keep track of the gemCounter from the player as opposed to on each individual gem.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
JLiebman
  • 80
  • 7
0

Each instance of GemTrigger has its own copy of the gemCounter field because it's not a static field.

One change you could use is making gemCounter static with:

public static int gemCounter = 0;

Or, better yet, put gemCounter in a singleton and have all of the GetTrigger instances modify the gemCounter in that singleton.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48