Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Destroying a GameObject deactivates the Collider2D attached to it

Discussion in 'Scripting' started by Kinkku2, May 22, 2015.

  1. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Hey. So I have a goal that changes place after the player touches it by desroying (Destroy(goal)) it and then instantiating a new goal from a prefab. However, after it has been destroyed the Collider2D attached to the new instantiated copy of the GameObject deactivates even though it hasn't been deactivated in the prefab.

    How could I go about fixing this problem?
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
  3. OneDragutin

    OneDragutin

    Joined:
    May 10, 2015
    Posts:
    326
    When instantiated you could get Collider2D and then you could enable it again.
     
  4. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Enabling the Collider2D component again did not work. :( Here's the code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Player : MonoBehaviour {
    5.  
    6.     public GameObject goal;
    7.     public Collider2D colliderGoal;
    8.  
    9.     void Start () {
    10.         CreateNewGoal ();
    11.     }
    12.  
    13.     void OnTriggerEnter2D (Collider2D other) {
    14.         if(other.gameObject.CompareTag("Collectible")) {
    15.             Debug.Log("works");
    16.             Destroy(goal);
    17.             CreateNewGoal();
    18.         }
    19.     }
    20.  
    21.     void CreateNewGoal () {
    22.         float randomY = Random.Range (-3, 5);
    23.         float randomX = Random.Range (-5, 5);
    24.         goal = (GameObject)Instantiate (goal, new Vector3 (randomX, randomY, -5.0f), Quaternion.identity);
    25.         colliderGoal.enabled = true;
    26.     }
    27. }
     
  5. OneDragutin

    OneDragutin

    Joined:
    May 10, 2015
    Posts:
    326
    When you destroy goal game object, that variable become empty, right?
    And then after that you want to create new object (instantiate) using that empty variable?

    That probably causes the problem you have!
     
  6. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Ok, I added a new variable for the prefab that is instantiated and it works now!

    Code (CSharp):
    1. goal = (GameObject)Instantiate (prefab, new Vector3 (randomX, randomY, -5.0f), Quaternion.identity);
     
unityunity