首页 > 解决方案 > 我的班级似乎有 2 个同名的不同变量

问题描述

我在 SpawnManager 类中声明了一个私有 int tree_count。void Start() 和 void Update() 按预期使用变量,但另一种方法 public void Tree_destroyed 似乎使用了不同的 tree_count。

这是我的代码。

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() 为 tree_count 打印 500,但 public void Tree_destroyed() 打印 0,并为每个方法调用转到 -1、-2、...。

public void Tree_destroyed() 由具有此脚本的对象调用:

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();
    }
}

知道为什么它会这样吗?任何帮助,将不胜感激。

编辑 1:对于发生的事情的顺序:首先,初始化 private int tree_count,调用 void Start(),将 tree_count 设置为 500,每帧调用 void Update(),将 tree_count 显示为 500,调用 void Tree_destroyed 3 秒后,显示不同的 tree_count,在下一帧调用 void Update(),显示 tree_count 仍为 500。

编辑 2:场景中只有 3 个对象,相机(未附加脚本),带有 SpawnManager 的对象,以及另一个在销毁时调用 Tree_destroyed 的对象。我确定没有重复的对象或脚本。

标签: c#unity3d

解决方案


有可能因为这是一个类对象,所以有两个具有相同私有变量的对象实例。在没有看到您项目的其余部分的情况下,这是最有可能的答案。


推荐阅读