我想让玩家创建一个自动射击一些“佳能球”的“佳能基地”,但是(在使用一些Debug.Log尝试之后)我可以说,只有在实例化“佳能球”之前进行编码被执行:(
它被称为多人游戏。
using UnityEngine.Networking;
public class PlayerScript : NewtworkBehaviour
{
public GameObject canonBase;
public Transform canonBaseSpawnPoint;
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
CmdCreateCanon();
}
}
[Command]
void CmdCreateCanon()
{
GameObject _canonBase = Instantiate(canonBase.gameObject,
canonBaseSpawnPoint.transform.position, Quaternion.identity);
_canonBase.transform.rotation = canonBaseSpawnPoint.transform.rotation;
NetworkServer.SpawnWithClientAuthority(_canonBase, connectionToClient);
}
}
//other script:
using System.Timers;
using UnityEngine.Networking;
public class CanonScript : NetworkBehaviour
{
public GameObject canonBall;
public Transform canonSpawnPoint;
public int shootAmount;
void Start()
{
shoot = new Timer(shootTime * 1000);
shoot.Elapsed += Shoot_Elapsed;
shoot.Start();
}
void Shoot_Elapsed(object sender, ElapsedEventArgs e)
{
for (int i = 0; i < shootAmount; i++)
{
//Code written down here gets executed
GameObject _canonBall = Instantiate(CanonBall.gameObject, canonSpawnPoint.transform.position, Quaternion.identity) as GameObject;
_canonBall.transform.rotation = canonSpawnPoint.transform.rotation;
//Code written down here doesn't get Instantiated
}
}
}
要添加:
使用Debug.Log(),我发现for循环中的代码已执行,但是canonBall-Instantiation-code后面的所有内容均未执行。
canonBall与BulletScript链接在一起,因此可以移动(这应该很好,因为它也可以在其他对象上使用。)
“ ... SpawnPoint”是具有禁用的Mesh Renderer和Box Collider的多维数据集,并已附加到实例化另一个对象所需的GameObject( Player-> canonBase; canonBase-> canonBall >)
编辑:目前我认为由于for循环等原因,它不起作用? (因为让播放器直接创建canonBall(没有计时器和for循环部分)效果很好)
答案 0 :(得分:0)
您可以像这样将Start
制成协程。
using System.Collections;
using UnityEngine;
public class Cannon : MonoBehaviour {
[SerializeField] private GameObject _cannonballPrefab;
private IEnumerator Start () {
yield return new WaitForSeconds (2);
Instantiate (_cannonballPrefab);
}
}
实例化带有此脚本的大炮时,延迟2秒后会创建一个炮弹。