C#/ Unity - 我如何比较字符串变量?

时间:2016-05-11 19:00:37

标签: c# string variables unity3d compare

如何将第一个对象中的字符串变量与Unity中第二个对象中的字符串进行比较? 我的问题有截图:https://onedrive.live.com/redir?resid=C7A243435ECAB1C0!2948&authkey=!ADg0Uh6Ih1cJKd8&ithint=folder%2cpng

感谢您的回答。

PlayerMove:

using UnityEngine;
using System.Collections;

public class PlayerMove : MonoBehaviour {

Vector3 pos;
public float speed;
char mv;
string ObstacleTypePlayer;


void Start () {

    pos = transform.position;

}

void Update () {

    if (Input.GetKeyDown(KeyCode.LeftArrow) && mv != 'l')
        pos.x -= speed;

    if (Input.GetKeyDown(KeyCode.RightArrow))
        pos.x += speed;

    if (Input.GetKeyDown(KeyCode.UpArrow) && mv != 'u')
        pos.y += speed;

    if (Input.GetKeyDown(KeyCode.DownArrow) && mv != 'd')
        pos.y -= speed;


    transform.position = pos;
}


void OnTriggerEnter2D(Collider2D col)
{

    if (col.CompareTag("obstacle"))
    {
        col.gameObject.GetComponent<Obstacle>().Move(true);
        print("obstacle");
    }

    if (col.gameObject.GetComponent<Obstacle>().ObstacleType == "big left") // not true, but if Obstacle.ObstacleType == "big left"
    {


        if (col.CompareTag("side_up"))
            NotMove('d');

        else if (col.CompareTag("side_down"))
            NotMove('u');

        else if (col.CompareTag("side_right"))
            NotMove('l');

    }

}

void OnTriggerStay2D(Collider2D col)
{

}


void OnTriggerExit2D(Collider2D col)
{
    if (col.CompareTag("side_up"))
        NotMove(' ');

    else if (col.CompareTag("side_down"))
        NotMove(' ');

    else if (col.CompareTag("side_right"))
        NotMove(' ');

}

char NotMove(char z)
{
    mv = z;
    return mv;
}

}

障碍:

Vector3 pos;
GameObject player;
bool move = false;
public string ObstacleType = "aaaa";

void Start () {
    player = GameObject.FindWithTag("Player");
    pos = transform.position;
}
public bool Move(bool mo)
{
    if(mo)
        move = true; 
    return move;
}

void Update () {



    if (ObstacleType == "big left" && Input.GetKeyDown(KeyCode.LeftArrow))
        move = false;

    if (move)
        transform.position = player.transform.position;

}

1 个答案:

答案 0 :(得分:2)

与调用Move()函数的方式完全相同:

col.gameObject.GetComponent<Obstacle>().ObstacleType == "big left"

编辑:
据我所知,你有Obstacle游戏对象有一些子对象。他们每个人都拥有自己的标记(obstacleside_upside_downside_right)和对手。由于上面的代码为您提供NullReferenceException,因此唯一可能的原因是只有主对象具有Obstacle.cs组件,而不是子组件,因此上述行失败。

编辑2:
如果只有父级应该有脚本,那么该行应该是这样的:

col.transform.root.GetComponent<Obstacle>().ObstacleType == "big left"