6
7

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 1 year has passed since last update.

Unityでよく使う初心者用コードサンプル集

Last updated at Posted at 2022-08-21

0.この記事の目的

Unityのプログラミングを初心者に教える際、ぱっと簡潔なコードがなかったりするので、このへんでまとめておこうと思った。
あくまで初心者用だ、ということに留意してほしい。(もっとこうしたほうが処理が軽い、みたいなのは無視しています)
随時更新して拡張していく予定。

1.当たり判定

Test.cs
using UnityEngine;

public class Test : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision) //なにかにあたった瞬間に呼び出される
    {
        if (collision.gameObject.tag == "Enemy") //Enemyというタグがついている敵に当たったら
        {
            //あたった後の処理を書く
        }
    }
}

2.シーン移動(ゲームクリアとか)

Test.cs
using UnityEngine;
using UnityEngine.SceneManagement; //追記必須

public class Test : MonoBehaviour
{
    private void Start()
    {
        SceneManager.LoadScene("GameScene"); //GameSceneに移動する
    }
}

ただし、これはコーディングだけではだめで、実行前に事前に該当シーンをBuild Settingで登録しておく必要がある。

スクリーンショット (230).png

3.ToString()の使い方

Test.cs
using UnityEngine;

public class Test : MonoBehaviour
{
    private void Start()
    {
        //int型からstring型に型変換したい
        int num = 7;
        string numSt = num.ToString();

        //float型からstring型に型変換したい
        float num2 = 0.7f;
        string num2St = num2.ToString();
    }
}

4.SetActiveの使い方

↓↓ここを変更するやつのコード。

スクリーンショット (232).png

Test.cs
using UnityEngine;

public class Test : MonoBehaviour
{
    private void Start()
    {
        //ゲームオブジェクトを表示したいとき
        this.gameObject.SetActive(true);
        
        //ゲームオブジェクトを非表示にしたいとき
        this.gameObject.SetActive(false);
        
        //実はこれが元の形。元の形をみたらSetActiveの理解が深まるかな?
        this.gameObject.active = true;
    }
}

5.効果音の鳴らし方

Test.cs
using UnityEngine;

public class Test : MonoBehaviour
{
    private AudioSource audioSource; //音を鳴らすコンポーネント
    [SerializeField] private AudioClip audioClip; //鳴らしたい音楽素材
    
    private void Start()
    {
        //AudioSourceコンポーネント取得
        audioSource = this.gameObject.GetComponent<AudioSource>();
        
        //効果音の鳴らし方
        audioSource.PlayOneShot(audioClip);
    }
}
6
7
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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?