【问题标题】:In unity3D, how to get the variable from other gameobject?在 unity3D 中,如何从其他游戏对象中获取变量?
【发布时间】:2014-03-02 10:42:22
【问题描述】:

我已成功将蓝牙设备连接到 unity 并尝试使用读取的数据来控制其他游戏对象 以此为参考 http://answers.unity3d.com/questions/16484/how-to-import-neurosky-mindset-data-into-unity.html

我将连接脚本附加到一个空的游戏对象,它可以读取一些变量。 我将所有变量设置为 public int 并将连接脚本包含到另一个游戏对象脚本

public s_ReadNeuro readNeuroScript;

问题是在那之后,我不知道如何从不断读入的连接脚本中获取公共变量(例如,注意力和冥想值)。 我怎样才能得到它们并在另一个游戏对象脚本中使用它?谢谢

这是附加到空游戏对象的连接脚本

using UnityEngine;
using System.Collections;

public class s_ReadNeuro : MonoBehaviour {


public int tgHandleId;
public int tgConnectionStatus;
public int tgPacketCount;
public float attention;
public float meditation;
// Use this for initialization
void Start () {
   setupNeuro();
}

// Update is called once per frame
void Update () {
   readNeuro();
}


void setupNeuro() {
    tgHandleId = ThinkGear.TG_GetNewConnectionId();

    tgConnectionStatus = ThinkGear.TG_Connect(tgHandleId,
                                     "\\\\.\\COM4", 
                                     ThinkGear.BAUD_9600, 
                                     ThinkGear.STREAM_PACKETS);

}


void readNeuro() {
    tgPacketCount = ThinkGear.TG_ReadPackets(tgHandleId, -1);

    attention = ThinkGear.TG_GetValue(tgHandleId,  ThinkGear.DATA_ATTENTION);

    meditation = ThinkGear.TG_GetValue(tgHandleId, ThinkGear.DATA_MEDITATION);

}}

【问题讨论】:

  • 不确定我是否理解您想要什么,但您是否尝试过将变量设为静态?

标签: c# unity3d


【解决方案1】:

基本上有两种方法可以做到这一点。将您的 OtherGameObject 与编辑器中的 s_ReadNeuro 游戏对象连接起来,或者使用 Unity 的查找函数在 OtherGameObject 中查找 s_ReadNeuro 游戏对象。使用哪一个取决于您的用例,但总的来说,我更喜欢在编辑器中连接而不是使用 Find 函数(更少的代码,更少的麻烦)。在任何情况下,您的 OtherGameObject 都应该是这样的:

class OtherGameObject : MonoBehaviour {

    public s_ReadNeuro readNeuroInstance;


    void Update() {
        var attention = readNeuroInstance.attention;

        // do something with it.
    }

}

然后在编辑器中,创建一个新游戏对象,将 OtherGameObject 行为附加到它,然后将带有 s_ReadNeuro 脚本的 GameObject 实例拖到 OtherGameObject 检查器中的“Read Neuro Instance”字段。

如果要使用find方法,扩展OtherGameObject的脚本如下:

class OtherGameObject : MonoBehaviour {

    private s_ReadNeuro readNeuroInstance;


    void Start() {
          readNeuroInstance = GameObject.FindObjectOfType(typeof(s_ReadNeuro));
    }

    void Update() {
        var attention = readNeuroInstance.attention;

        // do something with it.
    }

}

在这种情况下,您不需要在编辑器中连接对象。请务必在 Start 或 Awake 中调用 Find 函数,因为它并不是一个廉价的调用函数。

【讨论】:

  • 非常感谢,这个理解的很清楚,对我有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多