首页 > 解决方案 > 脚本之间的统一通信

问题描述

我正在制作 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!";
            }
        }
    }
}

编辑器视图 1

编辑器视图 2

标签: c#unity3d

解决方案


像这样的脚本之间的通信(与另一个类共享一个类的属性)在 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 的本教程,其中深入介绍了该主题。


推荐阅读