Search Unity

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

Discussion in 'Scripting' started by danybr, Sep 3, 2014.

  1. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    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)

    Code (csharp):
    1.  
    2. public class DestroyerScript : MonoBehaviour {
    3.  
    4.     void OnTriggerEnter2D(Collider2D other)
    5.     {
    6.         if(other.tag == "Player")
    7.         { Debug.Break ();
    8.             return;
    9.  
    10.         }
    11.  
    12.         if(other.gameObject.transform.parent)
    13.         {
    14.             Destroy (other.gameObject.transform.parent.gameObject);
    15.         }
    16.  
    17.         else
    18.         {
    19.             Destroy ( other.gameObject);
    20.         }
    21.     }
    22. }
    23.  
    and my SpawnScript for another quad:

    Code (csharp):
    1.  
    2.  
    3.  
    4. using UnityEngine;
    5. using System.Collections;
    6.  
    7. public class SpawnScript : MonoBehaviour {
    8.     public GameObject[] obj;
    9.     public float spawnMin = 1f;
    10.     public float spawnMax = 3f;
    11.     public Vector3 pos = new Vector3(26.10f,1.5f,10f);
    12.     public float size = 1.0f;
    13.     private Vector3 dir = Vector3.right;
    14.     public float speed = 2.0f;
    15.     void Start () {
    16.         StartCoroutine(Spawn());
    17.     }
    18.  
    19.     IEnumerator Spostamento(GameObject clone){
    20.         for(int i=0;i<300;i++){
    21.             clone.transform.position += Vector3.left * Time.deltaTime * speed;
    22.             yield return new WaitForSeconds (0.01f);
    23.         }
    24.     }
    25.     IEnumerator Spawn() {
    26.         while (true) {
    27.             GameObject clone;
    28.             clone = Instantiate (obj [Random.Range (0, obj.Length)], pos, Quaternion.identity) as GameObject;
    29.             StartCoroutine(Spostamento (clone));
    30.             yield return new WaitForSeconds(Random.Range (spawnMin, spawnMax));
    31.            
    32.         }
    33.     }
    34. }
    35.  
    if you have suggestions to improve the code, you make me happy :D
     
  2. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    Nobody help me??
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    What line is the error happening on?
     
  4. toreau

    toreau

    Joined:
    Feb 8, 2014
    Posts:
    204
    Maybe you should tell us what the problem is, where it is, and what your script is trying to do?
     
  5. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    No line.. The console not open the line error of script.
    This is in the console:
    Code (csharp):
    1.  
    2. MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
    3. Your script should either check if it is null or you should not destroy the object.
    4. 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)
     
    Last edited: Sep 5, 2014
  6. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Try adding this into your for loop (around the existing code, inside the loop):
    Code (csharp):
    1.  
    2. if (clone != null) {
    3. ...
    4. }
    5.  
    I suspect that the GameObject is being destroyed while Spostamento() is in the middle of running.
     
  7. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    Yooo man!! It work.. my forgetfulness. I love you!! :D

    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?
     
  8. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    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).
     
  9. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    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!!!
     
  10. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    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..
     
  11. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Never used TreeSpawner, so I can't help you on that one.
     
  12. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    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!
     
  13. danybr

    danybr

    Joined:
    Aug 28, 2014
    Posts:
    16
    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!
     
  14. Nabil_fx

    Nabil_fx

    Joined:
    Nov 9, 2013
    Posts:
    124
    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.
    Code (CSharp):
    1. /*==============================================================================
    2. * Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
    3. * ==============================================================================*/
    4.  
    5. using UnityEngine;
    6. using System.Collections;
    7. using Vuforia;
    8.  
    9. /// <summary>
    10. /// Demonstrates how to play the video on texture and full-screen mode.
    11. /// Single tapping on texture will play the video on texture (if the 'Play FullScreen' Mode in the UIMenu is turned off)
    12. /// or play full screen (if the option is enabled in the UIMenu)
    13. /// At any time during the video playback, it can be brought to full-screen by enabling the options from the UIMenu.
    14. /// </summary>
    15. public class PlayVideo : MonoBehaviour
    16. {
    17.  
    18.     private bool mVideoIsPlaying;
    19.     private VideoPlaybackBehaviour currentVideo;
    20.  
    21.     #region UNITY_MONOBEHAVIOUR_METHODS
    22.  
    23.     void Start()
    24.     {
    25.         InputController.SingleTapped += HandleSingleTap;
    26.         InputController.DoubleTapped += HandleDoubleTap;
    27.     }
    28.  
    29.     void OnApplicationPause(bool tf)
    30.     {
    31.         //When the video finishes playing on fullscreen mode, Unity application unpauses and that's when we need to switch to potrait
    32.         //in order to display the UI menu options properly
    33. #if UNITY_ANDROID
    34.         if(!tf) {
    35.             Screen.orientation = ScreenOrientation.Portrait;
    36.         }
    37. #endif
    38.     }
    39.  
    40.     #endregion UNITY_MONOBEHAVIOUR_METHODS
    41.  
    42.     #region PRIVATE_METHODS
    43.  
    44.     /// <summary>
    45.     /// 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
    46.     /// because the UI menu supports only potrait for now.
    47.     /// </summary>
    48.     private void HandleDoubleTap()
    49.     {
    50.         if (Screen.orientation != ScreenOrientation.Portrait)
    51.         {
    52.             Screen.orientation = ScreenOrientation.Portrait;
    53.         }
    54.     }
    55.     /// <summary>
    56.     /// Handle single tap event
    57.     /// </summary>
    58.     private void HandleSingleTap()
    59.     {
    60.  
    61.         if (VuforiaRuntimeUtilities.IsPlayMode())
    62.         {
    63.             if (PickVideo(Input.mousePosition) != null)
    64.                 Debug.LogWarning("Playing videos is currently not supported in Play Mode.");
    65.         }
    66.  
    67.         // Find out which video was tapped, if any
    68.         currentVideo = PickVideo(Input.mousePosition);
    69.  
    70.         if (currentVideo != null)
    71.         {
    72.             if (IsFullScreenModeEnabled())
    73.             {
    74.                 if (currentVideo.VideoPlayer.IsPlayableFullscreen())
    75.                 {
    76.                     //On Android, we use Unity's built in player, so Unity application pauses before going to fullscreen.
    77.                     //So we have to handle the orientation from within Unity.
    78. #if UNITY_ANDROID
    79.                     Screen.orientation = ScreenOrientation.LandscapeLeft;
    80. #endif
    81.                     // Pause the video if it is currently playing
    82.                     currentVideo.VideoPlayer.Pause();
    83.  
    84.                     // Seek the video to the beginning();
    85.                     currentVideo.VideoPlayer.SeekTo(0.0f);
    86.  
    87.                     // Display the busy icon
    88.                     currentVideo.ShowBusyIcon();
    89.  
    90.                     // Play the video full screen
    91.                     StartCoroutine( PlayFullscreenVideoAtEndOfFrame(currentVideo) );
    92.  
    93.                     UpdateFlashSettingsInUIView();
    94.                 }
    95.             }
    96.             else
    97.             {
    98.                 if (currentVideo.VideoPlayer.IsPlayableOnTexture())
    99.                 {
    100.                     // This video is playable on a texture, toggle playing/paused
    101.  
    102.                     VideoPlayerHelper.MediaState state = currentVideo.VideoPlayer.GetStatus();
    103.                     if (state == VideoPlayerHelper.MediaState.PAUSED ||
    104.                         state == VideoPlayerHelper.MediaState.READY ||
    105.                         state == VideoPlayerHelper.MediaState.STOPPED)
    106.                     {
    107.                         // Pause other videos before playing this one
    108.                         PauseOtherVideos(currentVideo);
    109.  
    110.                         // Play this video on texture where it left off
    111.                         currentVideo.VideoPlayer.Play(false, currentVideo.VideoPlayer.GetCurrentPosition());
    112.                     }
    113.                     else if (state == VideoPlayerHelper.MediaState.REACHED_END)
    114.                     {
    115.                         // Pause other videos before playing this one
    116.                         PauseOtherVideos(currentVideo);
    117.  
    118.                         // Play this video from the beginning
    119.                         currentVideo.VideoPlayer.Play(false, 0);
    120.                     }
    121.                     else if (state == VideoPlayerHelper.MediaState.PLAYING)
    122.                     {
    123.                         // Video is already playing, pause it
    124.                         currentVideo.VideoPlayer.Pause();
    125.                     }
    126.                 }
    127.                 else
    128.                 {
    129.                     // Display the busy icon
    130.                     currentVideo.ShowBusyIcon();
    131.  
    132.                     // This video cannot be played on a texture, play it full screen
    133.                     StartCoroutine( PlayFullscreenVideoAtEndOfFrame(currentVideo) );
    134.                 }
    135.             }
    136.         }
    137.     }
    138.  
    139.     public static IEnumerator PlayFullscreenVideoAtEndOfFrame(VideoPlaybackBehaviour video)
    140.     {
    141.         Screen.orientation = ScreenOrientation.AutoRotation;
    142.         Screen.autorotateToPortrait = true;
    143.         Screen.autorotateToPortraitUpsideDown = true;
    144.         Screen.autorotateToLandscapeLeft = true;
    145.         Screen.autorotateToLandscapeRight = true;
    146.  
    147.         yield return new WaitForEndOfFrame ();
    148.  
    149.         // we wait a bit to allow the ScreenOrientation.AutoRotation to become effective
    150.         yield return new WaitForSeconds (0.3f);
    151.      
    152.         video.VideoPlayer.Play(true, 0);
    153.     }
    154.  
    155.     //Flash turns off automatically on fullscreen videoplayback mode, so we need to update the UI accordingly
    156.     private void UpdateFlashSettingsInUIView()
    157.     {
    158.         VideoPlaybackUIEventHandler handler = GameObject.FindObjectOfType(typeof(VideoPlaybackUIEventHandler)) as VideoPlaybackUIEventHandler;
    159.         if (handler != null)
    160.         {
    161.             // add code as needed if you have set the flash on
    162.         }
    163.     }
    164.  
    165.     /// <summary>
    166.     /// Checks to see if the 'Play FullScreen' Mode is enabled/disabled in the UI Menu
    167.     /// </summary>
    168.     /// <returns></returns>
    169.     private bool IsFullScreenModeEnabled()
    170.     {
    171.         VideoPlaybackUIEventHandler handler = FindObjectOfType(typeof(VideoPlaybackUIEventHandler)) as VideoPlaybackUIEventHandler;
    172.         if (handler != null)
    173.         {
    174.             return handler.mFullScreenMode;
    175.         }
    176.  
    177.         return false;
    178.     }
    179.  
    180.     /// <summary>
    181.     /// Find the video object under the screen point
    182.     /// </summary>
    183.     private VideoPlaybackBehaviour PickVideo(Vector3 screenPoint)
    184.     {
    185.         VideoPlaybackBehaviour[] videos = (VideoPlaybackBehaviour[])
    186.                 FindObjectsOfType(typeof(VideoPlaybackBehaviour));
    187.  
    188.         GameObject go = VuforiaManager.Instance.ARCameraTransform.gameObject;
    189.         Camera[] cam = go.GetComponentsInChildren<Camera> ();
    190.         Ray ray = cam[0].ScreenPointToRay(screenPoint);
    191.  
    192.         RaycastHit hit = new RaycastHit();
    193.  
    194.         foreach (VideoPlaybackBehaviour video in videos)
    195.         {
    196.             if (video.GetComponent<Collider>().Raycast(ray, out hit, 10000))
    197.             {
    198.                 return video;
    199.             }
    200.         }
    201.  
    202.         return null;
    203.     }
    204.  
    205.     /// <summary>
    206.     /// Pause all videos except this one
    207.     /// </summary>
    208.     private void PauseOtherVideos(VideoPlaybackBehaviour currentVideo)
    209.     {
    210.         VideoPlaybackBehaviour[] videos = (VideoPlaybackBehaviour[])
    211.                 FindObjectsOfType(typeof(VideoPlaybackBehaviour));
    212.  
    213.         foreach (VideoPlaybackBehaviour video in videos)
    214.         {
    215.             if (video != currentVideo)
    216.             {
    217.                 if (video.CurrentState == VideoPlayerHelper.MediaState.PLAYING)
    218.                 {
    219.                     video.VideoPlayer.Pause();
    220.                 }
    221.             }
    222.         }
    223.     }
    224.  
    225.  
    226.     #endregion // PRIVATE_METHODS
    227.  
    228. }
    229.  
    please some help.
     
  15. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    @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
     
  16. liboyan

    liboyan

    Joined:
    Sep 21, 2015
    Posts:
    5
    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.
     
  17. willyumoliver_unity

    willyumoliver_unity

    Joined:
    Nov 2, 2020
    Posts:
    4
    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.
     
  18. alvinkhor

    alvinkhor

    Joined:
    Apr 22, 2021
    Posts:
    2
    Add this code in which line of coding yah????
     
  19. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    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/ass...3-syntax-error-expected.1039702/#post-6730855

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

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
  20. alvinkhor

    alvinkhor

    Joined:
    Apr 22, 2021
    Posts:
    2
    ??I'm just asking the solution of that question