我在做一个Unity3D游戏。我想实现脚本Timer.cs和Collide.cs之间的连接,通过它们来交换变量obji。在你把这个问题标记为重复之前,我想提一下已经读过本教程的问题。作为解决方案的结果,只要我得到了错误
命名空间不能直接包含成员,如字段或方法。
您能提供一个解决方案来在没有共同元素的脚本之间交换信息吗?我希望Timer.cs从Collide.cs获取变量obji
Timer.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()
{
}
}Collide.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!";
}
}
}
}


发布于 2019-01-31 19:08:14
这样的脚本之间的通信(共享一个类的属性和另一个类的属性)是非常常见的任务。需要另一个类的属性值的脚本应该获得对另一个类的引用。
在您的示例中,由于Timer需要从Collide类访问obji属性,因此需要将对Collide类的引用添加到Timer类:
public class Timer : MonoBehaviour
{
public Collide _collide;
// The rest of the script...
}然后,在“团结中的检查器”中,您需要拖动一个GameObject,该Collide脚本将Collide脚本附加到GameObject的_collide属性并附加Timer脚本。
最后,您可以通过新创建的引用访问obji属性:
if (_collide.obji > 0)请参阅本教程来自团结,它深入讨论了这个主题。
发布于 2019-01-31 19:09:45
您曾经收到的错误:
命名空间不能直接包含成员,例如字段或方法,
告诉您,在命名空间中不能直接放置任何方法或字段(即变量)。命名空间只能包含
一般来说,名称空间用于提供特定范围和组织实体。
有许多方法可以访问另一个类的成员字段。最干净和最简单的方法是通过所谓的Getter方法(也是通过get 属性)。您应该避免使用和引用公共字段。例如,在Collide类中
// You don't have to always initialize your fields: they have default values.
// Initialize only when you need to.
private int obji;
...
public int GetObji() {
return obji;
}现在,要调用该方法,需要对其进行适当的引用。为此,您可以简单地将其作为参数添加到计时器类中:
public Collide CollideRef;
...
// Get the field
CollideRef.GetObji();然后,只需拖放GameObject,将Collide组件拖放到它上。
https://stackoverflow.com/questions/54467438
复制相似问题