ぼっちプログラマのメモ

UE4とかUE5とかについて書いたり書かなかったり。

Unity勉強 六日目(STG作成開始・シングルトン)

そろそろダレかける時期なので、簡単なSTGを作成しながら学習


とりあえず、自機を準備

アセットストアから無料のこの子をチョイス
https://www.assetstore.unity3d.com/#/content/354

…かわいい(*´∀`)

キー入力による移動を実装

2日目のコードを使ってサクッと移動を実装

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
	
	public float Speed = 5000.0f;
	
	// ユーザ入力
	public float inputH = 0.0f;
	public float inputV = 0.0f;
	
	// Use this for initialization
	void Start ()
	{
	
	}
	
	// Update is called once per frame
	void Update ()
	{		
		// ユーザ入力
		// 左右
		inputH = Input.GetAxisRaw ("Horizontal");
		// 上下
		inputV = Input.GetAxisRaw ("Vertical");
		
		// 移動処理
		rigidbody.velocity = new Vector3( inputH, 0.0f, inputV ) * Speed;
	}
}

rigidbody.addForceの方だと色々調整が面倒なので、rigidbody.velocityを使っとく。
rigidbody.velocityは1秒間当たりの移動量を設定するらしい。Time.deltaTimeいらず!

シングルトンなクラスを用意

今後必要になるので早めに用意しておく。
とりあえず検索して出てきたサイトの中から、簡単そうなコードをパクる
http://iphone3gsapplication.blog129.fc2.com/blog-entry-153.html
http://akabosi.tumblr.com/post/38553973811

using UnityEngine;
using System.Collections;

public class Singleton : MonoBehaviour
{
	private Singleton instance = null;

	void Awake ()
	{
		if (instance == null) {
			instance = this;
			DontDestroyOnLoad (gameObject);	// シーン遷移での破棄を防ぐ
			
			//シングルトン処理
 			//自分の名前を一時的に変更する(元の名前は保持しておく)
			var nameOld = gameObject.name;
			gameObject.name = nameOld + "(SingletonCheck)";
			
			//元の名前のオブジェクトがあったら自殺する
			var obj = GameObject.Find (nameOld);
			if (obj != null) {
				Destroy (gameObject);
				Debug.LogError("シングルトンオブジェクト" + this + "を多重生成しようとしています。");
			} else {
				//無かったら自分の名前を元に戻す
				gameObject.name = nameOld;
			}
		} else {
			Destroy (gameObject);
			Debug.LogError("シングルトンオブジェクト" + this + "を多重生成しようとしています。");
		}
	}
}

このコードをベースに改造していこうっと…気が向いた時に

別オブジェクトのスクリプトにアクセスする方法

シングルトンを実装したはいいが、そのスクリプトのメンバを
外部から参照する方法が分からなかったので検索
https://sites.google.com/site/sunflowerlaboratory/unitynoto/arusukuriputokarabienoobujekutonokonponentohenoakusesu

public GameObject GameMainObj = null;
public Singleton GameMainScript = null;

GameMainObj = GameObject.Find("GameMain");
GameMainScript = GameMainObj.GetComponent<Singleton>( );

でけたでけた

色々と失敗

・豪勢に剛体付きCubeで自機の移動範囲を設定しよう!
 → そういや、敵に剛体付けるし面倒なことになるんじゃ…却下(Cube設置後に)
   …特定の属性持ちなら剛体同士の当たりを無視とか、そんな機能がありそうだけど

・Planeに剛体つけたらエラー!な、なんで?
エラーメッセージ

「Actor::updateMassFromShapes: Compute mesh inertia tensor failed for one of the actor's mesh shapes! 
 Please change mesh geometry or supply a tensor manually!」

原因・解決法:http://blog.be-style.jpn.com/article/53389562.html