Reputation: 428
I am developing an Android game using Unity and in my game I am instantiating objects which move in x direction visible to camera and when they leave camera view they are destroyed, to stop slowing the processing and taking memory. It works fine, but when my player moves in vertical direction there are objects which are instantiated but they are out of camera view, and then they are not destroyed. Therefore, when my objects are out of camera view I want to stop invokeRepeating. Here is the code which works only when objects are in view.
public GameObject colorbar;
public Vector2 velocity = new Vector2(-3, 0);
void Start () {
GetComponent<Rigidbody2D>().velocity = velocity;
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
InvokeRepeating("CreateObstacle", 1f, 1.8f);
}
// Update is called once per frame
void Update () {
}
public void OnBecameInvisible()
{
Destroy(colorbar);
Debug.Log ("Color bar is Destroyed");
}
void CreateObstacle()
{
Instantiate(colorbar);
Debug.Log ("Color bar instantiating");
}
}
Upvotes: 0
Views: 1674
Reputation: 10701
You can check if the renderer is visible when you create the object:
http://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
void Awake(){
if(GetComponent<Renderer>().isVisible == false){
Destroy(this.gameObject);
}
}
But best would be to avoid creation if not needed, so you could get the point where you object should be created, then convert to screen point:
http://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
if the value is within the boundaries of the screen, then you good. You could also linecast from position to camera and if there is nothing stopping the cast, you are double good to create.
Vector3 pos = ObjectPos;
Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
if(screenPos.x > 0 && screenPos.x < Camera.main.pixelWidth &&
screenPos.y > 0 && screenPos.y < Camera.main.pixelHeight && screenPos.z > 0)
{
if (Physics.Linecast(pos, Camera.main.transform.position) == false){
// Create object
}
}
Keep in mind this is using the position of the object. If your object is large, then the position may be outside while some edges would be inside. The best would be to check for each vertex of the mesh. But if you have a complex mesh, that might get expensive, if you deal with a cube then maybe.
Upvotes: 2