I solved the issue.
(C#) Invoke giving null reference exception, crashing unity
I have looked through many answers on this and other forums, but none seem to match my situation.
My original code was a fair bit more complex, so I commented out most of it (which still causes the error) to just:
public void Test() {
print("Test complete");
}
public void fire() {
print("Just before Invoke");
Invoke("Test", 1);
}
which is called from another script:
void Update() {
//if (Input.GetMouseButtonDown(0) && weaponsCarried[currentWeapon].readyToFire) {
if (Input.GetMouseButtonDown(0)) {
print("fire");
weaponsCarried[currentWeapon].fire();
}
}
The Invoke causes a null reference exception, which then causes unity to not respond and crash when I end the game (but I can still continue playing the game despite the error). The exact error is (line 55 is the Invoke):
NullReferenceException
Weapon.fire () (at Assets/Scripts/Weapons.cs:55)
The code works perfectly without the Invoke statement. All print statements except that in Test() do show up.
Is this not the exact way that Invoke is supposed to be used? I am lost as to why this is not working!?
Any help would be greatly appreciated! Thanks!
I solved the issue. Since the Invoke call was made within a class that had been instantiated, references to $$anonymous$$onoBehaviour do not work. It appears that $$anonymous$$onoBehaviour cannot be copied into the new class created, and so exists only in a class created by attaching to a gameObject as a component.
$$anonymous$$y fix is to call a function that is within a script attached to a gameObject, which starts another function in a coroutine and yields until the proper time, which then calls the required function back in the instantiated class. I had to use StartCoroutine and yield to allow me to pass the references to what had to be invoked after the time elapsed, as Invoke does not take parameters, and so the callback cannot be dynamically modified.
Follow this Question
Related Questions
Null Reference Exception on Sprite Renderer 0 Answers
Faulty NullReferenceException? 2 Answers
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers
Having a issue with a NullReferenceException 1 Answer
Using TextMeshProUGUI variable in a static function is returning a NullReferenceException 0 Answers