Rundown 好吧,家伙和gals需要一点帮助。基本上我是从一个开放的位置预制一个健康包。经过一段时间后,我试图摧毁HealthPack,如果它没有拿起,则将bool healthPackExist设置为false,并在免费位置实例化另一个HealthPack。销毁由脚本Unity3d C#中的脚本创建的对象#
问题: 当我试图访问游戏对象被实例化我最终要么摧毁整个父层次结构或只是擦脚本出来。
解决方案 我试图破坏根对象,搜索创建的对象的名称,添加标签的对象(健康套餐),并寻找它总是得到错误。
代码如下:
public GameObject healthPackPrefab;
public GameObject health;
private float healthTimer;
private bool healthExist;
// Use this for initialization
void Start()
{
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;
}
// Update is called once per frame
void Update()
{
//first check to see if a health pack exist, if not call method to spawn a health pack
//otherwise check to see if one exist and if it does is it's timer created with it
//has been passed by Time.time (returns game clock time), if yes destroy the created
//health pack.
if (healthExist == false)
{
spawnUntilFull();
}
else if (healthExist == true && Time.time > healthTimer)
{
//Error occuring here when trying to destroy
//Destroy(transform.root.gameObject) //destroys script, object scripts on, and prefab
Destroy(this.gameObject); //does same as Destroy(transform.root.gameObject
healthExist = false;
}
}
Transform NextFreePosition()
{
//free space
foreach (Transform childPositionGameObject in transform)
{
//if no health packs located return location of child object to spawn new health pack
if (childPositionGameObject.childCount == 0)
{
return childPositionGameObject;
}
}
return null;
}
void spawnUntilFull()
{
//returns next free position in space
Transform freePosition = NextFreePosition();
//if free slot is available
if (freePosition && healthExist == false)
{
//instantiates health object and places it in scene at coordinates received from
//freePosition
health = Instantiate (healthPackPrefab, freePosition.position, Quaternion.identity) as GameObject;
//spawns enemy onto a position under the Parent (Enemy Formation)
health.transform.parent = freePosition;
//set bool to true to stop spawning
healthExist = true;
//seat HealthTimer to 5 seconds after creation for use in Update method
healthTimer = Time.time + 5.0f;
}
}
你只是试图创建一个对象?你的代码'打开位置'和'spawnUntilFull'使得它听起来像你想生成多个,但你的代码似乎只允许创建一个,因为你将healthExist更改为true。 –
我现在将它打开,根据时间和敌人的情况随机创建它们。这就是为什么当它被玩家拾起(不同的脚本)时,它会被销毁并更改为healthExist = false,然后在上面的脚本中,当定时器耗尽时,它应该被销毁以允许稍后再创建。 – Phillipv20