- Home /
Destroying GameObject does not add to Debug.Log counter
Hi, I'm trying to make a game where a Player picks up presents and delivers it to people
My problem is that that I want to have a counter on my console telling me how many presents the Player has picked, but it's remaining stuck at 1 no matter how many presents I pick. https://i.imgur.com/jDYoQoh.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Present : MonoBehaviour
{
[SerializeField]
//setting the amount of time presents need to despawn
private float despawn = 5f;
public int presentCount = 0;
// Start is called before the first frame update
void Start()
{
//present counter is set to 0
presentCount = 0;
//start the despawn timer
Destroy(this.gameObject, despawn);
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
//if player picks up present, present is destroyed (still need to add to console counter)
if(other.transform.name == "Player")
{
presentCount++;
Debug.Log("Present Count: "+ presentCount);
Destroy(this.gameObject);
}
}
}
I know that it has something to do with the gameObject destroying itself therefore not being able to add to the counter, but I'm not sure how to solve this problem. I've tried putting a counter in Start(), I've tried using OnDestroy() but still arrived to the same result.
The result that I want is that every time I pick up a present, Debug.Log adds +1 to the counter.
If you need any other details please tell me and I will add them, thanks !
Answer by ryanlin138 · Jan 06, 2021 at 06:48 PM
You have to make the presentCount static, otherwise each individual present would have a different count.
Replace Line 11:
public int presentCount = 0;
With:
public static int presentCount = 0;
Keep in mind that you would no longer be able to see the parameter in the inspector.
Your answer

Follow this Question
Related Questions
host set to C:\Program Files\Unity\Hub\Editor\2019.4.9f1\Editor\Data\Tools\RoslynScripts\..\.. 0 Answers
How to add score after destroying object? 1 Answer
Respawn Management 2 Answers
1 exception was raised by workers: See the Console for details. 0 Answers
Unity Console not showing result 1 Answer