ゲーム制作総合知識⑥(2025/06/14)

・ドット絵の小物は作れるようになっておくとよい。

左右移動で反転すること
PlayerのInspector内 Flip(X)をチェック(True)すると、左右が反転する。
これをコードでコントロールする。

using UnityEngine;


public class PlayerController : MonoBehaviour
{
    [SerializeField] private float jumpPower = 5.0f;
    [SerializeField] private float speed = 10.0f;
   [SerializeField]private SpriteRenderer sprite;
    private Rigidbody2D rb;
    private int jumpCount = 0;
   

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

void Update()
{
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += new Vector3(10.0f, 0, 0) * Time.deltaTime;
            sprite.flipX = false;
    }
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position += new Vector3(-speed, 0, 0) * Time.deltaTime;
            sprite.flipX = true;
        }
        if (Input.GetKeyDown(KeyCode.Space) && jumpCount < 1)
            {
                rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
                jumpCount++;
            }
}
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            jumpCount = 0;
        }
    }

}

PlayerのSpriteのInspector内でSpriteを追加。

この段階では衝突時に回転してしまうので、これを解消する。
Sprite Renderer内のConstraints配下、Freeze Rotation:Zをチェックする。


プレハブ化

プレハブ(Prefab)=箱
※再利用ができる。必須機能。

①オブジェクトを作成。これを再利用するためにPrefab化する。

②Project内にPrefabsフォルダを作成。保存先を分けておく。

③作成したオブジェクトをPrefabs内にドロップ。これでPrefab化される。

④これをHierarchyにドロップすると、オブジェクトをコピーできる。
(最大の利点はコピーされたオブジェクトの設定の変更をPrefabを変更することで一括で可能な事)

なお、PrefabをダブルクリックするとPrefab編集画面になり、ここでComponentを追加したりTagを変更したり、もろもろ可能。

ステージの自動生成(インスタンス化)

public class StageManager : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    [SerializeField] private GameObject stage;
    void Start()
    {
        Instantiate(stage, new Vector3(18, 0, 0), Quaternion.identity);
   //↑実体化のための関数  ↑位置情報の生成   ↑回転
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
インスタント化とは
Unityでのインスタンス化(Instantiation)とは、スクリプトを使ってゲームオブジェクトを動的に生成することを指します。通常、プレハブ(Prefab)を活用して新しいインスタンスを作成し、シーン内に配置することが一般的です。
基本的なインスタンス化の方法
Unityでは、Instantiate() メソッドを使用してオブジェクトを生成できます。基本的な使い方は以下の通りです:
using UnityEngine;

public class Example : MonoBehaviour
{
    public GameObject prefab;

    void Start()
    {
        // プレハブを現在の位置にインスタンス化
        Instantiate(prefab, transform.position, Quaternion.identity);
    }
}


このコードでは、prefab に指定されたオブジェクトが transform.position の位置に生成されます。
インスタンス化の応用
- 特定の座標に生成:
Instantiate(prefab, new Vector3(0, 1, 0), Quaternion.identity);
- このコードでは、(0,1,0) の位置にオブジェクトを生成します。
- 親オブジェクトを設定:
Instantiate(prefab, transform.position, Quaternion.identity, transform);
- これにより、新しいオブジェクトは transform の子オブジェクトとして配置されます。
- オブジェクトのクローンを保存:
GameObject clone = Instantiate(prefab);
clone.transform.position = new Vector3(2, 0, 0);
- clone を使って、生成されたオブジェクトをプログラム上で操作できます。
インスタンス化の注意点
- パフォーマンス管理:大量のオブジェクトを生成すると、パフォーマンスに影響を与える可能性があるため、オブジェクトプールを活用すると効果的です。
- 不要なオブジェクトの削除:使い終わったオブジェクトは Destroy() を使用して適切に削除しましょう。
- 同期処理:ネットワークゲームでは、インスタンス化のタイミングを適切に管理し、すべてのクライアントで同じ状態を維持する必要があります。
このように、Instantiate() を活用することで、ゲームの動的なオブジェクト生成が可能になります。

①StageManager.csを作成してStageManagerオブジェクト(空オブジェクト)を作成。
②StageManagerオブジェクトにStageManager.csをアタッチ。

③StageManagerの内容は下記。

using System.Collections.Generic;
using UnityEngine;

public class StageManager : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    [SerializeField] private List<GameObject> stages;//Cの配列っぽいもの。後述。
    const int STAGE_WIDTH = 6;
    const int INITIAL_STAGE_COUNT = 10;
    void Start()
    {
        for (int i = 0; i < INITIAL_STAGE_COUNT; i++)
        {
            int index = Random.Range(0, stages.Count);
            Instantiate(
            stages[index],
            new Vector3(STAGE_WIDTH * (i + 1), 0, 0),
            Quaternion.identity);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

④ステージのPrefabを複数作り、StageManagerのInspector内StagesにPrefabをドロップ。

これでステージが自動生成されるようになった。

※C#の「List」について
C#のList<T>は、柔軟なサイズ変更が可能なコレクションの一種で、配列のように要素を管理できますが、動的にサイズを変更できるのが特徴です。
基本的な使い方
List<T>を使用するには、System.Collections.Genericをインポートする必要があります。
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Listの作成(int型)
        List<int> numbers = new List<int>();

        // 要素の追加
        numbers.Add(10);
        numbers.Add(20);
        numbers.Add(30);

        // リストの内容を表示
        foreach (int num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}


主なメソッド
- Add(T item): 要素を追加
- Remove(T item): 指定した要素を削除
- Count: 現在の要素数を取得
- Contains(T item): 指定した要素が含まれているか確認
- Clear(): 全ての要素を削除
- Insert(int index, T item): 指定した位置に要素を挿入
- Sort(): 要素を並び替え
応用例: リストのフィルタリング
Linqを活用すると、リスト内のデータを簡単に操作できます。
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 10, 15, 20, 25 };

        // 10以上の数値を抽出
        List<int> filteredNumbers = numbers.Where(n => n >= 10).ToList();

        foreach (int num in filteredNumbers)
        {
            Console.WriteLine(num);
        }
    }
}


List<T>はC#のプログラミングで非常に便利な機能です。

※配列との違い
List<T>はC言語の配列をより柔軟にしたものと考えられます。
Cの配列はサイズを固定しなければならず、メモリ管理も手動で行う必要がありますが、List<T>はサイズを動的に変更可能であり、要素の追加・削除などを簡単に行えます。また、List<T>はメソッドを多く備えており、検索や並び替えなどの操作を容易に行えます。
Cで動的配列を使う場合にはmalloc()やrealloc()を使う必要がありますが、C#のList<T>はそういったメモリ管理を自動で行ってくれるため、開発がより楽になります。
ただし、内部的には動的配列(Array)を基に実装されているため、配列と同様にインデックスを用いた高速アクセスが可能ですが、リストのサイズが大きくなると、リサイズ処理の負荷が発生することもあります。
「拡張版の配列」として考えれば違和感なく使えると思いますが、もっと便利なコレクション(Dictionary<T, U>やHashSet<T>など)もあるので、用途に応じて適切なものを選ぶのが良いですね!

(by Copilot)


※クラス図/UML

コメント

タイトルとURLをコピーしました