Is it overkill to RequireComponent then check if GetComponent isnt Null in Awake?
Would it be redundant to check for Nulls in the Awake function() when using GetComponents if the script already has RequireComponent? Seems debatable but is it good or bad practice? Would there be a better way to check for nulls such as using Try and Catch?
Ex:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class test : MonoBehaviour {
private Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
if (rb == null)
{
Debug.Log("Rigidbody cannot be null");
}
}
Answer by LeeJBaxter · Feb 27, 2018 at 10:13 AM
I'm tempted to say this is overkill in this instance (it kinda defeats the point of using RequireComponent if you're going to test for null anyway). However, in some cases, it might not be...
I'm not sure if it is possible to do this with a component possessing the RequireComponent tag, but I'd imagine a null test would be a good idea if there's a possibility of the required component being removed from the object at runtime (I think Unity would somehow stop you from doing this, but I'm not completely sure).
I too think it is not really required to check for null. But I know a small bug which would recreate your situation. If you added a script to the GameObject, Afterwards you changed the script and added the RequireComponent. But didn't manually deleted this script from the GameObject and added again. Unity won't automatically add the component you specified in RequireComponent. It is nothing major but still RequireComponent isn't without fail.
Edit: "Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies automatically added."
Your answer
Follow this Question
Related Questions
NullReferenceException problems. 0 Answers
Pass a value between script or else by reference? 1 Answer
Object reference; sometimes works but sometimes doesn't??? 2 Answers
how do I add link script to gameobject that already exist with attached script 1 Answer
Struggling with Unity 5 GetComponent: Null reference 0 Answers