Reputation: 61
So I have a simple local multiplayer game using the new input system. There's the game scene and the results scene. Once the game ends, the results scene is loaded and you can press "start" to restart the game (load the game scene again).
The problem is, after I reload the game scene and then trigger an InputAction (seems to be only on context.started):
MissingReferenceException while executing 'PlayerInput.onActionTriggered' callbacks
MissingReferenceException: The object of type 'Rigidbody2D' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
The weird thing is, none of these supposedly missing references are actually missing. The players still move using the "missing" rigidbody and etc.
I apologize if I don't explain well. I'm new to Unity and quite lost. I'm happy to share screenshots or snippits of my code I honestly just don't know where to look for this.
Upvotes: 0
Views: 3391
Reputation: 56
Term
This is a common problem for developers using Unity. This is a problem that occurs so often that Unity Techonology has already given it a term to explain it.
'Fake Null'
unity blog link https://blog.unity.com/technology/custom-operator-should-we-keep-it
In short, this happens because Unity's Object is a wrapper class that indicate pointer.
Code of Conduct
You can understand the details by reading the article on the Unity blog.
Unity developers need to be careful when using C#'s nullable syntax. (?, ??...etc)
Example Code
public class MyClass : Monobehaviour
{
[SerializeField] private Rigidbody _rigidbody;
private void DoSomething()
{
// This can cause Runtime error especially when GameObject that has
// Rigidbody already been Destroyed.
_rigidbody?.CallSomeMethod();
// This is Defensive Code preventing Runtime error
if (_rigidbody != null)
{
_rigidbody.CallSomeMethod();
}
}
}
Upvotes: 0