脚本之间的统一通信

时间:2019-01-31 18:55:13

标签: c# unity3d

我正在制作Unity3D游戏。我想在脚本Timer.cs和Collide.cs之间实现连接,通过它们它们可以交换变量obji。在您将此问题标记为重复问题之前,我想提一下已经读过this tutorial的问题。作为提供解决方案的结果,我得到了错误

  

名称空间不能直接包含字段或方法之类的成员

您能提供一种在没有共同元素的脚本之间交换信息的解决方案吗?我希望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!";
            }
        }
    }
}

Editor view 1

Editor view 2

2 个答案:

答案 0 :(得分:2)

像这样的脚本之间的通信(将一个类与另一个类共享属性)是Unity中非常常见的任务。需要另一个类的属性值的脚本应该获得对该另一个类的引用。

在您的示例中,由于Timer需要访问obji类中的Collide属性,因此您需要向{{ 1}}类:

Collide

然后,在Unity的检查器中,您需要拖动一个GameObject,该GameObject的Timer脚本已附加到GameObject的public class Timer : MonoBehaviour { public Collide _collide; // The rest of the script... } 属性中,并附加了Collide脚本。

最后,您可以通过新创建的引用访问_collide属性:

Timer

请参见this tutorial from Unity,其中详细介绍了此主题。

答案 1 :(得分:0)

您曾经收到的错误:

  

名称空间不能直接包含诸如字段或方法之类的成员,

告诉您,不能在名称空间中直接放置任何方法或字段(即变量)。名称空间只能包含

  • 类,
  • 界面
  • 枚举
  • 代表,
  • 结构
  • 命名空间。

通常来说,名称空间用于提供特定范围和组织实体。


有很多方法可以访问另一个类的成员字段。最干净,最简单的方法是通过所谓的Getter方法(也可以通过get properties)。您应该避免使用和引用公共字段。例如,在您的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;
}

现在,要调用该方法,您需要对其进行适当的引用。为此,您可以将其简单地添加为Timer类中的参数:

public Collide CollideRef;
...
// Get the field
CollideRef.GetObji();

然后只需拖放GameObject,将Collide组件放到上面即可。

相关问题