Unity3D - Counter always back to ZERO

i create simple counter using Unity3D with C#. it's purpose to count total of click to a button.

if i test at unity3d editor, it's fine... counter will count up.

but every time i test to device, if i click counter button, then it always back to zero.

any idea ?

below are the source codes :

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

public class z_manual : MonoBehaviour {

    private int counter;
    public GameObject textCounter;

    public void addCounter()
    {
        counter = counter + 1;
        textCounter.GetComponent<Text> ().text = counter.ToString ();
    }

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
}

Note : 1) Button Click will call method addCounter() 2) textCounter is Normal Unity UI Text

1 answer

  • answered 2018-11-08 08:31 Andrea ジーティーオー

    You have to initialize counter to 0. Actually it is just declared, not initialized, so its value could be "dirty" among instances of your application's process.