Unity2D中如何跨函数访问变量?Attack方法报错求助
问题分析与解决
你的核心问题是局部变量的作用域限制:DefineVariables()里定义的phealth、pdamage、ehealth都是函数内部的局部变量,只能在该函数内访问,Attack()根本看不到这些变量。另外代码还有语法错误和冗余调用的问题,下面一步步修正:
步骤1:定义类级别的静态成员变量
因为你的DefineVariables()和Attack()都是static方法,所以需要把要共享的变量定义为类的静态成员变量,这样整个类的静态方法都能访问:
public class DefaultEnemy : MonoBehaviour { // 定义类级别的静态变量,供静态方法共享 private static int phealth; private static int pdamage; private static int ehealth; // 缓存VStorage组件,避免重复查找 private static VStorage vStorage;
步骤2:优化变量初始化逻辑
不要多次调用GameObject.Find()和GetComponent(),一次获取组件后复用,提升性能:
public static void DefineVariables() { // 只查找一次VStorage组件 if (vStorage == null) { vStorage = GameObject.Find("VStorage").GetComponent<VStorage>(); } // 给静态成员变量赋值,而不是定义新的局部变量 phealth = vStorage.phealth; pdamage = vStorage.pdamage; ehealth = vStorage.ehealth; }
步骤3:修正Attack()方法的错误
补上缺失的分号,并且正确访问静态成员变量,同时建议同步更新VStorage内的数值,保证数据持久化:
public static void Attack() { ehealth -= pdamage; // 等价于ehealth = ehealth - pdamage,写法更简洁 // 同步更新VStorage中的敌人血量 if(vStorage != null) { vStorage.ehealth = ehealth; } }
完整修正后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class DefaultEnemy : MonoBehaviour { private static int phealth; private static int pdamage; private static int ehealth; private static VStorage vStorage; public static void DefineVariables() { if (vStorage == null) { vStorage = GameObject.Find("VStorage").GetComponent<VStorage>(); } phealth = vStorage.phealth; pdamage = vStorage.pdamage; ehealth = vStorage.ehealth; } public static void Attack() { ehealth -= pdamage; if(vStorage != null) { vStorage.ehealth = ehealth; } } private void Start() { DefineVariables(); } private void Update() { } }
额外提示
- 如果按钮绑定不需要
static方法,可以去掉DefineVariables()和Attack()的static修饰符,变量也改成非静态的,这更符合Unity组件的常规写法。 GameObject.Find()效率较低,如果VStorage是全局管理类,建议用单例模式(比如VStorage.Instance)直接获取,避免查找错误。
内容的提问来源于stack exchange,提问作者Mr Glub
相关产品推荐
相关产品推荐

