Skip to content

Instantly share code, notes, and snippets.

@gnjo
Forked from maco1028/unitymain.cs
Created September 14, 2021 04:12
Show Gist options
  • Save gnjo/e469baaf53cdd0b50477a9b3d8519efc to your computer and use it in GitHub Desktop.
Save gnjo/e469baaf53cdd0b50477a9b3d8519efc to your computer and use it in GitHub Desktop.
よく使うUnityスクリプト
1.現在のシーン名を判定
if(Application.loadedLevelName == "main"){
scene = true;
}else{
scene = false;
}
2.回転させる
this.transform.Rotate (new Vector3 (0, 0, 5 * Time.deltaTime));
3.オブジェクトの位置
GameObject.transform.position = new Vector3(0,0,0);
4.Prefabをスクリプトからインスタンス化
GameObject t = (GameObject)Instantiate(Prefab,new Vector3(0,0,0),Quaternion.identity);
5.オブジェクトを取得(名前)
GameObject t = GameObject.Find("xxxxx");
6.オブジェクトを取得(タグ名)
GameObject t = GameObject.FindWithTag("xxxxx");
7.オブジェクトの名前
GameObject.name = "xxxxx";
8.オブジェクトに力を加える
player.GetComponent<Rigidbody2D>().AddForce(new Vector2(0.0f, 0.0f),ForceMode2D.Force);
9.オブジェクトを削除
Destroy(GameObject);
10.自分自身の現在の座標
Vector2 ThisPosition;
ThisPosition = this.transform.position;
11.x秒後にオブジェクト削除
Destroy(clone,x);
12.左右に移動
transform.Translate(Vector3.right * moveForce * Time.deltaTime);
13.IsKinematicのオン、オフ
GameObject.GetComponent<Rigidbody2D>().isKinematic = false;
14.シーンをロードする
Application.LoadLevel("xxxxx");
15.オブジェクトがあるかどうか調べる
if(transform.Find("xxxxxxxxxx") == true){
}
16.オブジェクトを非アクティブにする(見えなくする)
GameObject.SetActive(false);
17.効果音を鳴らす
AudioSource.PlayClipAtPoint(AudioClip, transform.position,1.0f);
18.トリガーの処理
private void OnTriggerEnter2D(Collider2D col){
}
19.Resourcesフォルダからオブジェクトの読み込み
GameObject t = (GameObject)Resources.Load ("Prefabs/xxxxxx");
20.マテリアルの反映させる
public Material m; // 追加用のマテリアル
GameObject.GetComponent<Renderer>().material = m;
21.タグのオブジェクトをすべて削除
GameObject[] obstacles = GameObject.FindGameObjectsWithTag("xxxxx");
foreach(GameObject obs in obstacles) {
Destroy(obs);
}
22.乱数
int r;
r = Random.Range(0, 100);
23.Rigidbody2Dに力を加える
GetComponent<Rigidbody2D>().AddForce(new Vector2(x, y));
24.AudioListenerのボリューム調整
AudioListener.volume = 0.0f;
25.イメージコンポーネントを取得
Image images;
images = gameObject.GetComponent<Image>();
26.マウスクリック(タッチ)
// 生成したいPrefab
public GameObject Prefab;
// クリックした位置座標
private Vector3 clickPosition;
// Update is called once per frame
void Update () {
// マウス入力で左クリックをした瞬間
if (Input.GetMouseButtonDown(0)) {
// ここでの注意点は座標の引数にVector2を渡すのではなく、Vector3を渡すことである。
// Vector3でマウスがクリックした位置座標を取得する
clickPosition = Input.mousePosition;
// Z軸修正
clickPosition.z = 10f;
// オブジェクト生成 : オブジェクト(GameObject), 位置(Vector3), 角度(Quaternion)
// ScreenToWorldPoint(位置(Vector3)):スクリーン座標をワールド座標に変換する
Instantiate(Prefab, Camera.main.ScreenToWorldPoint(clickPosition), Prefab.transform.rotation);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment