单击实例化对象并返回数字C#(UNITY)

时间:2018-07-24 09:22:16

标签: c# unity3d

我实际上不知道该在Google上搜索什么,所以我直接到达了这里,对此我感到抱歉。我的问题是我有Instantiate()个对象

public void InstantiateObject(){
//the list has 5 objects in it .
  for (int i = 0; i < list.Count; i++)
  {
    GameObject o = Instantiate(lobby_object) as GameObject;
    o.transform.SetParent(pos_lobby_object);
    o.transform.localScale = Vector3.one;

    o.transform.name = "spr_boards " + lobby_object_no;

    o.transform.localPosition = new Vector3(0, 0, 0);
    NGUITools.SetActive(o, true);
  }
}

输出为

  

spr_boards 1

     

spr_boards 2

     

spr_boards 3

     

spr_boards 4

     

spr_boards 5

我在另一个脚本上有一个点击事件

public void InstantiateTheObject(){
      fromAnotherScript.InstantiateObject();
}

然后将此InstantiateTheObject拖动到检查器上的按钮

现在我要单击此对象之一并返回它们的编号 但我不知道该怎么做。

编辑:

更多信息

例如,如果我单击实例化的spr_board 1,则必须记录例如“ this is object 1”;

然后,例如,如果我单击spr_board 2,则必须记录例如“ this is object 2`;

我尝试过

public void InstantiateTheObject(){
   Debug.Log("objects number is : " + lobby_object_no);
      fromAnotherScript.InstantiateObject();
}

但是问题是它总是获得我的last的最后一个值。这不取决于我在实例化对象上单击的内容。

1 个答案:

答案 0 :(得分:0)

如何从变换名称获取数字:

RaycastHit hit;
 void Update()
 {
    if (Input.GetMouseButtonDown (0))
    {
       Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
       if(Physics.Raycast(ray, out hit))
       {
          GameObject ourObject = hit.collider.gameObject;

          string prefix = "spr_boards ";
          string txtNum = ourObject.transform.name.Remove(0, prefix.Length);
          int number = Int32.Parse(txtNum);

          Debug.Log ("this is object " + number);
       }
    }
 }

int number是1到5之间的数字