如何在不使用 FindGameObjectsWithTag 的情况下获取特定的 GameObjects 进行排列?

How can i get a specific GameObjects to array without using FindGameObjectsWithTag?

在第一个脚本中,我克隆了一些游戏对象:

using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class CloneObjects : MonoBehaviour
{
    public GameObject ObjectToCreate;
    public int objectsHeight = 3;
    [HideInInspector]
    public GameObject[] objects;

    // for tracking properties change
    private Vector3 _extents;
    private int _objectCount;
    private float _objectSize;
    private List<GameObject> cloneList = new List<GameObject>();

    /// <summary>
    ///     How far to place spheres randomly.
    /// </summary>
    public Vector3 Extents;

    /// <summary>
    ///     How many spheres wanted.
    /// </summary>
    public int ObjectCount;
    public float ObjectSize;

    public static float LargestSize = 0;

    // Use this for initialization
    void Start()
    {
        Clone();
        //objects = GameObject.FindGameObjectsWithTag("ClonedObject");
        objects = cloneList.ToArray();
        foreach (var element in objects)
        {
            float Size = element.transform.localScale.x;
            if (Size > LargestSize)
                LargestSize = Size;
        }
    }

    private void OnValidate()
    {
        // prevent wrong values to be entered
        Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
        ObjectCount = Mathf.Max(0, ObjectCount);
        ObjectSize = Mathf.Max(0.0f, ObjectSize);
    }

    private void Reset()
    {
        Extents = new Vector3(250.0f, 20.0f, 250.0f);
        ObjectCount = 100;
        ObjectSize = 20.0f;
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void Clone()
    {
        if (Extents == _extents && ObjectCount == _objectCount && Mathf.Approximately(ObjectSize, _objectSize))
            return;

        // cleanup
        //var ObjectsToDestroy = GameObject.FindGameObjectsWithTag("ClonedObject");
        var ObjectsToDestroy = objects;
        foreach (var t in ObjectsToDestroy)
        {
            if (Application.isEditor)
            {
                DestroyImmediate(t);
            }
            else
            {
                Destroy(t);
            }
        }

        var withTag = GameObject.FindWithTag("Terrain");
        if (withTag == null)
            throw new InvalidOperationException("Terrain not found");

        for (var i = 0; i < ObjectCount; i++)
        {
            var o = Instantiate(ObjectToCreate);
            cloneList.Add(o);
            o.transform.SetParent(base.gameObject.transform);
            o.transform.localScale = new Vector3(ObjectSize, ObjectSize, ObjectSize);

            // get random position
            var x = Random.Range(-Extents.x, Extents.x);
            var y = Extents.y; // sphere altitude relative to terrain below
            var z = Random.Range(-Extents.z, Extents.z);

            // now send a ray down terrain to adjust Y according terrain below
            var height = 10000.0f; // should be higher than highest terrain altitude
            var origin = new Vector3(x, height, z);
            var ray = new Ray(origin, Vector3.down);
            RaycastHit hit;
            var maxDistance = 20000.0f;
            var nameToLayer = LayerMask.GetMask("Terrain");
            var layerMask = 1 << nameToLayer;
            if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
            {
                var distance = hit.distance;
                y = height - distance + y; // adjust
            }
            else
            {
                Debug.LogWarning("Terrain not hit, using default height !");
            }

            // place !
            o.transform.position = new Vector3(x, y + objectsHeight, z);
        }
        _extents = Extents;
        _objectCount = ObjectCount;
        _objectSize = ObjectSize;
    }
}

之前我第一次给 children object 我克隆了一个标签名称。 所以我可以这样做:

var ObjectsToDestroy = GameObject.FindGameObjectsWithTag("ClonedObject");

但是现在我不用这条线了。所以所有克隆的 object 都没有标记。 所以现在我不使用这条线了。

但现在我想从另一个脚本中获取所有克隆的 objects:

void Start()
    {
        anims = GetComponent<Animations>();
        waypoints = GameObject.FindGameObjectsWithTag("ClonedObject");
        originalPosition = transform.position;
    }

但是由于克隆的项目没有任何标签 waypoints 将是空的。 waypoints 是游戏对象数组:GameObject[] waypoints.

我应该给每个克隆的标签名称 object 吗?或者有没有其他方法可以将所有克隆的 object 放入 array/List 中?

解决方案 A

创建 cloneList public 或创建 public 属性 returns 它,然后从另一个脚本访问它。

public class CloneObjects : MonoBehaviour
{
    public List<GameObject> cloneList = new List<GameObject>();
}

public class AnotherScript : MonoBehaviour
{
    void Start()
    {
        var cloneObjects = obj_with_CloneObjects.GetComponent<CloneObjects>();
        //cloneObjects.cloneList 
    }
}

方案B

在另一个脚本中创建类型为 List<GameObject> 的字段。克隆后,将 cloneList 分配给该字段。

public class CloneObjects : MonoBehaviour
{
    public List<GameObject> cloneList = new List<GameObject>();

    void Clone()
    {
    }

    void Start()
    {
        Clone();
        obj_with_AnotherScript.GetComponent<AnotherScript>.cloneList = cloneList;
    }
}

public class AnotherScript : MonoBehaviour
{
    public List<GameObject> cloneList = new List<GameObject>();

    void Start()
    {
        //this.cloneList 
    }
}

But since the cloned onjects are without any tag waypoints will be empty. waypoints is array of GameObject: GameObject[] waypoints.

您可以在实例化后更改游戏对象的标签。

var o = Instantiate(ObjectToCreate);
o.tag = "ClonedObject";

只需确保在 编辑。现在,GameObject.FindGameObjectsWithTag("ClonedObject"); 应该 return 如果有具有该标签名称的实例化对象。

Should I give tag name to every cloned object ? Or is there any other way to get all the cloned objects into array/List ?

使用带有 FindGameObjectsWithTag 的标签应该没问题。如果您关心性能,那么使用 List 因为 FindGameObjectsWithTag 将搜索具有该标签的游戏​​对象。它比较慢。

我注意到您已经将实例化的游戏对象存储在 List 中。

改变

private List<GameObject> cloneList = new List<GameObject>();

public List<GameObject> cloneList = new List<GameObject>();

如果您的场景中只有一个 CloneObjects 脚本实例,您可以使用 FindObjectOfType 找到 CloneObjects 脚本,然后访问 cloneList 变量。

CloneObjects cloneObjectsInstance = FindObjectOfType<CloneObjects>();
List<GameObject> clonedObj = cloneObjectsInstance.cloneList;
for (int i = 0; i < clonedObj.Count; i++)
{

}

如果场景中有多个 CloneObjects 脚本实例,请找到脚本附加到的游戏对象,然后对其执行 GetComponent

CloneObjects  cloneObjectsInstance = GameObject.Find("ObjectCloneObjectsIsAttachedTO").GetComponent<CloneObjects>();
List<GameObject> clonedObj = cloneObjectsInstance.cloneList;
for (int i = 0; i < clonedObj.Count; i++)
{

}