简体   繁体   English

Unity:碰撞时获取对象状态

[英]Unity: get object state on collision

using Unity3d 4.1.2 and C# Mono. 使用Unity3d 4.1.2和C#Mono。

I have an object (player) that contains this script: 我有一个包含此脚本的对象(播放器):

string[] colors = new string[] {"Red", "Blue", "Green", "Yellow", "Black", "Purple", "Pink", "Orange"};
public string joeColor;

// Use this for initialization
void Start () 
{
    SetColorState();
}

// Update is called once per frame
void Update () 
{

}

public void SetColorState()
{
    joeColor = colors[Random.Range(0, 7)];
}

void OnCollisionEnter(Collision obj)
{
    PlatformMove platform = new PlatformMove();
    platform = obj;
    if(platform.platformColor.ToString() == joeColor.ToString())
    {
        Debug.Log("COLOR MATchED!!!  Joe = " + joeColor.ToString() + " Platform COlor = " + platform.platformColor.ToString());
    }
}

What I want to do is detect a collision on a platform object. 我想要做的是检测平台对象上的碰撞。 Then get a method from that object (platform color) and if it same as my player object then = true. 然后从该对象(平台颜色)获取一个方法,如果它与我的播放器对象相同,那么= true。

As you can see the script above wont work, just been messing around seeing what would happen. 正如您所看到的,上面的脚本无法正常工作,只是一直在看看会发生什么。

The platform object is randomly instantiated in the game, random color as well. 平台对象在游戏中随机实例化,也是随机颜色。 So I need to detect that specific platform and then get its color state. 因此,我需要检测特定平台,然后获得其颜色状态。 What do I need to do? 我需要做什么?

Here is how to extract a component: 以下是如何提取组件:

void OnCollisionEnter(Collision obj)
{
    PlatformMove platform = obj.gameObject.GetComponent<PlatformMove>();
    if(platform != null){
        if(platform.platformColor.ToString() == joeColor.ToString()) {
            //... do stuff
        }
    } else {
        //... collision object did not have a PlatformMove component.
    }
}

It appears you know how you want to handle the color comparison but if you anticipate a lot of collisions I would recommend switching from storing platformColor as a string to using an enum instead. 您似乎知道如何处理颜色比较,但如果您预计会发生很多碰撞,我建议您将platformColor作为string为使用enum

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

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