- Home /
Unity Crashes When Spawning Prefab
Unity 2019.2.18f1
So, I'm trying to spawn in an item whenever the trigger is entered. It seems to work but it also crashes Unity almost instantly. It's hard to tell but looks like Unity is making multiple of these objects and that's causing the crash. How do I fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateObject : MonoBehaviour
{
public Transform Spawnpoint;
public GameObject Prefab;
private void OnTriggerEnter(Collider other)
{
Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
}
}
Answer by TMerelFSU · Mar 29, 2020 at 07:42 PM
This works pretty much perfectly. It only spawns the item once.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateObject : MonoBehaviour
{
public Transform Spawnpoint;
public GameObject Prefab;
private int count = 0;
private void OnTriggerEnter(Collider other)
{
count = count + 1;
if (count == 1)
{
Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
}
}
private void OnTriggerExit(Collider other)
{
count = count - 1;
}
}
Answer by wesleyos · Mar 29, 2020 at 10:57 AM
What probably is happening is your code isn't checking which object collides with the trigger and probably when the instantiation happens, the created object automatically enters the trigger. So it becomes a loop of instantiation.
The solution would be to even set a timer for this instantiation to happen or exclude the object that is being created of triggering the instantiation (this can be done through layers, tags or type checking).
Thank you for your answer! I went a slightly different route but you definitely helped point me in the right direction.
Your answer
Follow this Question
Related Questions
Instantiate a Prefab with click in a certain area 2 Answers
How to force a variable to prefab 1 Answer
instatiates at a bad position 1 Answer
i need to destroy prefab clones 1 Answer