Search code examples
c#unity-game-engine2dinstantiationgameobject

Unity3D - Instantiated gameobject loses method?


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.


Solution

  • 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:

    • Created a Empty (renamed it to Spawner)
    • Created a Sphere (as my thing, renamed it to Ball)
    • Made Ball a prefab by dragging it into the assets folder
    • Deleted the Ball from the scene
    • Created a Spawner script and put your spawning code into it
    • Created a Ball script and put your move code into it
    • Made the two changes to the scripts
    • Put the Spawner script on the spawner gameobject
    • Dragged the Ball prefab on into the public GameObject thing of Spawner
    • Put the Ball script on the ball prefab

    Done.