- Home /
When I merge 2 objects it spawns 2 objects
I just started to make a merge game. I try to merge 2 objects but because the script is in both of the objects it repeats the script 2 time and it spawn 2 objects instead of 1. Here is the code.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class merge : MonoBehaviour
{
public GameObject box2Prefab;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.transform.tag == "box1")
{
GameObject box2z = Instantiate(box2Prefab);
box2z.transform.parent = transform.parent;
box2z.transform.position = this.transform.position;
Destroy(other.gameObject);
Destroy(gameObject);
}
}
}
I cant delete the script on the other object because if I put a spawner it won't work.
Just a comment/recommendation on something else in your code, destroying and instantiating objects is very expensive so should be used sparingly if at all, and I imagine you'll be using it a lot in a merge game. You can use object pooling instead :) https://learn.unity.com/tutorial/introduction-to-object-pooling
Actually I am making the game for both having fun and remembering how to code. I quit coding and just started again. But I'm going to learn how to object pool. Thanks for telling me.
Answer by unity_ek98vnTRplGj8Q · Apr 21, 2021 at 10:45 PM
You could try DestroyImmediate instead of Destroy, which might get rid of the other object fast enough for it not to spawn its own copy of the new object. If that doesn't work just set a flag in the script to signify if the new box has been spawned already or not. Something like
bool newBoxAlreadySpawned = false;
OnTriggerEnter()
if(newBoxAlreadySpawned) return;
else
other.GetComponent<Merge>().newBoxAlreadySpawned = true;
//the rest of your stuff
DestroyImmediate doesn't work but the script worked thanks.