c# - 我的班级似乎有 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 的对象。我确定没有重复的对象或脚本。
解决方案
有可能因为这是一个类对象,所以有两个具有相同私有变量的对象实例。在没有看到您项目的其余部分的情况下,这是最有可能的答案。
推荐阅读
- php - 如何从会话 php/mysqli 中获取客户 ID?
- c# - Xamarin ListView 未填充 XAML。绑定问题
- angular - 错误:如果在表单标记中使用 ngModel,则必须设置名称属性或表单。控件必须在 ngModelOptions 中定义为“独立”
- javascript - JSON解析返回未定义的值
- angular - Ionic 3 应用程序中的 Sqlite 本地存储问题
- perl - 将一个数组与另一个数组进行比较,然后在该数组中排序
- javascript - 如何在路由器中正确延迟加载 vuejs 组件
- spring - 建议 SpringBoot WhiteLabel 错误页面的解决方案?
- angular - Angular 安装命令到底做了什么?
- html - 为什么 HTML 标签在 JSP 文件中不兼容?