It’s very strange, if I make some minute changes that doesn’t interfere with logic it sometimes works and sometimes doesn’t. I don’t understand. Obviously I don’t want to have this printing statement everyframe so want to get rid of it. Any ideas?
Sounds like a concurrency issue. I suggest to first clarify what exactly is causing the null reference exception (playerChar, GetComponent, getTriggers?). Then try to trace back where the null is coming from.
Usually, the error is quite trivial once you figure out where it is coming from.
I thought that you could be right about concurrency. I had an update() function inside of the C# script (AnimaConnect) that was inputting constantly altering ints into my triggerArray. Maybe the function getTriggers() was being called at the same time as the triggerArray was being loaded with ints.
void Update()
{
string[] words = recvStr.Split(' ');
for (int i = 1; i < 37; i++)
{
float element = float.Parse(words[i]);
floatArray[i-1] = element;
}
for (int n = 37; n < 43; n++)
{
int element = int.Parse(words[n]);
triggerArray[n - 37] = element;
}
}
public int[] getTriggers()
{
return triggerArray;
}
So, I got rid of the update function and replaced this whole function as getTriggers().
public int[] getTriggers()
{
string[] words = recvStr.Split(' ');
for (int i = 1; i < 37; i++)
{
float element = float.Parse(words[i]);
floatArray[i-1] = element;
}
for (int n = 37; n < 43; n++)
{
int element = int.Parse(words[n]);
triggerArray[n - 37] = element;
}
return triggerArray;
}
This getTriggers() function in the C# script (AnimaConnect) is called from the JS script’s update function (Both AnimaConnect and the JS script are attached to the same GameObject):
function Update ()
{
triggers = GetComponent(AnimaConnect).getTriggers();
}
The only change to the triggerArray occurs in the same function before it is returned so this rules out concurrency?
Sometimes it works, most of the time it generates a NullReferenceException. If I add several print statements before I return the triggerArray in the getTriggers() function of the c# script it works!?
Could someone please help me out as this is driving me crazy!
If you look at the null reference error in the console window, it will (usually) tell you the line number where the error occurred. What you have posted so far doesn’t make it clear where the null reference is. When you have a line like:-
…the error message will tell you which of the two lines is causing the problem.
Another thing I’ve seen happen often is that the console contains many repetitions of the same null reference error because the error happens in the Update function. However, if you scroll the console back up to the start, there is sometimes an initialisation error in the Start/Awake method that subsequently causes the others.
Doing things like this can help narrow down the cause of the error. You can always put the code back the way it was after discovering the error if you think it is neater or more efficient.