[英]Can I pass diferent type parameter to the same function?
/*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;
}
}
如您所见,该函数采用3个类型的参数: GameObject
, Transform[]
和float
。
如何使我可以提供类型Transform
而不是Transform[]
。
更具体地说,如何使函数接受更多不同类型的参数,而实际上不需要传递每个参数:
因此,例如,我可以使用不同的类型来调用函数,例如:
`SpawnPylon(GameObject ,Transform[] ,float`)
然后执行以下操作:
SpawnPylon(GameObject ,Transform ,float)
或这样做:
SpawnPylon(GameObject, string, float)
有没有办法做到这一点?
您可以重载您的方法以具有不同的签名,然后调用原始签名。 例如:
void SpawnPylon(GameObject whatSpawn, Transform whereSpawn, float spawnDistance) {
SpawnPylon(whatSpawn, new Transform[] {whereSpawn}, spawnDistance);
}
如果要更改方法签名中的类型,则必须重载方法:
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);
如果要传递参数,请输入所需的参数。使用对象。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.