Unity scripts need access to components they will be using, my solution here guarantees that a script will have a valid reference to a component it needs, but is this solution overkill, or hard to discern intention from?
Note: null coalescence operators would be cleaner but cannot be used for unity objects or components for terrible reasons.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))] // disallows deletion of component from editor
public class CubeControll : MonoBehaviour
{
[SerializeField, HideInInspector]
private Rigidbody rigidbody;
private void OnValidate()
{
rigidbody = GetComponent<Rigidbody>() != null ? // if has component attached
GetComponent<Rigidbody>() : // assign referance
gameObject.AddComponent<Rigidbody>(); // else add new component
}
// start, update etc
}
This is a common situation, are there any general best practices to doing this?
rigidbody? so this way you can make itreadonly. \$\endgroup\$?:operator return aRigidbody... i'm not really sure what you mean? \$\endgroup\$