c# - Sharing variable data back and forth between scripts
问题描述
I have one script calling COINS getting coins
every time an object collides. I want to take coins
and move the data into another script called SHOP. In SHOP I want to modify the money, for example subtract it. Then transfer that data back to COINS.
解决方案
这在 Unity 中很容易做到。
您需要引用可以使用公共变量完成的脚本:
public class Shop : Monobehaviour {
public Coins coins;
}
// ---
public class Coins : Monobehaviour {
int totalCoins;
}
然后您可以使用编辑器将脚本拖到变量中。不过要小心,您不能(在这种情况下)从项目文件中拖动脚本。您必须使用附加到您的游戏对象的那个。
然后,如果您想要Shop
减去硬币,您所要做的就是使用Coins
脚本变量的引用。
public class Shop : Monobehaviour {
public Coins coins;
public void SubtractCoins(int toSub) {
coins.totalCoins -= toSub;
}
}
如果您的变量是公开的,那真的很容易。这就是您可以开始让脚本相互“交流”的方式。
推荐阅读
- javascript - 图像地图上的 onmouse enter 和 onmouseleave 无法使用 IE11 或 Edge 正确触发,但可与其他浏览器一起使用
- python - DRF:API 设计
- angular - 我正在使用的 ng-select 角度库使用回车键选择一个选项,我需要它在选项卡上
- c# - 无法在 JQuery 中获取/绑定正确的实体 ID,总是从迭代中获取第一个项目 ID
- python - selenium 过滤掉 _blank,这会打开新选项卡
- c# - 将 [必需] 添加到基类 IdentityUser
- python - PermissionError: [Errno 13] Permission denied: 'tesseract' when launching kivy app with buildozer: android mobile app
- android - Flutter - NoSuchMethodError:方法'visitChildren'在null上被调用
- c - 如何获取我通过程序调用的 exe 的标准输出?
- reactjs - 无法使用 Amplify Auth.currentAuthenticatedUser 检索用户名