Home > front end >  unity The object of type 'GameObject' has been destroyed but you are still trying to acces
unity The object of type 'GameObject' has been destroyed but you are still trying to acces

Time:11-18

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.

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");
        }
    }
}    

CodePudding user response:

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;
}
  • Related