为什么在创建新的GameObjects时它没有改变标签?

时间:2017-05-16 06:37:33

标签: c# unity3d unity5

在第一个脚本中:

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

public class InstantiateObjects : MonoBehaviour
{
    public GameObject prefab;
    public Terrain terrain;
    public float yOffset = 0.5f;

    private float terrainWidth;
    private float terrainLength;

    private float xTerrainPos;
    private float zTerrainPos;


    void Start()
    {
        //Get terrain size
        terrainWidth = terrain.terrainData.size.x;
        terrainLength = terrain.terrainData.size.z;

        //Get terrain position
        xTerrainPos = terrain.transform.position.x;
        zTerrainPos = terrain.transform.position.z;

        //generateObjectOnTerrain();
    }

    public void generateObjectOnTerrain(bool parent, string tag)
    {
        //Generate random x,z,y position on the terrain
        float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
        float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
        float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));

        //Apply Offset if needed
        yVal = yVal + yOffset;

        //Generate the Prefab on the generated position        
        GameObject objInstance = Instantiate(prefab, new Vector3(randX, yVal, randZ), Quaternion.identity);
        if (parent)
            objInstance.transform.parent = this.transform;
        objInstance.transform.tag = tag;
    }
}

在我正在使用的脚本中:

private void Start()
    {
        for (int i = 0; i < cloneTeleportations; i++)
        {
            InstantiateObjects gos = GetComponent<InstantiateObjects>();
            gos.prefab = prefab;
            gos.generateObjectOnTerrain(true, "ddd");//"Teleportation");
        }
    }

如果我将它从true更改为false,它将不会使GameObjects的孩子,如果它是真的,他们将是孩子。父部分正在运作。 但是为了测试,我试图将标签更改为“ddd”,我在第一个脚本中看到标签是“ddd”:

objInstance.transform.tag = tag;

标签是“ddd”,默认情况下objInstance.transform.tag是“Teleportation”,在运行游戏时所有克隆的游戏对象都标记为“传送”而不是“传送”。

1 个答案:

答案 0 :(得分:3)

Unity中,您必须先从编辑器手动添加tag,然后才能将其分配给GameObject。如果tag不存在,则无法分配它。