I am making a FPS game, in which I have a trigger and a key (simple cube). When I throw the cube on the trigger, the door to the next level will open.
The problem is my weapon has no Collider or Rigid Body, when it enters the trigger a null reference exception is thrown by Unity.
My script tries to look for a collider in a game object which has no collider. How I can fix this ?
Can I ignore the weapon for trigger enter or I have to add a Rigid Body to my weapon
Heres my script which is attached to the trigger.
using System.Collections;
using UnityEngine;
public class DoorKeyTrigger : MonoBehaviour
{
private Rigidbody rb;
private bool alreadyOpened;
[SerializeField] private string notGrabableTag = "NotGrabable";
[SerializeField] private GameObject connectedDoor;
[SerializeField] private float doorOpenDelay;
[SerializeField] private float keySpinDuration;
private float keySmoothTime;
[SerializeField] private GameObject glowObject;
[SerializeField] private Material greenGlow;
[SerializeField] private Transform holdPoint;
private void Update()
{
if (alreadyOpened)
{
keySmoothTime = Time.deltaTime * keySpinDuration;
rb.transform.Rotate(Vector3.up * keySmoothTime);
}
}
private IEnumerator OnTriggerEnter(Collider other)
{
if (!other.transform.parent.CompareTag("Key") || alreadyOpened) yield break;
rb = other.gameObject.GetComponentInParent<Rigidbody>();
rb.tag = notGrabableTag;
/*float childCount = rb.transform.childCount;
for (int i = 0; i < childCount; i++)
{
rb.transform.GetChild(i).tag = notGrabableTag;
}
*/
rb.useGravity = false;
rb.isKinematic = true;
rb.MovePosition(holdPoint.position);
rb.MoveRotation(Quaternion.identity);
glowObject.GetComponent<MeshRenderer>().material = greenGlow;
alreadyOpened = true;
yield return new WaitForSeconds(doorOpenDelay);
connectedDoor.GetComponent<Door>().OpenDoor();
}
}