user6768003
user6768003

Reputation:

unity2d: Destroy method not working when i try to destroy a game object

(this is not the whole code) when i test the script in the console it says: LEVEL2 UNLOCKED meaning that it works but when i try to use the destroy method it doesn't destroy the level2lock gameobject.

 if (PlayerPrefs.GetString("level2unlocked") == "true")
     {
         Debug.Log("LEVEL2 UNLOCKED");
         Destroy(level2lock);
     }

Upvotes: 1

Views: 1736

Answers (1)

Motonstron
Motonstron

Reputation: 932

Is 'level2lock' of the type GameObject, or is it a reference to a script attached to the GameObject.

So for example:

private LevelLockComponent level2lock;

private void DestroyLevelLockMethod()
{
    Destroy(level2lock.gameObject);
}

LevelLockComponent would be a script attached to the level2lock GameObject.

I hope this helps.

Update

Hi Drin,

I see, I've just written this simple implementation for destroying a GameObject that has been assigned in the editor.

using UnityEngine;
using System.Collections;

public class GameObjectKiller : MonoBehaviour 
{
    public GameObject otherGameObject;

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            Destroy(otherGameObject);
        }
    }
}

This destroys the 'otherGameObject' from the hierarchy when the A button is pressed.

I would also recommend looking at the Unity Tutorial for using 'Destroy' here: https://unity3d.com/learn/tutorials/modules/beginner/scripting/destroy

Upvotes: 2

Related Questions