- Home /
NullReferenceException: Object reference not set to an instance of an object
I'm trying to move the cube with two potentiometers which will then send it values to the microchip on the Arduino Uno. The 2 values steers the cube horizontally and the other one changes speed. Below is the code that I have composed for this too happen. myDevice is referring to the port the Arduino is connected to.
public class PlayerController : MonoBehaviour {
wrmhl myDevice = new wrmhl(); // wrmhl is the bridge beetwen your computer and hardware.
[Tooltip("SerialPort of your device.")]
public string portName = "COM7";
[Tooltip("Baudrate")]
public int baudRate = 9600;
[Tooltip("Timeout")]
public int ReadTimeout = 20;
[Tooltip("QueueLenght")]
public int QueueLenght = 1;
public float v;
public float h;
void Start () {
myDevice.set (portName, baudRate, ReadTimeout, QueueLenght); // This method set the communication with the following vars;
// Serial Port, Baud Rates, Read Timeout and QueueLenght.
myDevice.connect (); // This method open the Serial communication with the vars previously given.
StartCoroutine(ReadDataFromSerialPort());
}
IEnumerator ReadDataFromSerialPort(){
while(true){//loop
string[] values = myDevice.readQueue().Split (',');// we split our string value by , because we write string as carspeed,cartotation in our ardunio codes
v = (float.Parse (values[0]));
h = (float.Parse (values[1]));
yield return new WaitForSeconds (.05f);//waiting seconds to read data. It should be same as ardunio code loop delay
}
}
// Update is called once per frame
void Update () {
//print (myDevice.readQueue () ); // myDevice.read() return the data coming from the device using thread.
// float h = Input.GetAxis ("Horizontal") * speed * Time.deltaTime;
// float v = Input.GetAxis ("Vertical") * speed * Time.deltaTime;
transform.Translate (0f, 0f, v);
GetComponent<Rigidbody> ().AddTorque (transform.up * h);
// transform.localEulerAngles = new Vector3 (0, h, 0);
}
void OnApplicationQuit() { // close the Thread and Serial Port
myDevice.close();
}
}
Everytime i run this code with unity, it gives me this error:
NullReferenceException: Object reference not set to an instance of an object PlayerController+c__Iterator0.MoveNext () (at Assets/PlayerController.cs:37) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17) UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator) PlayerController:Start() (at Assets/PlayerController.cs:31)
I am new to coding, so I'm not sure what to change or do with this error. Appreciate any help possible :)
With respect to the code sample above, (Assets/PlayerController.cs:37) is referring to line 30 and PlayerController:Start() (at Assets/PlayerController.cs:31) is referring to line 24. Hopefully that makes more sense :)
Answer by Reynarz · Apr 06, 2018 at 03:33 PM
Are you 100% sure that myDevice.ReadQueue() is returning a valid value? Because the method Split() tells you the opposite. :) You can try checking for null
var value = myDevice.ReadQueue();
if(value == null)
Debug.Log("is null");
Answer by unity_PGAfH3eoHXq0Vg · Apr 06, 2018 at 03:59 PM
But when I receive the data from Arduino, it is printed as (v,h) v = vertical movement/ speed h = horizontal movement / steering angle
Unity then has to read (v,h) so that's why I wrote in the method Split() to collect the two values individually.
When I run
var value = myDevice.ReadQueue();
if(value == null)
Debug.Log("is null");
the result is null but I think that's because it can't read "," in between the two values.
When I run var
value = myDevice.ReadQueue().Split(',');
if(value == null)
Debug.Log("is null");
Nothing comes up on the console
Of course not, because there you are obtaining the null error. at that point the code is broken.
ok now I put value = myDevice.ReadQueue(); if(value == null) Debug.Log("is null");
before string[] values = myDevice.readQueue().Split (','); and I ran it 3 times and I each time I got 1 error but they were all different.
Error 1 - IndexOutOfRangeException: Array index is out of range. PlayerController+c__Iterator0.$$anonymous$$oveNext () (at Assets/PlayerController.cs:44) UnityEngine.SetupCoroutine.Invoke$$anonymous$$oveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17) UnityEngine.$$anonymous$$onoBehaviour:StartCoroutine(IEnumerator) PlayerController:Start() (at Assets/PlayerController.cs:31)
Error 2 - FormatException: Invalid format. System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Double.cs:209) System.Single.Parse (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Single.cs:183) PlayerController+c__Iterator0.$$anonymous$$oveNext () (at Assets/PlayerController.cs:43) UnityEngine.SetupCoroutine.Invoke$$anonymous$$oveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17) UnityEngine.$$anonymous$$onoBehaviour:StartCoroutine(IEnumerator)
Error 3 - NullReferenceException: Object reference not set to an instance of an object PlayerController+c__Iterator0.$$anonymous$$oveNext () (at Assets/PlayerController.cs:41) UnityEngine.SetupCoroutine.Invoke$$anonymous$$oveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
When I take the Split() method off myDevice.readQueue(), I get this error - Assets/PlayerController.cs(41,31): error CS0029: Cannot implicitly convert type string' to string[]'
Answer by Alfredo78 · Jun 06, 2018 at 02:49 PM
I tried to use the wrmhl too, this only run well when i use the example, i can modify the text that is sendind but when i want to save it in a variable and use it always obtain null. Then i think that is your method which is generating the problem.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NullReferenceException in StartCoroutine 1 Answer
Misunderstanding Co-routines? 1 Answer