Hey everyone and thanks for taking the time.
I'm currently working on a 2D something in Unity and have the following problem:
We have a spawner that periodically creates 'thing':
public float spawnTime = 3;
public Object thing; //public GameObject thing;
// Use this for initialization
void Start () {
InvokeRepeating("spawn", spawnTime, spawnTime);
}
void spawn ()
{
Vector3 pos = new Vector3(-14, 0, 0);
Quaternion ori = new Quaternion(0, 0, 0, 0);
Instantiate(thing, pos, ori);
}
And it does a good job. Meet 'thing':
void Start () {
InvokeRepeating("move", 0.1f, 0.1f);
}
void move()
{
transform.Translate(0.2f, 0, 0);
if (this.transform.position.x > 14)
{
Destroy(this); //Destroy(GameObject);
So basically a 'thing' is created, hauls itself from -14 to 14 and then suffocates.
Problem: As soon as the first 'thing' is deleted the newly created (not the ones already moving) dont ever move from -14.
I guess I haven't properly specified which method to call periodically but wasn't able to find a proper solution in the unity3d top-down-shooter or similar examples.
Thanks again.
€: After applying the proposed changes the spawner stops creating 'thing's after 3 cycles of creation.
€: My mistake was not using the 'thing' as a prefab (dragging it into "assets" as described in the beautiful answer) so I was referencing a soon to be deleted instance of my 'thing'. Dragged it to hell (assets) and was happy ever after.
I recreated you setup with just these scripts and what I got is that the objects just didn't get destroyed, but newly spawned moved properly until 14.
The reason they didn't get destroyed though is, that you called Destroy(this);
which destroys the script component, not the gameobject. So this should be Destroy(gameObject);
instead. With this fix it runs just fine for me.
Also, if there is no special reason to use object, your public Object thing;
should better be public GameObject thing;
.
Edit:
How I set it up:
Empty
(renamed it to Spawner
)Sphere
(as my thing
, renamed it to Ball
)Ball
a prefab by dragging it into the assets folderSpawner
script and put your spawning code into itBall
script and put your move code into itSpawner
script on the spawner gameobjectBall
prefab on into the public GameObject thing
of Spawner
Ball
script on the ball prefabDone.