Why more balls are instantiating?

51 views Asked by At

I'm making a game in unity where the user drags to shoot a ball at some objects at a distance. So far I have this DragAndShoot script:

 //using System.Collections;
 //using System.Collections.Generic;
 using UnityEngine;
 
 [RequireComponent(typeof(Rigidbody))]
 [RequireComponent(typeof(Collider))]
 public class DragAndShoot : MonoBehaviour
 {
     public Transform prefab;
     private Vector3 mousePressDownPos;
     private Vector3 mouseReleasePos;
 
     private Rigidbody rb;
 
     private bool isShoot;
     
     void Start()
     {
         rb = GetComponent<Rigidbody>();
     }
 
     private void OnMouseDown()
     {
         mousePressDownPos = Input.mousePosition;
     }
 
     private void OnMouseUp()
     {
         mouseReleasePos = Input.mousePosition;
         Shoot(mouseReleasePos-mousePressDownPos);
     }
 
     private float forceMultiplier = 3;
     void Shoot(Vector3 Force)
     {
         if(isShoot)    
             return;
         
         rb.AddForce(new Vector3(Force.y,Force.x,Force.z) * forceMultiplier);
         isShoot = true;
         createBall();
     }
 
     void createBall(){
         Instantiate(prefab, GameObject.Find("SpawnPoint").transform.position, Quaternion.identity);
     }
     
 }

As you can see, I made the function createBall() in order to respawn a ball prefab at the position of the game object SpawnPoint. When I run the game, the first ball shoots fine. And another ball respawns.

Issue: when I shoot the second ball and it moves, one more ball seems to have appeared at the second ball somehow, and it moves as well. Not sure why this is happening and how to fix it - can someone pls help? Thanks.

1

There are 1 answers

0
gbe On

The problem is that you need to Destroy() the game object you threw first. Since you are just bringing the objects back when click down again, here is what you should do:

Make it so that it destroys the old object. Because you just keep instantiating the object, then when you throw it again it throws the old one too. If you understand what I mean, then hopefully, you can turn this into what you want. (It wasn’t exactly clear what your game was; this is what I interpreted)