- Home /
Other
Object Not Instantiating After Being Destroyed
Hello, I have a GameObject in my game called Wind and I am trying to spawn the wind on the right side of my screen every 3 seconds. The wind then moves across the bounds of the screen, then is destroyed once it is far enough off of the screen. The first wind object, which is always off the screen to begin with, does this properly, but once it is destroyed, no new wind prefabs are instantiated. The code for the wind is here:
public class WindSpawn : MonoBehaviour
{
public float speed = 5f;
private Rigidbody2D rb;
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(-speed, 0);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void Update()
{
if (transform.position.x < screenBounds.x * -2)
{
Destroy(this.gameObject);
}
}
}
And for Instantiating the prefab:
public class spawnWind : MonoBehaviour
{
public GameObject windPrefab;
public float respawnTime = 3.0f;
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
StartCoroutine(windWave());
}
void windSpawn()
{
GameObject a = Instantiate(windPrefab) as GameObject;
a.transform.position = new Vector2(screenBounds.x * -2, -1.89f);
}
IEnumerator windWave()
{
while(true)
{
yield return new WaitForSeconds(respawnTime);
windSpawn();
}
}
}
Any help would be greatly appreciated.
The code looks fine, did you try Debug.Log() in 'windSpawn()'. I think the object is getting destroyed as soon as it is spawned.
Great that it solved your issue.
Also you can use pooler ins$$anonymous$$d of instantiation, so ins$$anonymous$$d of destroying and instantiating you will simply SetActive(false), reposition, SetActive(true). It's also better choice perfomance-wise, because you reduce Destroy and Instantiate calls overall, but that's just for information of another approach option.
Good luck in your project.
Follow this Question
Related Questions
Why is it important to create an empty gameobject for my prefabs? 0 Answers
How to instantiate a empty gameobject prefab 1 Answer
PlayerRespawn class wont Instantiate the player prefab 1 Answer
Disable/Enable game object by clicking instantiated prefab during runtime 0 Answers
What does "Couldn't find matching instance in prefab" mean? 2 Answers