我可以将不同的类型参数传递给同一个函数吗?

时间:2017-04-22 21:04:26

标签: c# function unity3d

我有一个功能:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (comboBox1.SelectedIndex == -1)
            {
                cstTxtBox.Text = string.Empty;
            }
            else
            {
                cstTxtBox.Text = comboBox1.SelectedItem.ToString();
            }

正如您所看到的,该函数采用3个类型的参数:/*This function spawns a GameObject randomly at another GameObject's position and it takes 3 arguments: Argument 1. type GameObject: the game object that will be spawned. 2. type Transform[]: the GameObject will be spawned at this Transform position. 3. type float: the distance that the camera must travel before the GameObject will be spawned. */ void SpawnPylon(GameObject whatSpawn, Transform[] whereSpawn, float spawnDistance) { bool hasSpawnedPylon = false; if (currPosition != (int)transform.position.z) { if ((int)transform.position.z % spawnDistance == 0) { if (!hasSpawnedPylon) { //this makes the GameObject spawn randomly spawnIndex = Random.Range (0, spawnPoints.Length); //This is instantiationg the GameObject Instantiate (whatSpawn, whereSpawn [spawnIndex].position, whereSpawn [spawnIndex].rotation); //this makes shore that the GameObject is not spawned multiple times at aproximetley the same position. currPosition = (int)transform.position.z; } } } else { hasSpawnedPylon = false; } } GameObjectTransform[]

我怎样才能使float代替Transform

更具体地说,如何使函数接受更多不同类型的参数,而不需要实际传递每个参数:

因此,例如,我可以使用不同类型调用该函数,例如:

Transform[]

然后这样做:

`SpawnPylon(GameObject ,Transform[] ,float`)

或者这样做:

SpawnPylon(GameObject ,Transform ,float)

有办法做到这一点吗?

3 个答案:

答案 0 :(得分:4)

您可以重载方法以使其具有不同的签名,然后调用原始方法。例如:

void SpawnPylon(GameObject whatSpawn, Transform whereSpawn, float spawnDistance) {
  SpawnPylon(whatSpawn, new Transform[] {whereSpawn}, spawnDistance);
}

答案 1 :(得分:1)

如果要更改方法签名中的类型,则必须重载方法:

https://msdn.microsoft.com/en-us/library/ms229029(v=vs.100).aspx

您是否考虑过使用不确定数量的参数?

https://msdn.microsoft.com/en-us/library/ms228391(v=vs.90).aspx

要处理您要求的案例,您班级的界面可能如下所示:

void SpawnPylon(GameObject whatSpawn, float spawnDistance, params Transform[] whereSpawn);
void SpawnPylon(GameObject whatSpawn, float spawnDistance, string whereSpawn);

然后你可以这样称呼它:

SpanPylon(game, distance, where1);

SpanPylon(game, distance, where1, where2);

SpanPylon(game, distance, whereString);

答案 2 :(得分:-1)

如果你想要传递参数类型你想要的..使用对象。

void SpawnPylon (GameObject whatSpawn,object whereSpawn,float spawnDistance)
{

    if(whereSpawn is Transform[])
    {
//put your Transform[] specific codes here
    }

if(whereSpawn is Transform)
    {
//put your Transform specific codes here
    }

if(whereSpawn is String)
    {
//put your String specific codes here
    }

}