Jaafar Ben Bouker
Jaafar Ben Bouker

Reputation: 27

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

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);

    }
}

Upvotes: 0

Views: 53

Answers (1)

Erik Overflow
Erik Overflow

Reputation: 2306

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.

Upvotes: 1

Related Questions