LoginSignup
10
7

More than 3 years have passed since last update.

【Unity】newってなに?? newが必要なシチュエーションまとめ

Last updated at Posted at 2020-04-25

環境

Unity 2019.3.7f1

はじめに

ネットでコードを検索していると new がついているコードありますよね??
今回は、
 ・newとは何か?
 ・newが必要なシチュエーション
を私がわかっている範囲でまとめておきます。

newとは何か?

まずnewですが、
インスタンスを作る演算子
です。

new 型名();

でその型名のインスタンスを作成することができます。

設計図の状態から実体を持たせるらしいです。(雰囲気しかわかってない)

newが必要なシチュエーション

今私が把握しているのは次の4つです。
・空のゲームオブジェクトを作るとき
・自分で作ったクラスを使うとき
・配列を使うとき
・構造体(Vector3やVector2など)を使うとき

※もとから作られているC#のクラスはnewでインスタンス化できないらしい

コード例

・空のゲームオブジェクトを作るとき

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{
    void Start()
    {
        new GameObject();//空のオブジェクト作成 括弧内に文字列を入れることでオブジェクトの名前を指定できる
    }
}

 
・自分で作ったクラスを使うとき

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//ABCという名前のクラス作成
public class ABC
{    
    //関数作成
    public void Moji()
    {
        Debug.Log("newって難しい");
    }
}


public class test : MonoBehaviour
{
    ABC a;//作成したクラスABC型の変数aを宣言

    void Start()
    {
        a = new ABC();//変数aにABCクラスのインスタンスを作成
        a.Moji();//ABCクラスのMoji()関数を実行
    }
}

 
・配列を使うとき

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{
    private int[] a;//int型の配列を変数aで宣言

    void Start()
    {
        a = new int[3];//配列を作りint型の配列変数aに入れる

        //配列 a[0]=0, a[1]=1, a[2]=2 にする
        for (int i = 0; i < 3; i++)
        {
            a[i] = i;
            Debug.Log("a[" + i + "]=" + a[i]);
        }
    }    
}

 
・構造体(Vector3やVector2など)を使うとき

Vector3
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class test : MonoBehaviour
{    
    void Start()
    {
        //このスクリプトがアタッチされたオブジェクトの位置を(1,2,3)へ変更
        transform.position = new Vector3(1, 2, 3);
    }    
}

 

Vector2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class test : MonoBehaviour
{    
    void Start()
    {
        //このスクリプトがアタッチされたオブジェクトの位置を(10,20,0)へ変更
        transform.position = new Vector2(10, 20);
    }    
}

おわりに

空のゲームオブジェクトを作ることは実際やらないと思うので、

・自分で作ったクラスを使うとき
・配列を使うとき
・構造体(Vector3やVector2など)を使うとき

の3パターンの場合、newするってのを覚えておけば開発に問題無いと思ってる私です。

そのうち深く理解できることを信じて今日も開発!!

10
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
10
7