首页 > 解决方案 > 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.

标签: c#unity3d

解决方案


这在 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;
  }

}

如果您的变量是公开的,那真的很容易。这就是您可以开始让脚本相互“交流”的方式。


推荐阅读