0

I'm working on a project with Unity and I've to check if there are any hands in the scene before the Update function. I've written this short code

Hand hand;
HandModel handModel;
private static LeapProvider s_provider;

void Start()
{
    handModel = GetComponent<HandModel>();
    hand = handModel.GetLeapHand();
    if (hand == null) Debug.LogError("No leap_hand founded");
    s_provider = Object.FindObjectOfType<LeapServiceProvider>();
    if (s_provider == null) {
        s_provider = Object.FindObjectOfType<LeapProvider>();
        if (s_provider == null) {
            return;
        }
    }
}

but an error occurs when I press the Play button, refered to hand = handModel.GetLeapHand();: NullReferenceException: Object reference not set to an instance of an object. I know it's a noob problem but I can't get a solution

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • change to `hand = handModel?.GetLeapHand();`. Btw., you are never using `hand`. – Olivier Jacot-Descombes Feb 23 '21 at 15:44
  • @OlivierJacot-Descombes while this hides the exception it actually only makes the debugging life harder if later you wonder why nothing is moving e.g. ^^ I think the correct approach would be fixing the original cause of the exception instead ;) Oh besides that: the `?` operator doesn't work correctly with stuff inheriting from `UnityEngine.Object` – derHugo Feb 23 '21 at 15:46
  • Your `GetComponent` fails so `handModel` isn't set ... are you sure the component is attached to the **same** `GameObject` as this script? – derHugo Feb 23 '21 at 15:48
  • Well, it will not completely hide the problem, as it will log an error. – Olivier Jacot-Descombes Feb 23 '21 at 15:48
  • @OlivierJacot-Descombes yes but it would seem that only `GetLeapHand()` failed while the original cause is a completely different one, the component is not attached to the `GameObject` ;) Also as said the `?` might fail for `UnityEngine.Object` at least that was the case in the past due to their [Custom `==` opertaor](https://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it) for `null` – derHugo Feb 23 '21 at 15:51
  • @derHugo I'm still trying to figure it out what's wrong with this code. I saw on internet some similar codes, so I think the problem is where to put it in Unity. I've tried to attach it to the GameObject HandModels in my scene but it gives error as I press play. Right now it's attached to the CapsuleHands (L and R) and when I press Play the hand is shown for a frame, it's in the scene but then the error appers again immediately and the game stops. I actually don't know what to do – Lorenzo Bergamini Mar 06 '21 at 15:22

0 Answers0