I would like that when two spheres (prefab) meet they disappear and form a square, but 2 are formed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class circle : MonoBehaviour
{
public GameObject square;
Vector3 pos;
void Start()
{
}
void Update()
{
}
void OnCollisionEnter2D(Collision2D collision) {
if(collision.gameObject.name == this.gameObject.name) {
pos = transform.position;
Destroy(gameObject);
Instantiate(square, pos, Quaternion.identity);
}
}
}
I tried with for and while loops and with a variable but I couldn't get it to work
The reason 2 squares are spawned is because both objects are spawning the square.
To fix this, add a boolean to the class to indicate if merging already happened.
Before merging, check that boolean to see if merging has already been handled.
If it hasn't been merged yet, set merged to true and destroy both objects.
public class Circle : MonoBehaviour
{
private bool isMerged;
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.TryGetComponent<Circle>(out var otherCircle) &&
collision.gameObject.name == this.gameObject.name &&
otherCircle.isMerged == false)
{
isMerged = true;
Instantiate(square, transform.position, Quaternion.identity);
Destroy(gameObject);
Destroy(collision.gameObject);
}
}
}