Search code examples
c#unity-game-engineinstantiation

UNITY - Instantiate in order


There is a cannonball in the game and as you press the button, it sends three balls that go in sequence, then the number of balls doubles when passing through the place where it says "2X". The problem is that the doubled balls, the cloned balls, travel in different positions. What I want is; cloned balls follow the balls from which they were cloned. enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BallManager : MonoBehaviour
{
public Rigidbody mainBall;
public Rigidbody cloneBall;
public float shootSpeed;

void Start()
{

}

// Update is called once per frame
void Update()
{
    
}

void OnTriggerEnter(Collider col)
{
    if (col.tag == "Push")
    {
        Debug.Log("Oldu işte aq");
        Destroy(gameObject, 0.5f);
    }

    if (col.tag == "2X" && gameObject.tag == "Ball")
    {
        Rigidbody p = Instantiate(cloneBall, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
        //Rigidbody p = Instantiate(projectile, transform.position, Quaternion.identity);
        p.velocity = transform.TransformDirection(Vector3.forward * shootSpeed);

        //Çarptığı nesneyi yok eder
        Destroy(col.gameObject, 0.2f);
    }
}
}


Solution

  • So yeah you issue is most probably that you spawn all the balls at the same position in

    Instantiate(cloneBall, transform.position, Quaternion.identity);
    

    so they all collide/overlap with each other and are pushed away in arbitrary direction by the physics.


    So the best would probably be to simply make your balls not collide with each others but with anything else.

    For this simply create a dedicated Layer like e.g. Ball, assign it to your ball prefab and then configure the Physics SettingsLayer Collision Matrix so that the layer Ball does not collide with itself.