LoginSignup
23

More than 3 years have passed since last update.

初心者用UnityでC#のスニペット集

Last updated at Posted at 2016-03-30

すぐ忘れるのでここに書き記しておきます。
プログラミングはできるけどUnityのC#知らないという方にも多少参考になると思います。

ログを出す

log
Debug.Log("Hello, world!");
print("hoge");//これもいける

配列

array
GameObject[] objects = new GameObject[100];
//objects.Length==100
List
//jsっぽい配列、動的な追加ができる
using System.Collections.Generic;

List<GameObject> objects = new List<GameObject>();
objects.Add( hoge );//push的なやつ
Debug.Log( objects.Count );//Length的なやつ

配列いろいろある
http://unitygeek.hatenablog.com/entry/2014/10/09/165352

for文

for
for (int i = 1; i <= 5; i++)
{
    Debug.Log(i);
}
foreach
foreach (var n in array)
{
    Debug.Log(n);
}

乱数

random
float r = Random.value;//0-1
float r2 = Random.Range(0,999);//0-999の間でfloatのrandom

入力系

mouse
    void Update () {

        //スクリーン上のmouse位置の比率。左下が(0,0);
        float mouseX = Input.mousePosition.x/Screen.width;
        float mouseY = Input.mousePosition.y/Screen.height;

        //クリック
        if (Input.GetMouseButton(0)) {
            print("左ボタンが押されている");
        }
        if (Input.GetMouseButton(1)) {
            print("右ボタンが押されている");
        }
        if (Input.GetMouseButton(2)) {
            print("中ボタンが押されている");
        }       
    }
keyboard
    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow)) {
            print("右矢印キーが押されている");
        }
        if (Input.GetKeyDown(KeyCode.A)) {
            print("押下された瞬間だけ");
        }
    }

KeyCodeはhttp://docs.unity3d.com/ScriptReference/KeyCode.html
を見よう。

MonoBehaviourで定義されているメソッドのメモ

monobehaviour
void Start(){} //
void Awake(){} //Startより前によばれるやつ
void Reset(){} //デフィルト値にリセット
void Update(){} //毎フレーム呼ばれる
void LateUpdate(){}//毎フレームの終わりの方に呼ばれる?カメラの計算などはこれがいい?

動的にgameObjectインスタンス生成し、子供にする

instantiate
public GameObject Fuga;//GUI上でセット
void Start() {
    var pos = new Vector3();
    var rot = Quaternion.Euler(0,0,0);//オイラー角をQuaternionに。
    GameObject hoge = Instantiate (Fuga, pos, rot) as GameObject;
    hoge.transform.parent = gameObject.transform;//gameObjectの子供にする。

    //消す時は Destroy(hoge);
}

親から子供たちを取得

for文で。

getChildren
foreach (Transform child in transform)
{
    //child is your child transform
    Debug.Log ("Child[" + count + "]:" + child.name);
    Debug.Log ( child.gameObject );
    count++;
}

名前を指定して。

getChild
obj1 = transform.FindChild ("name1").gameObject;
obj2 = transform.FindChild ("name2").gameObject;
obj3 = transform.FindChild ("name3").gameObject;

プリミティブを動的生成&マテリアル動的生成

instantiate
GameObject emptyObj = new GameObject("object name");
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.parent = transform;
//material
Material material = new Material(Shader.Find("Unlit/Color"));
material.color = Color.red;
cube.GetComponent<Renderer>().material = material;

GameObjectの位置の更新

setPos
//直接だとダメっぽいので1回変数にいれる
Vector3 p = transform.position;
p.x = 10 * Random.value;
p.y = 10 * Random.value;
p.z = 10 * Random.value;
transform.position = p;

GameObjectの回転

setPos
//0,0,1f の軸で、 0.2f回転
transform.Rotate (new Vector3(0, 0, 1f), 0.2f);

//オイラー角でセット
transform.rotation = Quaternion.Euler(90, 30, 10);

コンポーネントを取得する

GetComponent
//例えばTransform取得。
//ふつうはtransform or gameObject.transformで取得する
Transform t = gameObject.GetComponent<Transform>();

//例えばMeshFilter取得
Mesh mesh = gameObj.GetComponent<MeshFilter>().mesh;//Mesh取得

ちなみにMonoBehaviourクラスで以下の3つは同じ意味。GetComponetしなくてもtransformはしょーっとカット的に用意されている。

Debug.Log(gameObject.GetComponent<Transform>().position);
Debug.Log(gameObject.transform.position);
Debug.Log(GetComponent<Transform>().position);
Debug.Log(transform.position);

オブジェクトを消す

visible
gameObject.SetActive(false);
//GameObject.activeSelf で true/false 状態確認。

表示だけを消す場合

visible
//rendererコンポーネントをオフに
GetComponent<Renderer>().enabled = false;

delay

invoke
Invoke("MethodName", 5); //5秒後にMethodNameメソッドを実行する
//CancelInvokeというのもある

callback

callback
public Systenm.Action _callback;

publid void SetCallback(Systenm.Action callback){
_callback=callback;
//実行する場合は
//_callback();
}

音を鳴らす

AudioSourceコンポーネントをgameObjectにくっつけて、clipにAudioClip(mp3とかをアセットに入れとくとこれになる)を入れる。

sound
using UnityEngine;
using System.Collections;

namespace sound{
    public class SoundPlayer : MonoBehaviour {

        //uiからmp3をぶち込む
        public AudioClip audioClip1;
        public AudioClip audioClip2;
        public AudioClip audioClip3;

        private AudioSource audioSource;

        void Start () {
            audioSource = gameObject.GetComponent<AudioSource>();
            audioSource.clip = audioClip1;
            audioSource.Play();
        }

        void Update () {
            //print( audioSource.time );//時間取得
        }
    }
}

時間・日付を取得する

changeScene
using System;
DateTime hoge = DateTime.Now;
Debug.Log( "H"+hoge.Hour );
Debug.Log( "M"+hoge.Minute );
Debug.Log( "S"+hoge.Second );

シーンを切り替える

changeScene
using UnityEngine.SceneManagement;
SceneManager.LoadScene("Main");

5.3からの機能
http://b-shiki.hatenablog.com/entry/2016/01/02/223509

クラスを書く

quatenion演算メモ

ライトの影響を受けないテクスチャ

シングルトンを使う

JSONを扱う

5.3から標準で使えるらしい
http://qiita.com/toRisouP/items/53be639f267da8845a42

画像のピクセルの色を取得

インスペクターにボタンを設置

その他参考

Unityを触り始めたのでメモ(C#編)
http://qiita.com/edo_m18/items/e15b679596abfcad8f32

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
23