如何使游戏对象定位其他游戏对象的位置并告诉它们的颜色



我有 2 个游戏对象,一个蓝色和红色。他们俩都在现场跑来跑去,相机有限制,所以他们不能通过某个区域。

如果可能的话,我也想知道如何在对角线上移动它们。

这是我的全部代码。

public Transform Objectup;
public Transform Objectdown;
public Transform Objectright;
public Transform Objectleft;
public DirectionGameObject direction;
public int speed = 2;

public enum DirectionGameObject
{
    Right,
    Left,
    Up,
    Down
}
// Start is called before the first frame update
void Start()
{
    direction = SortdirectionGameObject(direction);
}
// Update is called once per frame
void Update()
{
    Destroy();
    if(direction == DirectionGameObject.Right)
    {
        transform.Translate(Vector3.right * Time.deltaTime * speed);
        if(transform.position.x >= Objectright.position.x)
        {
            direction = SortdirectionGameObject(direction);
        }
    }
    if(direction == DirectionGameObject.Left)
    {
        transform.Translate(Vector3.left * Time.deltaTime * speed);
        if(transform.position.x <= Objectleft.position.x)
        {
            direction = SortdirectionGameObject(direction);
        }
    }
    if(direction == DirectionGameObject.Up)
    {
        transform.Translate(Vector3.up * Time.deltaTime * speed);
        if(transform.position.y >= Objectup.position.y)
        {
            direction = SortdirectionGameObject(direction);
        }
    }
    if(direction == DirectionGameObject.Down)
    {
        transform.Translate(Vector3.down * Time.deltaTime * speed);
        if(transform.position.y <= Objectdown.position.y)
        {
            direction = SortdirectionGameObject(direction);
        }
    }
}
private DirectionGameObject SortdirectionGameObject(DirectionGameObject maindirection)
{
    DirectionGameObject directionSorted = maindirection;
    do{
        int newDirection = Random.Range((int)DirectionGameObject.Right, (int)DirectionGameObject.Down + 1);
        directionSorted = (DirectionGameObject)newDirection;
    } while (maindirection == directionSorted);
    return directionSorted;
}
void Destroy()
{
    Destroy(gameObject,120.0f);
}

当我按 G 和 V 时,我需要在控制台上显示它们的颜色和位置。

您要查找的游戏对象的颜色属性驻留在渲染器组件的材质中。

可以通过以下方式引用它:

gameObject.GetComponent<Renderer>().material.color

为了获取游戏对象的渲染器组件,您必须具有对它的引用,例如:

GameObject object1;
GameObject object2;

然后,您可以像这样获取每个对象的颜色:

Color color1 = object1.GetComponent<Renderer>().material.color;

然后,您可以像这样检查颜色的值:

if (color1 == Color.red){
    // Do something
}

或者,如果要向控制台显示其颜色:

Debug.Log(color1);

颜色存储为 4 个浮点值,因此如果要输出"颜色为红色"或"颜色为蓝色",则需要进行等效性检查,就像我上面提供的"//做某事"注释一样。

我不知道

有没有办法获取游戏对象的材质颜色但是你可以将游戏对象命名为它的颜色,因为颜色是静态的并且不会改变并且你可以使用 Gameobject.name 方法,并且为了定位其他游戏对象你可以使用transform。看

最新更新