0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity備忘録、STG制作4:弾の消去に関する一考察

Posted at

※この記事は2016年当時に在籍していた某社内での(略)、社内技術ブログを作ろうと提案した言い出しっぺが三日坊主野郎だったためにブログの存在自体が埋もれてしまう事態となった。(続く)

背景

Q:画面外に消えていったオブジェクトはどうなるか?
A:そのまま残り続ける。

つまり、不要なオブジェクトであれば、画面外に消えた時に何らかの削除処理を実装しないとメモリを食い潰すことになる。

方法1:OnBecameInvisible()を使う

オブジェクトがカメラ外(=画面外)に消えた時にコールされるOnBecameInvisible()というコールバック関数がある。こんな感じで使えばよい。

void OnBecameInvisible() {
    Destroy (this.gameObject);
}

OnBecameInvisible()を使う上での注意点

(1) カメラ内からカメラ外へと消えた時にのみコールされる。最初からカメラ外にオブジェクトがあった場合はコールされない。
(2) Unity Editor上で動作させた場合、カメラ外に出ても消えない。理由は不明だが、この時だけは編集画面の外枠が対象となる模様。下記図をご参考。
01.png

方法2:カメラ範囲を取得してカメラ外かどうかを判定する

http://bribser.co.jp/blog/delete-object-out-of-camera/ (※リンク切れ)
このブログに記載のコードを丸パクリする。暇な人は解析してください。
ブログがいつまであるか分からないので、ソースコードを転記しておく。
(2018/1/12追記):オリジナルではないので、コード公開に不都合があるとの指摘があれば削除します。

autoDeleteOutOfScreen.cs
using UnityEngine;
using System.Collections;

public class autoDeleteOutOfScreen : MonoBehaviour {
	public Camera _setCamera;
	
	//Margin
	float margin = 0.05f; //マージン(画面外に出てどれくらい離れたら消えるか)を指定
	float negativeMargin;
	float positiveMargin;
	
	void Start ()
	{
		if (_setCamera == null) {
			_setCamera = Camera.main;
		}
		
		negativeMargin = 0 - margin;
		positiveMargin = 1 + margin;
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (this.isOutOfScreen()) {
			Destroy (gameObject);
		}
	}
	
	bool isOutOfScreen() 
	{
		Vector3 positionInScreen = _setCamera.WorldToViewportPoint(transform.position);
		positionInScreen.z = transform.position.z;
		
		if (positionInScreen.x <= negativeMargin ||
		    positionInScreen.x >= positiveMargin ||
		    positionInScreen.y <= negativeMargin ||
		    positionInScreen.y >= positiveMargin)
		{
			return true;
		} else {
			return false;
		}
	}
}

実行結果より、カメラからちょっと出たところで弾が消えていることが確認できる。
02.png

その他

今回は採用しないが、こんな方法もあるらしい。
http://ftvoid.com/blog/post/653
画面内の表示領域の当たり判定を持つオブジェクトを一つ用意し、このオブジェクトに当たらなければオブジェクト破棄されるようにする。

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?