Unity inspector中如何区分不同的BoxCollider
How to distinguish between different BoxCollider in the inspector Unity
假设我有一个游戏对象 "player" 有 4 个不同的 BoxColliders2D
我有一个墙体脚本,它是 "wall" 游戏对象的一个组成部分。
wall script 有 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.
您不能从编辑器中做到这一点,但您应该能够通过代码做到这一点。
使用 GetComponents
函数从代码中初始化您的 4 个变量,其中 returns 组件数组附加到 GameObject。注意最后的 's' 。这与 GetComponent
函数不同,后者 returns 只有一个游戏对象。
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];
}
虽然代码版本应该可以工作,但不要将多个 BoxCollider2D 附加到一个游戏对象。要做的是为每个你想要的额外碰撞器创建子游戏对象,然后将 BoxCollider2D 组件附加到它。这是在一个游戏对象上使用多个碰撞器的推荐方法,应该可以解决您的问题。
下面是应该看起来像的屏幕截图:
现在,您可以拖动每个子 Collider (BoxCollider2D 1, BoxCollider2D 2, BoxCollider2D 3) 到正确的 public
变量名。
假设我有一个游戏对象 "player" 有 4 个不同的 BoxColliders2D
我有一个墙体脚本,它是 "wall" 游戏对象的一个组成部分。
wall script 有 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.
您不能从编辑器中做到这一点,但您应该能够通过代码做到这一点。
使用 GetComponents
函数从代码中初始化您的 4 个变量,其中 returns 组件数组附加到 GameObject。注意最后的 's' 。这与 GetComponent
函数不同,后者 returns 只有一个游戏对象。
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];
}
虽然代码版本应该可以工作,但不要将多个 BoxCollider2D 附加到一个游戏对象。要做的是为每个你想要的额外碰撞器创建子游戏对象,然后将 BoxCollider2D 组件附加到它。这是在一个游戏对象上使用多个碰撞器的推荐方法,应该可以解决您的问题。
下面是应该看起来像的屏幕截图:
现在,您可以拖动每个子 Collider (BoxCollider2D 1, BoxCollider2D 2, BoxCollider2D 3) 到正确的 public
变量名。