简体   繁体   中英

How to distinguish between different BoxCollider in the inspector Unity

Let's say I have a gameobject "player" with 4 different 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.

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.

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. Notice the 's' at the end. That's different from the GetComponent function which returns just one GameObject.

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. What to do is create child GameObject for each extra collider you want then attach the BoxCollider2D component to it. This is the recommended way of using multiple colliders on one GameObject and that should solve your problem.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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