- Home /
Instantiate problem.
I just want ONE object to be created at a spot but it just creates them endlessly, even made unity crash. :D
using UnityEngine;
using System.Collections;
public class Spawning : MonoBehaviour {
public GameObject target;
Vector3 spawnSpot;
bool once = false;
void Start() {
if(once = !once) {
spawnSpot = target.transform.position;
Instantiate(transform, spawnSpot, Quaternion.identity);
once = true;
}
}
}
Thanks in advance.
Answer by robertbu · Feb 16, 2013 at 01:43 AM
You are creating copies of yourself? Is that what you want to do? Make your once variable static:
static bool once = false;
Answer by dubbreak · Feb 16, 2013 at 03:05 AM
As roberbu pointed out you're creating copy of the object you have that script on. But then that object creates a copy of itself and so on and so on.
First question is: what are you trying to do? I.e. what's your goal. There may be a better way.
As for fixing your script, I tested the following as working (creates one copy of object at the location of "target"):
using UnityEngine;
using System.Collections;
public class Spawning : MonoBehaviour {
public GameObject target;
Vector3 spawnSpot;
static bool makeCopy = true;
void Start()
{
if(makeCopy)
{
makeCopy = false;
spawnSpot = target.transform.position;
Instantiate(transform, spawnSpot, Quaternion.identity);
}
}
}
Answer by HashGrove · Feb 16, 2013 at 03:54 PM
Changing to static worked! My goal is to create a random number of enemies in random locations, but my idea was to start small to get the hang of things. I'm not sure I understand what changed when I switched the variable to static.
Do you understand why you originally produced enemies until Unity crashed? The static means there will be one variable for the Spawning class rather than a variable for every instance of your class.
With it not static each instance of your class ends up with it's own copy (so make copy is set to true on the clone of your object). With static there is only one copy of that variable.
The issue is you're cloning an object with that script attached so the next item has the script too. When I have a "spanwner" I usually attach it to an empty object and have it spit out items as I want them.
Also, you are new here, but FYI don't create an answer to comment on someone's answer. Press the add new comment button below their question.
Your answer
Follow this Question
Related Questions
Potential 4.3.1f1 bug Instantiate c# 2 Answers
Checking if object intersects? 1 Answer
Shotgun Spread Issue 1 Answer
Better way to do this? Instatiate or simply turn on and off? 1 Answer