根据多维数组(C#UNITY)的值实例化预制件

时间:2018-06-27 05:54:42

标签: c# unity3d

大家好,我只是想问问是否可以根据您的Multidimensional Array的值实例化预制件,例如我有此数据。

  

10 20 11

     

00 21 10

     

00 00 00

     

00 00 00

     

00 00 00

     

00 00 00

现在这是我的代码

string road1 = "";
    for (int y = 0; y < bsb.ArrBigRoad.GetLength(0); y++)
    {
        for (int x = 0; x < bsb.ArrBigRoad.GetLength(1); x++)
        {
            road1 += string.Format("{0:D2}", bsb.ArrBigRoad[y, x] / 100);
            road1 += ".";
        }
        road1 += "\n";
    }
Debug.Log(road1);

现在我正在像这样使用Label打印它

[SerializeField] public UILabel info_scores_bigroad;

info_scores_bigroad.text = road1;

2 个答案:

答案 0 :(得分:1)

我建议您采用2种不同的方式:

1。创建一个Switch / Enum,并使用实例化可能的预制件,例如:

//Possible Prefabs, link them on editor
public GameObject car;
public GameObject road;
public GameObject truck;

//Used to instantiate the new object
public GameObject newObject;

switch(road1){
    case 'car':
        newObject = Instantiate(car);
        break;
    case 'road':
        newObject = Instantiate(road);
        break;
    case 'truck':
        newObject = Instantiate(truck);
        break;
    default:
        print("error: prefab not exists");
        break;
}

2。使用资源文件夹

//Used to instantiate the new object
public GameObject newObject;

newObject = (GameObject)Instantiate(Resources.Load(road1));

请记住,对于案例2,您需要创建一个名为Resources的文件夹,并在该文件夹上找到预制件。

答案 1 :(得分:1)

感谢Lotan我所做的就是这样

SetScore.cs

public void Set( int score )
{
    int who = score / 1000;

    if (who == 1)
    {
        NGUITools.SetActive(obj_player, true );
        NGUITools.SetActive(obj_banker, false);
    }
    else if( who == 2)
    {
        NGUITools.SetActive(obj_player, false);
        NGUITools.SetActive(obj_banker, true);
    }
    else
    {
        NGUITools.SetActive(obj_player, false);
        NGUITools.SetActive(obj_banker, false);

        NGUITools.SetActive(lbl_tie_no.gameObject, false);
        NGUITools.SetActive(spr_playerPair.gameObject, false);
        NGUITools.SetActive(spr_bankerPair.gameObject, false);
        return;
    }
}

然后像这样对我的二维数组上的内容进行图案化

Game.cs

public IEnumerator ShowScoreBoard_BigRoad(int[,]  arrBigRoad)
{
    NGUITools.DestroyChildren(pos_bigroad);

    for (int y = 0; y < arrBigRoad.GetLength(0); y++)
    {
        for (int x = 0; x < arrBigRoad.GetLength(1); x++)
        {
            int score = arrBigRoad[y, x];

            GameObject o = Instantiate(prefab_bigroad) as GameObject;
            o.transform.SetParent(pos_bigroad);
            o.transform.localScale = Vector3.one;

            o.transform.localPosition = new Vector3(x * SX_, y* SY_, 0);
            NGUITools.SetActive(o, true);

            // 1011, 2000, 3000, 

            bsbBigRoad s = o.GetComponent<bsbBigRoad>();
            s.Set(score);
        }
    }

    yield break;
}

但是还是谢谢你。 :)