[Probably a Unity bug] Object gets destroyed on collision even tho I'm not using Destroy() method.

Hi, there I have decent knowlage of Unity and when my player collides with an object or when the game is over and I double click on the player in the hierarchy it gets destroyed. I have couple of scripts and I’m sure that I’m not using Destroy() method. I just can’t figure out how this can happen. If any of you know why this is happening and have solution please let me know. I tried to put player to Don’tDestroyOnLoad but it’s still happening. I also did find in files to check if there is a Destroy() method. I’m using Unity 2017.1

Did you do a search for DestroyImmediate as well?
Also, by “game is over” do you mean the Editor leaves Play Mode as well? Because if so, any objects created during Play Mode will not remain in the scene when you stop playing.

Also, what version of 2017.1 are you on? 2017.1.1p2 is the latest patch release for 2017.1

When you double click the player in the hierarchy it gets destroyed? Do you have an editor script running that’s doing something? That just sounds odd…

1 Like

Invertex: I’ve just did a search for DestroyImmediate as well and nothing came up. Editor keeps staying in the game mode and Player is in the Hierarchy before entering the play mode. Gameover is a function I wrote and it basically toggles the player’s sprite renderer controller ect. and I’m only pooling objects and that’s where I create object in the during the game. I’m not creating nor destroying the player. During Run time it gets Destroyed. I’m using 2017.1.0f3

Brathnann: I’m not using any editor scripts at all. I created this porject 2 days ago and I have 7 classes no plugings (exept sprites no code in there) and all of my classes are MonoBehaviour. I will try updating unity now maybe this will fix it.

Is there any way that unity can destroy something because of some reason on it’s on did any of you experienced that?

Never heard of something similar either, are you sure there’s really nothing that might destroy your object?

Without any more details, it’s difficult to guess and the usual answer will be “you’re probably destroying it somewhere” as this would otherwise be a really weird bug that noone has heard of.

That’s what I’m thinking. Below you can see two scripts of objects that are being collided and also the gamemanger where I check if player lost the game or not. In the image you can see the Toggle Events that I’m doing in the game manager.

public class PlayerController : MonoBehaviour {

void OnBecameInvisible()
    {
        GameManager.instance.GameOver();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        GameManager.instance.GameOver();
    }
}
public class OrbitController : MonoBehaviour {

#region PublicMembers
    public float Gravity;
    public float OuterAtmosphare;
    public float InnerAtmosphare;
    public bool isBlackHole;
    #endregion
#region PriviteMembers
    bool pointIsGiven;
    Transform PlayerStartPoint;
#endregion

    // Use this for initialization
    void Start () {
        PlayerStartPoint = transform.Find("StartPoint");
    }

    // Update is called once per frame
    void FixedUpdate () {
        ApplyGravity();
    }

    void ApplyGravity()
    {
        Collider2D[] Objects = Physics2D.OverlapCircleAll(transform.position, OuterAtmosphare);

        foreach (Collider2D col in Objects)
        {
            if (col.tag == "Player" && GameManager.instance.isGameStarted)
            {
                Camera2DFallow.instance.targetOne = this.gameObject;
            }
            Rigidbody2D colBody = col.GetComponent<Rigidbody2D>();
            if (Vector2.Distance(transform.position, col.transform.position) > InnerAtmosphare)
            {
                if (col.GetComponent<Rigidbody2D>() != null)
                {
                    colBody.AddForce(Gravity * (transform.position - col.transform.position).normalized, ForceMode2D.Impulse);
                }
            }
            else
            {
                if (col.GetComponent<Rigidbody2D>() != null)
                {
                    colBody.AddForce(-Gravity * (transform.position - col.transform.position).normalized, ForceMode2D.Force);
                }
            }
        }
    }

    void OnBecameInvisible()
    {

        PoolingSystem.DestroyAPS(gameObject);

        pointIsGiven = false;
    }


    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, OuterAtmosphare);
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, InnerAtmosphare);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Player")
        {
            if(Camera2DFallow.instance != null)
                Camera2DFallow.instance.targetOne = this.gameObject;

            other.GetComponent<PlayerController>().enabled = true;
            GameManager.instance.SaveStartPosition = PlayerStartPoint;
            if (!pointIsGiven)
            {
                GameManager.instance.GivePoint();
                pointIsGiven = true;
            }
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            other.GetComponent<PlayerController>().enabled = false;
        }
    }

}
public class GameManager : MonoBehaviour {
#region Events
    [SerializeField] ToggleEvent OnGameStart;
    [SerializeField] ToggleEvent OnGameRunning;
    [SerializeField] ToggleEvent OnGameOver;
    #endregion

public void GameOver()
    {
        OnGameRunning.Invoke(false);
        OnGameStart.Invoke(true);
        OnGameOver.Invoke(true);
        player.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    }

}

Also you might wonder what is DestroyAPS. It returns the objects to the Pool. Here is the code below. Just setting them inacitive.

public sealed class PoolingSystem : MonoBehaviour {

public static void DestroyAPS(GameObject myObject)
    {
        myObject.SetActive(false);
    }
}

One small note: I wrote a Instantiate function and call it OnDestroy and new object is not being destroyed on it’s own. I guess that’s the solution I found but still a wierd case

Because OnDestroy is a member of Monobehaviour, the class your script is inheriting from.

You shouldn’t use the Engine’s callback names if they’re not doing what they’re supposed to be doing.

Once again, you haven’t really provided enough information to continue looking for solutions. It’s really difficult for everyone here to help you.
You should try to track down the problem by removing objects or scripts partly from the scene. Other than that, at least Visual Studio also provides the option to search for words in the whole solution, have you tried that already?

I agree with @Suddoha , if this is a bug, it’s not one I’ve ever seen anybody on here mention. I’d be willing to look at the project if you’d like to upload it here, otherwise, I’m not sure what it is that would make your object be destroyed like that.

I think he’s using OnDestroy to recreate the object after it’s been destroyed, which while I understand why he’s doing that, it’s certainly very hackish.

Indeed a weird work-around for something that shouldn’t occur in the first place. :smile:

@marpione , have you already tried to attach the debugger to your project and track down the problem with it?

Amigos, por que alguns scripts no monodevelop mostram a seguinte mensagem “sem conclusões encontradas” quando eu escrevo velocidade ou adicione e fica vermelho?

You’re more-likely to get a quick answer to your question if you post it in English.
Also, please create a new thread if this is either not related to this topic and/or a similar problem but a different context.

Hello everyone Thanks for the replys. I put an OnDestroy to debug the issue and than I used it to create a new object. It was an hack and I got an error massage that’s saying “Some objects not cleared are you creating a new object on Destroy” I ignored it cause that’s what I was doing.

I found this threat and people were having a similar issue so I did the suggestions and remove and readd the trail renderer. That seems like fixed the problem. I was enabling and disabling the trail renderer and when I removed it nothing was destroyed. Than I added again and it’s working now.

Threat: Game Object being destroyed, why?

@Suddoha I shared some of my code and it’s still waiting to be approved.

Thank you so much for the answers and I hope this threate will help other people. To clearify. Remove the trail renderer and re add it. Try also removing sprite or mesh renderer and readd it as well. In some cases you might need to delete the prefab and create it again as well. I will mark this topic as solved. I also field a bug report and send the project to Unity. Hope they will find the solution.

2 Likes

Where are you waiting for code to be approved? UnityAnswers?

TrailRenderes have got a property autoDestruct that will - if enabled - ensure to destroy the GameObject they’re attached to as soon as it does not move any longer (to be exact, once the trail is no longer present - given that it has already been present).
For the pooling mechanism you may want to disable it (uncheck the box / set it to false).

Just a convenience feature that exists since the TrailRenderer component itself knows best when the trail is no longer being rendered.

I guess that was the problem. I may have checked it by mistake or something. I didn’t know such property existed. Good to know and I will keep it in mind for the future. How do I close this thread? I can’t select an asnwer as the best answer. That’s my first time here.

1 Like

These threads never get closed or a “best answer”. (like Unity Answers).
They stay here for the future, and hopefully the “best answer(s)” is/are posted here and pointed out for future readers :wink:

I see Okay no proble so the solution is to check if Auto Destruct is true on trail renderer.