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

Hi guys.
My problem is this… I read variously post but i don’t fix it.

My script are:

DestroyerScript for quad (thanks Mike Geig)

public class DestroyerScript : MonoBehaviour {

    void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Player")
        { Debug.Break ();
            return;

        }

        if(other.gameObject.transform.parent)
        {
            Destroy (other.gameObject.transform.parent.gameObject);
        }

        else
        {
            Destroy ( other.gameObject);
        }
    }
}

and my SpawnScript for another quad:

using UnityEngine;
using System.Collections;

public class SpawnScript : MonoBehaviour {
    public GameObject[] obj;
    public float spawnMin = 1f;
    public float spawnMax = 3f;
    public Vector3 pos = new Vector3(26.10f,1.5f,10f);
    public float size = 1.0f;
    private Vector3 dir = Vector3.right;
    public float speed = 2.0f;
    void Start () {
        StartCoroutine(Spawn());
    }

    IEnumerator Spostamento(GameObject clone){
        for(int i=0;i<300;i++){
            clone.transform.position += Vector3.left * Time.deltaTime * speed;
            yield return new WaitForSeconds (0.01f);
        }
    }
    IEnumerator Spawn() {
        while (true) {
            GameObject clone;
            clone = Instantiate (obj [Random.Range (0, obj.Length)], pos, Quaternion.identity) as GameObject;
            StartCoroutine(Spostamento (clone));
            yield return new WaitForSeconds(Random.Range (spawnMin, spawnMax));
           
        }
    }
}

if you have suggestions to improve the code, you make me happy :smile:

Nobody help me??

What line is the error happening on?

Maybe you should tell us what the problem is, where it is, and what your script is trying to do?

No line… The console not open the line error of script.
This is in the console:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
SpawnScript+<Spostamento>c__Iterator1.MoveNext () (at C:/Users/Dany/Desktop/Project/Assets/Scripts/SpawnScript.cs:24)

EDIT: Line 24 of SpawnScript.cs?
I have a Quad,the spawner,wich i generate the obstacles… this run from right to left.
On the Left,next the scene,there is a quad destroyer,this destroy my GameObject obstacles.
I think,the problem is : Destroyer catch the obstacle,destory it,but the spawnscript try to access it (to move to right)

Try adding this into your for loop (around the existing code, inside the loop):

if (clone != null) {
...
}

I suspect that the GameObject is being destroyed while Spostamento() is in the middle of running.

Yooo man!! It work… my forgetfulness. I love you!! :smile:

Another problem:
I have create another two quad with spawnscript for generate the trees and clouds for the background.
I add at it a polygon collider 2D,with “is trigger” enabled.
When i simulate the game,i have a loss of frame,it drops by 30-40 fps!!!
How can i solve it? Is too much stress for Gpu?

P.S. How can i stop the simulation,when it looping and freezing?

Colliders don’t affect the GPU at all.

What’s happening here is that, when you add a collider with no Rigidbody to an object, Unity treats that object as a static collider. It does some optimizations to make physics run better. However, those optimizations take time to do, and anytime the static colliders of a level change, it has to re-do those optimizations. You’re moving them every frame, so it has to redo those calculations every frame (I think it might redo those optimizations every time you move the objects - if you have several being moved, that’s several times per frame it recalculates.)

Short answer: if you have a collider that is going to move (especially if it moves every frame), ALWAYS add a Rigidbody (set it to isKinematic).

I added RigidBody2D and set isKinematic at all background’s item and at obstacles… but problem remains.
Sometimes the fps drops at 1.8 or less!!!

My problem is on the TreeSpawner… if i disable it,game run on 68-69 FPS always!
maybe,i have to use the FixedUpdate() function… I don’t know…

Never used TreeSpawner, so I can’t help you on that one.

I’m sorry,I’ll explain:
treeSpawner is my quad with spawnerScript (the same of the obstacle generator script,the spawnerScript on the first post).
I use it for generate trees (these are a “part of background”).
When the quad generate the prefab tree,game loss frame!

I solved it… The problem is in the polygon collider and complessity of the image.
I replaced it with box collider. It works too fine!

i have the same problem,
MissingReferenceException: The object of type ‘PlayVideo’ has been destroyed but you are still trying to access it.

here my script.

/*==============================================================================
* Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
* ==============================================================================*/

using UnityEngine;
using System.Collections;
using Vuforia;

/// <summary>
/// Demonstrates how to play the video on texture and full-screen mode.
/// Single tapping on texture will play the video on texture (if the 'Play FullScreen' Mode in the UIMenu is turned off)
/// or play full screen (if the option is enabled in the UIMenu)
/// At any time during the video playback, it can be brought to full-screen by enabling the options from the UIMenu.
/// </summary>
public class PlayVideo : MonoBehaviour
{

    private bool mVideoIsPlaying;
    private VideoPlaybackBehaviour currentVideo;

    #region UNITY_MONOBEHAVIOUR_METHODS

    void Start()
    {
        InputController.SingleTapped += HandleSingleTap;
        InputController.DoubleTapped += HandleDoubleTap;
    }

    void OnApplicationPause(bool tf)
    {
        //When the video finishes playing on fullscreen mode, Unity application unpauses and that's when we need to switch to potrait
        //in order to display the UI menu options properly
#if UNITY_ANDROID
        if(!tf) {
            Screen.orientation = ScreenOrientation.Portrait;
        }
#endif
    }

    #endregion UNITY_MONOBEHAVIOUR_METHODS

    #region PRIVATE_METHODS

    /// <summary>
    /// Just in case the device is in any other mode at the time the user double taps to bring up the UI menu, we force it to go to potrait
    /// because the UI menu supports only potrait for now.
    /// </summary>
    private void HandleDoubleTap()
    {
        if (Screen.orientation != ScreenOrientation.Portrait)
        {
            Screen.orientation = ScreenOrientation.Portrait;
        }
    }
    /// <summary>
    /// Handle single tap event
    /// </summary>
    private void HandleSingleTap()
    {

        if (VuforiaRuntimeUtilities.IsPlayMode())
        {
            if (PickVideo(Input.mousePosition) != null)
                Debug.LogWarning("Playing videos is currently not supported in Play Mode.");
        }

        // Find out which video was tapped, if any
        currentVideo = PickVideo(Input.mousePosition);

        if (currentVideo != null)
        {
            if (IsFullScreenModeEnabled())
            {
                if (currentVideo.VideoPlayer.IsPlayableFullscreen())
                {
                    //On Android, we use Unity's built in player, so Unity application pauses before going to fullscreen.
                    //So we have to handle the orientation from within Unity.
#if UNITY_ANDROID
                    Screen.orientation = ScreenOrientation.LandscapeLeft;
#endif
                    // Pause the video if it is currently playing
                    currentVideo.VideoPlayer.Pause();

                    // Seek the video to the beginning();
                    currentVideo.VideoPlayer.SeekTo(0.0f);

                    // Display the busy icon
                    currentVideo.ShowBusyIcon();

                    // Play the video full screen
                    StartCoroutine( PlayFullscreenVideoAtEndOfFrame(currentVideo) );

                    UpdateFlashSettingsInUIView();
                }
            }
            else
            {
                if (currentVideo.VideoPlayer.IsPlayableOnTexture())
                {
                    // This video is playable on a texture, toggle playing/paused

                    VideoPlayerHelper.MediaState state = currentVideo.VideoPlayer.GetStatus();
                    if (state == VideoPlayerHelper.MediaState.PAUSED ||
                        state == VideoPlayerHelper.MediaState.READY ||
                        state == VideoPlayerHelper.MediaState.STOPPED)
                    {
                        // Pause other videos before playing this one
                        PauseOtherVideos(currentVideo);

                        // Play this video on texture where it left off
                        currentVideo.VideoPlayer.Play(false, currentVideo.VideoPlayer.GetCurrentPosition());
                    }
                    else if (state == VideoPlayerHelper.MediaState.REACHED_END)
                    {
                        // Pause other videos before playing this one
                        PauseOtherVideos(currentVideo);

                        // Play this video from the beginning
                        currentVideo.VideoPlayer.Play(false, 0);
                    }
                    else if (state == VideoPlayerHelper.MediaState.PLAYING)
                    {
                        // Video is already playing, pause it
                        currentVideo.VideoPlayer.Pause();
                    }
                }
                else
                {
                    // Display the busy icon
                    currentVideo.ShowBusyIcon();

                    // This video cannot be played on a texture, play it full screen
                    StartCoroutine( PlayFullscreenVideoAtEndOfFrame(currentVideo) );
                }
            }
        }
    }
  
    public static IEnumerator PlayFullscreenVideoAtEndOfFrame(VideoPlaybackBehaviour video)
    {
        Screen.orientation = ScreenOrientation.AutoRotation;
        Screen.autorotateToPortrait = true;
        Screen.autorotateToPortraitUpsideDown = true;
        Screen.autorotateToLandscapeLeft = true;
        Screen.autorotateToLandscapeRight = true;

        yield return new WaitForEndOfFrame ();

        // we wait a bit to allow the ScreenOrientation.AutoRotation to become effective
        yield return new WaitForSeconds (0.3f);
      
        video.VideoPlayer.Play(true, 0);
    }

    //Flash turns off automatically on fullscreen videoplayback mode, so we need to update the UI accordingly
    private void UpdateFlashSettingsInUIView()
    {
        VideoPlaybackUIEventHandler handler = GameObject.FindObjectOfType(typeof(VideoPlaybackUIEventHandler)) as VideoPlaybackUIEventHandler;
        if (handler != null)
        {
            // add code as needed if you have set the flash on
        }
    }

    /// <summary>
    /// Checks to see if the 'Play FullScreen' Mode is enabled/disabled in the UI Menu
    /// </summary>
    /// <returns></returns>
    private bool IsFullScreenModeEnabled()
    {
        VideoPlaybackUIEventHandler handler = FindObjectOfType(typeof(VideoPlaybackUIEventHandler)) as VideoPlaybackUIEventHandler;
        if (handler != null)
        {
            return handler.mFullScreenMode;
        }

        return false;
    }

    /// <summary>
    /// Find the video object under the screen point
    /// </summary>
    private VideoPlaybackBehaviour PickVideo(Vector3 screenPoint)
    {
        VideoPlaybackBehaviour[] videos = (VideoPlaybackBehaviour[])
                FindObjectsOfType(typeof(VideoPlaybackBehaviour));

        GameObject go = VuforiaManager.Instance.ARCameraTransform.gameObject;
        Camera[] cam = go.GetComponentsInChildren<Camera> ();
        Ray ray = cam[0].ScreenPointToRay(screenPoint);

        RaycastHit hit = new RaycastHit();

        foreach (VideoPlaybackBehaviour video in videos)
        {
            if (video.GetComponent<Collider>().Raycast(ray, out hit, 10000))
            {
                return video;
            }
        }

        return null;
    }

    /// <summary>
    /// Pause all videos except this one
    /// </summary>
    private void PauseOtherVideos(VideoPlaybackBehaviour currentVideo)
    {
        VideoPlaybackBehaviour[] videos = (VideoPlaybackBehaviour[])
                FindObjectsOfType(typeof(VideoPlaybackBehaviour));

        foreach (VideoPlaybackBehaviour video in videos)
        {
            if (video != currentVideo)
            {
                if (video.CurrentState == VideoPlayerHelper.MediaState.PLAYING)
                {
                    video.VideoPlayer.Pause();
                }
            }
        }
    }


    #endregion // PRIVATE_METHODS

}

please some help.

@Nabil_fx , I’m assuming you posted the question here by just searching for the error message you got and finding a forum post that matches it; however this is a very different problem that just happens to result in the same (very common) error message. I recommend making a new thread instead, so as not to confuse the discussion

you set up the parent, then you distory the gameobject so , you make mistakes;
you can use word “try"and “catch’ in “try” you can add a gameobject, in” catch” you can set up the parent.

I have a similar problem, however if the problem is what ya’ll figured it was, I don;t know how to modify it to add it to my code.

Add this code in which line of coding yah???

Please don’t hijack 7-year-old threads with cryptic unrelated questions. It’s against forum rules.

Instead, start your own post… it’s FREE!

When you post, remember that nobody here can read your mind so you need to be VERY explicit in your question.

Here is how to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

How to understand compiler and other errors and even fix them yourself:

https://forum.unity.com/threads/assets-mouselook-cs-29-62-error-cs1003-syntax-error-expected.1039702/#post-6730855

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

??I’m just asking the solution of that question