I declared a private int tree_count in a class SpawnManager. void Start() and void Update() uses the variable as expected, but another method, public void Tree_destroyed seems to be using a different tree_count.
Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
private int tree_count;
// Start is called before the first frame update
void Start()
{
tree_count = 500;
}
// Update is called once per frame
void Update()
{
if (Time.time < 3.05)
{
print(tree_count);
}
}
public void Tree_destroyed()
{
tree_count--;
print(tree_count);
}
}
void Update() prints 500 for the tree_count, but public void Tree_destroyed() prints 0, and goes to -1, -2,... for every method call.
public void Tree_destroyed() is called by an object with this script:
using System.Collections.Generic;
using UnityEngine;
public class TreeBehaviour : MonoBehaviour
{
public GameObject spawnManager;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, 3);
}
// Update is called once per frame
void Update()
{
}
private void OnDestroy()
{
spawnManager.GetComponent<SpawnManager>().Tree_destroyed();
}
}
Any idea why it behaves like that? Any help would be appreciated.
EDIT 1: For the order of things that happen: first, private int tree_count is initialized, void Start() is called which sets tree_count to 500, void Update() is called every frame, which shows tree_count as 500, void Tree_destroyed is called after 3 seconds, which shows a different tree_count, void Update() is called in the next frame, showing tree_count as still 500.
EDIT 2: There are only 3 objects in the scene, the camera (no scripts attached), object with SpawnManager, and another object that calls Tree_destroyed when destroyed. I'm sure there are no duplicate objects or scripts.
SpawnManager
, and for the second you never call theStart
method. That's my guess. – Mario Vernari