我如何告诉另一个脚本在 Unity 中实例化一个特殊的预制件?

How can I tell another script to instantiate a special prefab in Unity?

我有生成障碍物顺序的代码:

using UnityEngine;
using System.Collections.Generic;

public class GroundSpawner : MonoBehaviour
{   
    public GameObject groundTile;
    public static string item;

    private List<string> listOfChoices = new List<string>{"box", "antitank", "barricade", "wheels"};
    private List<string> roadList = new List<string>();

    Vector3 nextSpawnPoint;

    void Start()
    {
        roadList = GenItemList(10, 2);
        for (int i = 0; i < roadList.Count; i++)
        {
            item = roadList[i];
            GameObject temp = Instantiate(groundTile, nextSpawnPoint, Quaternion.identity);
            nextSpawnPoint = temp.transform.GetChild(1).transform.position;
        }
    }

    public List<string> GenItemList(int numOfItems, int numOfTanks)
    {
        List<string> returnList = new List<string>();

        for (int i = 0; i < numOfItems; i++)
        {
            int randomIndex = Random.Range(0, listOfChoices.Count);
            string add = listOfChoices[randomIndex];
            returnList.Add(add);
        }

        for (int i = 0; i < numOfTanks; i++)
        {
            int randomIndex = Random.Range(1, numOfItems);
            returnList[randomIndex] = "tank";
            int tankIndex = randomIndex;

            int numOfMolotoves = Random.Range(1, 4);
            for (int j = 0; j < numOfMolotoves; j++)
            {
                randomIndex = Random.Range(0, (tankIndex - 1));
                if(returnList[randomIndex] != "molotov")
                {
                    returnList[randomIndex] = "molotov";
                }
                else
                {
                    numOfMolotoves++;
                }
            }
        }

        return returnList;
    }

}

void Start()中有一行:

item = roadList[i];

这条线是我想要生成的障碍物(箱子、路障、轮子、反坦克或燃烧弹)。

我有 GroundTileGroundTileScript。我实例化 GroundTile,但我如何告诉当前 GroundTileGroundScript 实例化 item?真的可以吗?

因此,假设您在 GroundTile 对象中有一个 GroundTileScript,您可以这样做。

GameObject tile = Instantiate(tileprefab);
tile.GetComponent<GroundTileScript>().Spawnitem;

我可能是错的,所以如果有问题请告诉我。

您已经在可变温度下保存了 groundTile 游戏对象数据。

GameObject temp = Instantiate(groundTile, nextSpawnPoint, Quaternion.identy);

你要做的就是从 temp gameObject 中获取你生成的 GameObject temp 的组件,如下所示。

GroundTile tile = temp.GetComponent<GroundTile>();

然后您可以使用您的 public 方法或获取 public 变量值。

tile.DoSomeThing();
tile.somePublicVariable = 0;