c# - 脚本之间的统一通信
问题描述
我正在制作 Unity3D 游戏。我想实现脚本 Timer.cs 和 Collide.cs 之间的连接,它们通过它交换变量obji
. 在您将此问题标记为重复之前,我想提一下已经阅读过本教程的问题。由于提供的解决方案,我得到了错误
命名空间不能直接包含字段或方法等成员
您能否提供在没有共同元素的脚本之间交换信息的解决方案。obji
我希望 Timer.cs从 Collide.cs获取变量
定时器.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public ScoresManager ScoresManager;
Text instruction;
// Start is called before the first frame update
void Start()
{
instruction = GetComponent<Text>();
InvokeRepeating("time", 0, 1);
}
void time() {
if (timeLeft <= 0){
/* if(move.obji() <= 0){
instruction.text = "You win!";
}else{
instruction.text = "You lost!";
}*/
} else {
timeLeft = timeLeft - 1;
instruction.text = (timeLeft).ToString();
}
}
// Update is called once per frame
int timeLeft = 30;
void Update()
{
}
}
碰撞.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Collide : MonoBehaviour
{
public Text txt;
public int obji = -1; //this is an example, I always try to initialize my variables.
void Start()
{ //or Awake
obji = GameObject.FindGameObjectsWithTag("Enemy").Length;
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.tag == "Enemy")
{
transform.localScale -= new Vector3(0.03F, 0.03F, 0.03F);
Destroy(collision.collider.gameObject);
obji = obji - 1;
Debug.Log(obji);
if ((obji) > 0)
{
txt.text = (obji).ToString();
}
else {
txt.text = "You win!";
}
}
}
}
解决方案
像这样的脚本之间的通信(与另一个类共享一个类的属性)在 Unity 中是一项非常常见的任务。需要另一个类的属性值的脚本应该获得对另一个类的引用。
在您的示例中,由于Timer
需要obji
从类访问属性Collide
,因此您需要向类添加对类的Collide
引用Timer
:
public class Timer : MonoBehaviour
{
public Collide _collide;
// The rest of the script...
}
然后,在 Unity 的 Inspector 中,您需要拖动一个带有附加脚本的 GameObject 到附加了脚本的 GameObjectCollide
的_collide
属性Timer
。
最后,您可以obji
通过新创建的引用访问该属性:
if (_collide.obji > 0)
请参阅Unity 的本教程,其中深入介绍了该主题。
推荐阅读
- unity3d - DirectoryNotFoundException:找不到路径的一部分。(C# - 统一)
- python - 'from X import a' 有效,但 'import X; Xa'没有
- java - 采用 int 数组、int 索引和 int 值的方法
- node.js - 如何在 MongoDB 的聚合管道中获取当前时间戳?
- windows - 使用汇编语言打印字符串变量
- java - 由于 java.lang.VerifyError,打开 APK 失败
- python-3.x - 使用 pip3 安装 Jupyterlab 和使用 homebrew 安装 python3 后无法从终端启动 Jupyterlab
- php - 使用 PHP 生成链接以恢复订单
- python-3.x - 不兼容的形状:[32] 与 [4536] [[{{nodelogistic_loss/mul}}]]
- unity3d - Unity下拉菜单未正确刷新