Hello Unity community,
I’m currently facing some difficulties with my door opening script. The script worked perfectly until I tried using it in a new room setup. Initially, the door used to teleport slightly, but after reimporting the door asset, the script stopped functioning altogether. When I try to run the game, the console displays an error message stating “object at index 0 is null.”
Problem:
-
Teleportation: Previously, the door would teleport a bit when opening, which was not the intended behavior. I would like the door to open smoothly without any teleportation.
-
Null Object Error: After reimporting the door asset into a new room, the door opening script no longer works. The console shows an error message mentioning “object at index 0 is null,” but I’m unsure why this error occurs.
Code:
using UnityEngine;
public class DoorScript : MonoBehaviour
{
public Transform PlayerCamera;
[Header("MaxDistance you can open or close the door.")]
public float MaxDistance = 5;
private bool opened = false;
private Animator anim;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Pressed();
}
}
void Pressed()
{
Debug.Log("1");
RaycastHit doorhit;
if (Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out doorhit, MaxDistance))
{
Debug.Log("2");
if (doorhit.transform.tag == "Door")
{
Debug.Log("3");
anim = doorhit.transform.GetComponent<Animator>();
opened = !opened;
anim.SetBool("Opened", !opened);
}
}
}
}
I kindly request your assistance in identifying the reasons behind the teleportation issue and the null object error in my door opening script. Any insights or suggestions you can provide to help resolve these problems would be greatly appreciated.
Thank you in advance for your support and expertise!
Best regards