Search code examples
c#unity-game-enginegame-physics

Instantiate creates multiple clones in Unity


I have the following code:

public Rigidbody2D ball;
Vector2 sp = new Vector2(0f, 2.1f);

void Update() {
    if (Input.GetKeyDown("w")) {
        SpawnBall();           
        DestroyBall();
    }
}
void SpawnBall()
{
    Instantiate(ball, sp, transform.rotation);
}

void DestroyBall()
{
    if (ball.transform.position.y >= -5.7f)
    {
        Destroy(ball);
    }
}

and the code is supposed to generate a new ball every time when "w" is pressed, but for some reason it creates multiple clones and it crashes the engine. How can I create a single clone only?

And also the destroy method doesn't do anything, although it should remove the clone when it passes -5.7 on the y-axis.

Thanks in advance


Solution

  • Create a new script named "SpawnRigidbody" and copy and paste the below code.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class SpawnRigidbody : MonoBehaviour 
    {
    
        public Rigidbody2D ball;
        Vector2 sp = new Vector2(0f, 2.1f);
    
        void Update() 
        {
            if (Input.GetKeyDown("w")) {
                SpawnBall();
            }
        }
    
        void SpawnBall()
        {
            Debug.Log ("spawn");
            GameObject go = Instantiate(ball, sp, transform.rotation).gameObject;
            go.AddComponent<DestroyAfterPosition> ();
        }
    }
    

    Now create another script named "DestroyAfterPosition" and copy and paste the below code.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class DestroyAfterPosition : MonoBehaviour 
    {
    
        void Update ()
        {
            if (transform.position.y <= -5.7f)
            {
                Destroy(gameObject);
            }
        }
    }
    

    Create an empty game object and attach the SpawnRigidbody and then assign your ball in the inspector.

    Hope this help you.