Home > Net >  Cloning too many of the same object when pressing an object to replace instead of the other
Cloning too many of the same object when pressing an object to replace instead of the other

Time:06-28

Image from my 2D game on unity cloning infinite objects when I press the broken one

I want to replace the broken table with a fixed table but when I press the button it places the table multiple times around the background. This is the script for the replacement.

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

public class ReplaceObjects : MonoBehaviour
{
    public GameObject Broken_Table;
    public GameObject Table;
    private bool used = false;

    void Start()
    {

    }

    void Update()

    {

        if (Input.touchCount > 0)
        {
            GameObject broken_Table = Instantiate(Broken_Table) as GameObject;
            GameObject table = Instantiate(Table) as GameObject;
            Replace(broken_Table, table);
            used = true;
        }

    }
    void Replace(GameObject obj1, GameObject obj2)
    {

        Instantiate(obj2, obj1.transform.position, obj1.transform.rotation);
        Destroy(obj1);

    }
}

CodePudding user response:

You are instantiating 3 objects for every frame you have input.

            GameObject broken_Table = Instantiate(Broken_Table) as GameObject;
            GameObject table = Instantiate(Table) as GameObject;

and

            Instantiate(obj2, obj1.transform.position, obj1.transform.rotation);

All of the above statements clone objects into your scene. You're then destroying the broken_Table right after creating it, meaning you're creating 2 fixed tables for every frame your finger is held down.

To fix this, you can do both of the following things:

  1. Only enact logic on the first frame your player "touches" the object, rather than every frame. The best way to do this is to utilize the GetTouch method and only act during TouchPhase.Began.

  2. Do not instantiate more than 1 "fixed table" in this code.

CodePudding user response:

Your code will be called every frame while your touchcount is superior than zero. So as long as you hold your finger on the screen it will call the Replace() method.

You can add your "used" bool to the previous if to avoid that, like so:

 void Update()

    {

        if (Input.touchCount > 0 && !used)
        {
            Replace(broken_Table, table);
            used = true;
        }

    }
  • Related