【问题标题】:How can I add a int level variable to decide from what level to start getting the objects? And what colliders should I add to them?如何添加一个 int 级别变量来决定从哪个级别开始获取对象?我应该向它们添加哪些对撞机?
【发布时间】:2019-10-19 23:18:49
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

public class GetComponents : MonoBehaviour
{
    public Transform parent;
    public List<GameObject> allObjects = new List<GameObject>();

    private void Start()
    {
        string path = "e:/colliders.txt";
        StreamWriter writer = new StreamWriter(path, true);

        allObjects = FindObjectsOfType<GameObject>().ToList();

        Transform[] allChildren = parent.GetComponentsInChildren<Transform>();

        foreach (Transform child in allChildren)
        {
            var colliders = child.GetComponents<Collider>();

            int length = colliders.Length;

            if (length == 0)
            {
                writer.WriteLine(string.Format("{0} - No Colliders", child.name));
            }
            else
            {
                //composes a list of the colliders types, this will print what you want e.g. "Wall1 - BoxCollider, MeshCollider"

                string colliderTypes = string.Empty;

                for (int i = 0; i < length; i++)
                {
                    colliderTypes = string.Format("{0}{1}", colliderTypes, colliders[i].GetType().Name);

                    if (i != (length - 1))
                    {
                        colliderTypes = string.Format("{0}, ", colliderTypes);
                    }
                }
                //writer.WriteLine(string.Format("{0} - {1}", child.name, colliderTypes));
            }
        }

        writer.Close();
    }
}

在这种情况下,我只得到没有碰撞器的对象。然后我想为每个对象添加一个对撞机。但是由于有太多对象,我想为每个对象添加一个碰撞器,以防止玩家角色穿过它们。我不确定是否只是向它们添加网格对撞机或其他一些对撞机?

我如何设置一个级别来开始获取对象?

例如我有这个结构:

Parent
 Child 1
 Child 2
 Child 3
 Child 4

现在 0 级是父级 1 级是子级 1 到 4。但在每个子级 1、2、3、4 中,在许多级(树)中还有更多的子级。

我想从示例中获取子级 1 的变换,因此它不会将父级和子级 1、2、3、4 作为没有碰撞器的对象。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    有两种方法可以实现这一目标 1.检查孩子的父母是不是你想要的。

    foreach (Transform child in allChildren){ 
      if(child.parent == parent){
       //Add colliders}
    

    2.不使用GetComponentsInChildern

    foreach(Transform t in parent){
       // add Colliders
    }
    

    参考:
    https://answers.unity.com/questions/495079/how-to-get-first-depth-child-components-of-a-paren.html

    【讨论】:

    • 我应该在游戏对象中添加什么对撞机? Mesh Collider 还是 Box Collider ?由于有很多游戏对象,我想向它们添加自动对撞机,以防止玩家穿过它们。但不确定要添加哪种类型的对撞机。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多