Home > database >  How to make copies of Game objects?
How to make copies of Game objects?

Time:05-26

What I am trying to do in my game is when the ball destroy box its makes random number for spawning different power ups I did random chanses but I don't know how to spawn power up icon on place of destroyed block. And when its spawned its just floating down and yiu need to pick him up by touching him with platform witch you are using to baunce the ball. My code on boxes is:

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


public class destroy : MonoBehaviour
{

private string BALL_TAG = "ball";
public AudioClip coin;
public AudioSource src;
private float digit;
public GameObject spawnTo;




private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag(BALL_TAG))
    {

        movement PBDM = FindObjectOfType<movement>();          

        PBDM.Destroy();
        src.clip = coin;
        src.Play();
        digit = Random.Range(0, 101);

        if (digit <= 15 && digit >= 11)        
         print("THERE IS A PLACE WHERE I NEED TO SPAWN POWER UP ON XYZ OF BOX.");

        else if (digit <= 10 && digit >= 1)
            Debug.Log("epic");

        else
            Debug.Log("basic");

        Destroy(gameObject);

        }
    }

}

This Debugs I used just for testing if it workes.

CodePudding user response:

So if I understand you correctly you want just to Instantiate object.

To create a new GameObject on the scene you can follow these steps:

  1. Create a Prefab of the GameObject that you want to spawn. You can do it by dragging the GameObject from the hierarchy to the assets window.

  2. Drag & drop it on C# Script component on the object you want to spawn the prefab.

  3. change your if statement to:

         if (digit <= 15 && digit >= 11)
             Instantiate(spawnTo, this.transform.position, Quaternion.identity);
    

You can additionally read about the Instantiate() method if you want to instantiate GameObject as a child of some another GameObject.

  • Related