spawn / un-spawner需要有这个对象签名,这是在高级API中定义的。
传递给spawn
函数的assetID可以在NetworkIdentity.assetId
中找到,用于预制,它自动填充。动态assetID的注册处理方式如下:
// generate a new unique assetId
NetworkHash128 creatureAssetId = NetworkHash128.Parse("e2656f");
// register handlers for the new assetId
ClientScene.RegisterSpawnHandler(creatureAssetId, SpawnCreature, UnSpawnCreature);
// get assetId on an existing prefab
NetworkHash128 bulletAssetId = bulletPrefab.GetComponent<NetworkIdentity>().assetId;
// register handlers for an existing prefab you'd like to custom spawn
ClientScene.RegisterSpawnHandler(bulletAssetId, SpawnBullet, UnSpawnBullet);
// spawn a bullet - SpawnBullet will be called on client.
NetworkServer.Spawn(gameObject, creatureAssetId);
public GameObject SpawnBullet(Vector3 position, NetworkHash128 assetId)
return (GameObject)Instantiate(m_BulletPrefab, position, Quaternion.identity);
}
public void UnSpawnBullet(GameObject spawned)
{
Destroy(spawned);
}
使用自定义spawn
函数时,有时可以在不破坏对象的情况下取消对象。这可以通过调用NetworkServer.UnSpawn
完成。这会导致将消息发送给客户端以取消生成该对象,以便在客户端上调用定制的未生成函数。调用此函数时,对象不会被销毁。
请注意,在主机上,不会为本地客户端生成对象,因为它们已经存在于服务器上。所以没有派生处理函数会被调用。
使用自定义spawn处理程序设置对象池
要使用此管理器,请执行以下操作
• 这适用于像“ 入门指南”中那样的场景。
• 创建一个名为“SpawnManager”的新空游戏对象
• 为上面的代码创建一个SpawnManager脚本,并将其添加到新的SpawnManager对象中
• 将想要多次产生的预制件拖到预制字段并设置大小(默认值为5)。
• 在玩家移动脚本中设置对spawn管理器的引用
SpawnManager spawnManager;
void Start()
{
void Update()
{
if (!isLocalPlayer)
return;
var x = Input.GetAxis("Horizontal")*0.1f;
var z = Input.GetAxis("Vertical")*0.1f;
transform.Translate(x, 0, z);
if (Input.GetKeyDown(KeyCode.Space))
{
// Command function is called on the client, but invoked on the server
CmdFire();
}
}
自动销毁显示对象如何返回到池中,并在再次启动时重新使用。