気軽に遊べるミニゲームを制作しています

ブラウザゲームまとめ

Unity ゲームオブジェクトの画像変更、非Activeにする

Unity2D

スケールを変更する .transform.localScale = new Vecotr3

アタッチされたオブジェクトの大きさを変更します。

以下のコードではゲーム開始時にスケールを4に変更します。

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

public class ScaleChange : MonoBehaviour
{
    public GameObject targetObject;

    // Start is called before the first frame update
    void Start()
    {
        targetObject.transform.localScale = new Vector3(4f, 4f);
    }
 
}

インスペクターを見ると、スケールが4に変更されています。

画像を変更する .GetComponent<SpriteRenderer>().sprite

ゲームオブジェクトの画像を変更します。
まずは、使用する画像のテクスチャータイプをインスペクター上で Sprite(2D and UI)に変更します。

ゲーム開始時にアタッチされたイメージに変更します。

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

public class ScaleChange : MonoBehaviour
{
    public GameObject targerObject;
    public Sprite image;

    // Start is called before the first frame update
    void Start()
    {
        targerObject.GetComponent<SpriteRenderer>().sprite = image;
    }
 
}

画像を反転させる .GetComponent<SpriteRenderer>().flipX = true;

前述と同様、ゲームオブジェクトのパラメータを変えるときは、GetComponentでデータを取り扱います。

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

public class ScaleChange : MonoBehaviour
{
    public GameObject targerObject;

    // Start is called before the first frame update
    void Start()
    {
        targerObject.GetComponent<SpriteRenderer>().flipX = true;
    }
 
}

インスペクターを確認すると、FlipのXにチェックが入っています。

オブジェクトを非表示にする .SetActive (false);

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

public class ScaleChange : MonoBehaviour
{
    public GameObject targerObject;

    // Start is called before the first frame update
    void Start()
    {
        targerObject.SetActive(false);
    }

}

ゲーム開始時にアタッチされたゲームオブジェクトが非表示になります。
アクティブでないオブジェクトのコンポーネントは機能しないので、他のオブジェクトを操作するスクリプトをつけていた場合は、ゲームの進行に影響がないか注意が必要です。

コメント

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