Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unity The object of type 'GameObject' has been destroyed but you are still trying to access it

I have a problem that when i change scenes from the menu to the game and when i click i will get the error ‘The object of type ‘GameObject’ has been destroyed but you are still trying to access it.’ and this is happening while the menucontroller is not in the game scene, i have been working on this for the past few days to fix it but cant find how to do it. If anyone can help that would be great this kind of question has been asked alot but I cant find a solution for my problem.

We also have a similar script that has the same code except instead of sceneswitching its for interaction so when we try to interact with something we get the error

Thank you for your help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

menucontroller

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using API;

public class MenuController : MonoBehaviour
{
    [SerializeField] private InputActionReference shoot;
    [SerializeField] private InputActionReference shoot2;
    public GameObject sendObject;
    public GameObject sendObject2;
    public float range = 1000;




    void Start()
    {
        shoot.action.performed += Shoot;

       
    }

    async void Shoot(InputAction.CallbackContext obj)
    {
        RaycastHit hit;

        if (Physics.Raycast(sendObject.transform.position, sendObject.transform.forward, out hit, range))
        {
            SceneManager.LoadScene("SampleScene");
        }
    }
}    

>Solution :

The error message sounds quite self-explanatory.

You are trying to access an object that already was destroyed.

Since you load a new scene

SceneManager.LoadScene("SampleScene");

the current scene and its objects are unloaded / destroyed.

Whenever you deal with events

void Start()
{
    shoot.action.performed += Shoot;
}

make sure to also remove the callback as soon as not needed/valid anymore

private void OnDestroy()
{
    shoot.action.performed -= Shoot;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading