unity require component code example
Example 1: unity requirecomponent
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
Rigidbody rb; void Start()
{
rb = GetComponent<Rigidbody>();
} void FixedUpdate()
{
rb.AddForce(Vector3.up);
}
}
Example 2: require component unity
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
...
Example 3: unity get component
using UnityEngine;
public class TryGetComponentExample : MonoBehaviour
{
void Start()
{
if (TryGetComponent(out Rigidbody rigidFound))
{
rigidFound.enabled = false;
}
Rigidbody rigidFound = GetComponent<Rigidbody>();
if(rigidFound != null)
{
rigidFound.enabled = false;
}
}
}