[英]How do I pass a variable between scripts in Unity 2d C#
For example, I have a variable "Wisps" that I want to change when the player picks up an object.例如,我有一个变量“Wisps”,当玩家捡起一个物体时我想改变它。 But I don't know how to do it.
但我不知道该怎么做。 I tried to add a WispDisplay object to call the classes, like in Java, but it doesn't seem to work.
我尝试添加一个 WispDisplay 对象来调用类,就像在 Java 中一样,但它似乎不起作用。
public class WispCode : MonoBehaviour
{
WispDisplay wd = new WispDisplay();
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
wd.setWisp(wd.getWisp()+1);
Destroy(gameObject);
}
}
}
public class WispDisplay : MonoBehaviour
{
public int Wisp = 5;
public Text WispText;
void Start()
{
}
void Update()
{
WispText.text = "Wisp: " + Wisp.ToString();
}
public int getWisp()
{
return Wisp;
}
public void setWisp(int newWisp)
{
Wisp = newWisp;
}
}
Easiest (a tiny bit dirty) way is to use a static variable.最简单(有点脏)的方法是使用静态变量。 Downside: you can only have exactly ONE.
缺点:你只能有一个。
Example:例子:
public class MyClass: MonoBehaviour {
public static int wisps;
}
Then, in ANY class, just use this to access it:然后,在任何类中,只需使用它来访问它:
MyClass.wisps = 1234;
The more elegant way, working with multiple class instances, is using references.处理多个类实例的更优雅的方法是使用引用。
Example:例子:
public class PlayerClass: MonoBehaviour {
public int wisps = 0;
}
public class MyClass: MonoBehaviour {
public PlayerClass player;
void Update(){
player.wisps += 1;
}
}
Then, you need to drag-drop (aka "assign") the "PlayerClass" Component (attached to the player) to the the Gameobject that should increase the Wisps count.然后,您需要将“PlayerClass”组件(附加到玩家)拖放(也称为“分配”)到应该增加 Wisps 计数的 Gameobject。 You can duplicate these objects after assigning the reference.
您可以在分配参考后复制这些对象。
Now, if you actually want to have some sort of collectible, I'd suggest this approach:现在,如果您真的想拥有某种收藏品,我建议您采用这种方法:
You Have a Player "PlayerClass" and some Objects that are collectible, which have Trigger Colliders.你有一个玩家“PlayerClass”和一些可收集的对象,它们有触发碰撞器。
The objects have this code:对象具有以下代码:
public class Example : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
// probably a good idea to check for player tag:
// other.compareTag("Player");
// but you need to create the "Player" Tag and assign it to Player Collider Object.
if(TryGetComponent(out PlayerClass player))
{
player.wisps += 1;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.