Sam*_*tty 1 c# android unity-game-engine destroy
林做一个2D游戏在Unity 2D(4.3),我需要销毁时,这些组合屋去关闭屏幕实例化的组合屋.我已经编写了一些代码来生成Objects,但是当我们离开屏幕时我想要删除那些预制件.这是我到目前为止编写的代码.
要生成预制件(C#):
void Update () {
float y = Random.Range(-4.53f, 2.207f);
if(x < 2000) {
Instantiate(obstacle, new Vector3(y, x * 6.0f, 0),Quaternion.identity);
x++;
}
//Debug.Log(x);
}
Run Code Online (Sandbox Code Playgroud)
要销毁预制件(C#):
/*************************************************************************************************
* GET INSTANTIATED OBSTACLE
* AND DESTROY IT ON EXIT
* TO SAVE MEMORY
**************************************************************************************************/
GameObject clone = (GameObject)Instantiate (obstacle);
/*if(clone.transform.position.y == -11)
{
Destroy(clone);
Debug.Log("Destroy");
}*/
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Destroy(gameObject);
Debug.Log("Destroy");
}
Run Code Online (Sandbox Code Playgroud)
但是,销毁对象的代码不起作用,但也没有出现错误.在预制件离开屏幕后输出"Destroy",所以我知道破坏它们的代码有问题.
谢谢
小智 7
当位置不在相机位置时,您可以制作一个会破坏自身的组件,然后将此组件附加到障碍物上.
void Update() {
float y = Random.Range(-4.53f, 2.207f);
if(x < 2000) {
GameObject clone = (GameObject)Instantiate(obstacle, new Vector3(y, x * 6.0f, 0),Quaternion.identity);
clone.AddComponent(typeof(DestroyMySelf));
x++;
}
}
Run Code Online (Sandbox Code Playgroud)
并且这个组件附着在障碍物上会破坏自我.
public class DestroyMySelf : MonoBehaviour {
void Update() {
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
Destroy(this.gameObject);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14983 次 |
| 最近记录: |