C#错误访问非静态成员需要对象引用(unity和arduino之间的串行通信)

时间:2017-01-17 06:46:11

标签: unity3d arduino

存在错误“访问非静态成员需要对象引用。”

你知道如何解决这个问题吗? 我不想使用“静态”,因为Unity gui“button-Onclick”无法使用静态成员。

enter image description here

就像这个截图一样,如果我们在GUI上使用静态成员(画布 - 按钮 - 按钮单击),则不会列出该静态成员(“缺少------------”)< / p>

我的代码很震撼。

Sending.cs

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
public class Sending : MonoBehaviour{
    //public static SerialPort sp = new SerialPort("COM4",9600,Parity.
    public SerialPort sp = new SerialPort("----------);
    public string message2;
    float timePassed = 0.0f;
    //Use this for initialization
    void Start()
    {
        OpenConnection();
    }

    //Update is called once per frame
    void Update(){
        //timePassed+= Time.deltaTime;
        //if(timePassed)=0.2f){
        //print("BytesToRead" +sp.BytesToRead);
        message2 = sp.ReadLine ();
        print (message2);
        ///timePassed = 0.0f;
        //}
    }

    public void OpenConnection()
    {
        if(sp != null)
        {
            if (sp.IsOpen) {
                sp.Close ();
                print ("Closing port, because it was already open!");
            }  else {
                sp.Open ();//open the connection
                sp.ReadTimeout = 16;
                print ("Port Opened!");
                //message = "Port Opened";
            }
        }
        else 
        {
            if (sp.IsOpen)
            {
                print ("Port is already open");
            }
            else
            {
                print ("Port == null");
            }
        }
    }
    void OnApplicationQuit()
    {
        sp.Close();
    }
    public void sendStop(){
        sp.Write ("s");
    }
    public void sendForward(){
        sp.Write("f");
    }
    public void sendBack(){
        sp.Write("b");
    }
    public void sendRight(){
        sp.Write("r");
    }
    public void sendLeft(){
        sp.Write("l");
    }
}

另外,还有一些脚本。

CallForward.cs

using UnityEngine;
using System.Collections;
public class CallForward: MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    void OnMouseDown(){
        print ("Clicked");
        Sending.sendForward();
    }
}

enter image description here

1 个答案:

答案 0 :(得分:2)

您必须先获取发送脚本才能使用它。只有静态类才能在不首先启动它们的情况下使用。

GameObject.Find("GameObjectWithSendingScript").GetComponent<Sending>().sendForward();