Search Unity

Problem with 2D text output.

Discussion in '2D' started by alex2007kosh, Jan 7, 2021.

  1. alex2007kosh

    alex2007kosh

    Joined:
    Jan 7, 2021
    Posts:
    3
    Hello. I want to create counter in my 2D game. When player touching object (tree), script add 1 money(for example) to it.
    In real counter adding 1 money every frame. I don't know how to fix this.
    May be this problem with code?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class TextCounter : MonoBehaviour
    7. {
    8.  
    9.     [SerializeField]public static float moneyCount;
    10.     Text count;
    11.  
    12.     void Start(){
    13.         count = GetComponent<Text> ();
    14.     }
    15.  
    16.     void Update(){
    17.         count.text = "Money: " + moneyCount.ToString();
    18.     }
    19. }
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,466
    You need to have it occur every time the object intersects with the tree's collider. So use an OnTriggerEnter2D function.
    In that function you can determine if the object that intersected with the tree's collider is the player, then increase score or moneyCount.

    Code (CSharp):
    1. void OnTriggerEnter2D(Collider2D other)
    2. {
    3.     if(other.gameObject.tag == "Player")
    4.     {
    5.          moneyCount++;
    6.     }
    7. }
    Something like that. Check out the OnTriggerEnter2D page: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html

    Or, check out a video on creating a score/counter system:
     
    MarekUnity likes this.
  3. alex2007kosh

    alex2007kosh

    Joined:
    Jan 7, 2021
    Posts:
    3
  4. Alice0400

    Alice0400

    Joined:
    Jan 7, 2021
    Posts:
    1
    Thank You Soo Much