Reputation:
How do I destroy a gameObject permanently? That is, I want the gameObject to be there only once before if I destroy it in the current scene and then when I reload the same scene, I want it to be disabled/destroyed. How do I achieve this?
Edit: Or the below script can run only once with a bool variable?
void Update()
{
if(Input.GetKeyDown(KeyCode.A)
{
GameObject go = GameObject.Find("Cloner");
Destroy(go);
SceneManager.LoadScene("Home");
}
}
Upvotes: 3
Views: 3228
Reputation: 29
I threw together this simple script for permanently destroying pickup items in my game even as the player switches between scenes. Just attach it to the single-use item GameObject and give it a unique name.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontRespawn : MonoBehaviour
{
public static List<string> pickedUpObjs = new List<string>();
void Start()
{
if (pickedUpObjs.Contains(gameObject.name))
{
Destroy(gameObject);
}
}
void OnDestroy()
{
pickedUpObjs.Add(gameObject.name);
}
}
Upvotes: 0
Reputation:
I did it by using DontDestroyOnLoad() in the function
void Awake()
static bool created = false;
public bool Loading = true;
void Awake()
{
if(!created)
{
DontDestroyOnLoad(this.gameObject);
created = true;
}
else
{
Destroy(this.gameObject);
}
}
void Update()
{
if(Input.GetKeyDown(KeyCode.A) && LoadingOnce == true)
{
GameObject go = GameObject.Find("Cloner");
Destroy(go);
LoadingOnce = false;
SceneManager.LoadScene("Home");
}
}
Upvotes: 2