简体   繁体   English

如何在检查器Unity中区分不同的BoxCollider

[英]How to distinguish between different BoxCollider in the inspector Unity

Let's say I have a gameobject "player" with 4 different BoxColliders2D 假设我有一个带有4种不同BoxColliders2D的游戏对象“玩家”

I have a wall script that's a component of the "wall" gameobject. 我有一个墙脚本,它是“墙”游戏对象的组成部分。

The wall script has 4 different public boxcolliders2D variables, but I can't seem to find a way to set each of them to their respective boxcollider2D in the player gameobject, in the inspector. 贴图脚本有4个不同的public boxcolliders2D变量,但我似乎找不到一种在检查器中的玩家游戏对象中将它们分别设置为各自的boxcollider2D的方法。

The wall script has 4 different public boxcolliders2D variables, but I can't seem to find a way to set each of them to their respective boxcollider2D in the player gameobject, in the inspector. 贴图脚本有4个不同的public boxcolliders2D变量,但我似乎找不到一种在检查器中的玩家游戏对象中将它们分别设置为各自的boxcollider2D的方法。

You can't do that from the Editor but you should be able to do this via code. 不能从编辑器中执行此操作,但应该可以通过代码执行此操作。

Initialize your 4 variables from code by using the GetComponents function which returns array of components attached to the GameObject. 通过使用GetComponents函数从代码初始化您的4个变量,该函数返回附加到GetComponents的组件的数组。 Notice the 's' at the end. 注意最后的“ s”。 That's different from the GetComponent function which returns just one GameObject. 这与GetComponent返回一个GetComponent函数不同。

public BoxCollider2D col1;
public BoxCollider2D col2;
public BoxCollider2D col3;
public BoxCollider2D col4;

void Awake()
{
    BoxCollider2D[] colliders = GetComponents<BoxCollider2D>();
    col1 = colliders[0];
    col2 = colliders[1];
    col3 = colliders[2];
    col4 = colliders[3];
}

While the code version should work, do not attach multiple BoxCollider2D to one GameObject. 虽然代码版本应该可以,但是不要将多个BoxCollider2D附加到一个GameObject。 What to do is create child GameObject for each extra collider you want then attach the BoxCollider2D component to it. 要做的是为每个想要的额外对撞机创建子GameObject,然后将BoxCollider2D组件附加到它。 This is the recommended way of using multiple colliders on one GameObject and that should solve your problem. 这是在一个GameObject上使用多个碰撞器的推荐方法,应该可以解决您的问题。

Below is a screenshot of what that should look like: 下面是应该显示的屏幕截图:

在此处输入图片说明

Now, you can drag each child Collider ( BoxCollider2D 1 , BoxCollider2D 2 , BoxCollider2D 3 ) to the proper public variable name. 现在,您可以将每个子Collider( BoxCollider2D 1BoxCollider2D 2BoxCollider2D 3拖到适当的public变量名称中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM