- Home /
Check if object is destroyed on level load, if so instantiate prefab?
I have pick up items that are destroyed when the player picks them up, when I load the level from the gameover or start screen after playing, the objects are still destroyed and therefore the player cannot pick them up. I would like it so that the objects are instantiated from a prefab when the level is reloaded. Here is my current script:
using UnityEngine;
using System.Collections;
public class objectregen : MonoBehaviour {
public GameObject original;
public GameObject prefab;
void Start(){
if (!original) {
print("stuff");
Instantiate(prefab);
}
}
}
I get no errors but nothing happens.
i guess you are calling DontDestroyOnLoad() on your objects, if you do are you sure that you really need it?
I'm not sure if I know what you mean. Right now the objects are destroyed when the player picks them up. If I put DontDestroyOnLoad() on the objects will that prevent them from being destroyed in the reload even though they were destroyed in game?
my apologies, corrected the script
void Start(){
foreach(gameObject g in GameObject.FindObjectsWithTag("recreate$$anonymous$$e"))
g.SetActive(true);
}
Answer by OctoSloths · Dec 08, 2014 at 10:49 PM
I tried your script and it doesn't seem to be working but there are no errors. The gameobject is not set active again. I also tried this script and it doesn't work either:
using UnityEngine;
using System.Collections;
public class objectregen : MonoBehaviour {
public GameObject prefab;
void Start (){
//foreach(GameObject g in GameObject.FindGameObjectsWithTag("pickup"))
prefab.SetActive(true);
}
}
EDIT: Wait your script worked perfectly and it turns out it was just Unity being weird, after closing and reopening it it worked, haha. Thank you so much!
Your answer
![](https://koobas.hobune.stream/wayback/20220613173507im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to instantiate object with content prefab and not him self 2 Answers
How many time does a prefab takes to load?? 1 Answer
Deleting a GameObject 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
PlayerRespawn class wont Instantiate the player prefab 1 Answer