Home > Net >  Scoring points using triggers in Unity
Scoring points using triggers in Unity

Time:05-06

I want that whenever my player passes through a particular portion of my obstacle it should add 2 points to the score. In order to do this I've made a child of the obstacle. This child contains the box collider which covers that particular portion of the obstacle (I've switched on the Is Trigger in Unity).

Code on child having trigger -

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

public class Score : MonoBehaviour
{
    float points;
    
    void Start()
    {
    
    }

    void Update()
    {
        Debug.Log(points);
    }
    void OnTriggerExit2D(Collider2D other)
   {
        points  = 2f;
   }
}

The problem is that in the console the points are showing 0s and 2s only like this -

Console

While it should be 0, 2, 4, 6... after passing the obstacle.

Also clones of the original obstacle are being created, i.e. I pass through a new clone each time; in case this is causing the problem.

CodePudding user response:

Yeah it is obvious that it will print out 0s and 2s because your script doesn't use a centralized scoring system it just updates the score in that particular instance. You can make another script call it GameManager where you can make a player score variable and on trigger exit function of your child function would increment the score of that GameManager variable playerscore.

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

public class GameManager : MonoBehaviour
{
    public float playerPoints = 0f;
}

In Score Script

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

public class Score : MonoBehaviour
{
public GameManager manager; // Drag and drop the gamemanager object from scene in to this field
    void OnTriggerExit2D(Collider2D other)
   {
        manager.playerPoints  = 2f;
        Debug.Log(manager.playerPoints);
   }
}
  • Related