How to Instantiate a game object at the same posit

2019-08-22 07:57发布

I have multiple empty game objects that serve as the spawn points that spawn the game objects and I want the spawned game objects to be destroyed and Instantiate a new one on same spawn point if the condition to be tested is true.

I have 2 separate scripts, the one attached on the spawn point objects and another for the game manager that has the condition in it.

The Condition on the Game manager script:

public void checkword()
 {
     wordBuilded = displayer.text.ToString();

     LetterTiles[] tiles = FindObjectsOfType<LetterTiles>();

     foreach (LetterTiles item in tiles)
     {

         if (txtContents.Contains(wordBuilded))
         {
             if (item.gameObject.CompareTag("clicked"))
             {
                 Destroy(item.gameObject);
                 FindObjectOfType<letterSpawner>().refresh();
             }                                                     
         }

         else
         {
             if (item.gameObject.CompareTag("clicked"))
                 item.GetComponent<Button>().interactable = true;
         }

     }
 }

The script attached to the spawn point objects that Instantiates the objects

using UnityEngine;

public class letterSpawner : MonoBehaviour {

     public GameObject[] letterTiles;
     GameObject tiles;
     Vector3 scale = new Vector3(0.8f, 0.8f, 0);

     void Start () {
         refresh();
     }

     public void refresh()
     {
         int rand = Random.Range(0, letterTiles.Length);
         tiles = Instantiate(letterTiles[rand], transform.position, Quaternion.identity);
         tiles.transform.SetParent(gameObject.transform);
         tiles.transform.localScale = scale;

     }
 }

1条回答
乱世女痞
2楼-- · 2019-08-22 08:35

You can do that by making a small change to whatever you have, first change your refresh function into this one

public void refresh(Vector3 position)
 {
     int rand = Random.Range(0, letterTiles.Length);
     tiles = Instantiate(letterTiles[rand], position, Quaternion.identity);
     tiles.transform.SetParent(gameObject.transform);
     tiles.transform.localScale = scale;

 }

also in the same file add another default one that calls this with the default value that you had

public void refresh()
 {
     refresh(transform.position);
 }

and then in your checkword function

if (item.gameObject.CompareTag("clicked"))
{
    Vector3 pos = item.transform.position;
    Destroy(item.gameObject);
    FindObjectOfType<letterSpawner>().refresh(pos);
}

that should do it for you

查看更多
登录 后发表回答