2014-03-02 67 views
1

我已经成功连接的蓝牙设备来统一和试图用在数据读出与该控制其它游戏对象 作为参考 http://answers.unity3d.com/questions/16484/how-to-import-neurosky-mindset-data-into-unity.html在unity3D中,如何从其他gameobject获取变量?

我附着在连接脚本到一个空的游戏对象,它可以读取在一些变量。 我将所有的变量是公共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); 

}} 
+0

不知道我明白你想要什么,但你有没有尝试使变量静态? – dudledok

回答

2

连接脚本基本上有这样的两种方式。在编辑器中将您的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脚本的游戏对象的实例OtherGameObject的检查器中的“读取实例”字段。

如果你要使用的查找方法,延长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. 
    } 

} 

在这种情况下,你不需要连线在编辑器中的对象。一定要在开始或唤醒中调用查找功能,因为它不是一个便宜的函数。

+0

非常感谢,这是非常明确的理解和帮助我 – wuwuwu3