LoginSignup
22
20

More than 5 years have passed since last update.

Unity カメラを切り替える

Last updated at Posted at 2015-03-17

Unity5 Personal Edition
OS: osX
言語: C#

spaceキーを押すとカメラが切り替わるスクリプトです

Sample.cs

using UnityEngine;
using System.Collections;

public class Sample : MonoBehaviour {

    private GameObject MainCam;
    private GameObject SubCam;

    void Start () {
        MainCam = GameObject.Find("MainCamera");
        SubCam = GameObject.Find("SubCamera");

        SubCam.SetActive(false);
    }

    void Update () {
        if(Input.GetKeyDown("space")){
            if(MainCam.activeSelf){
                MainCam.SetActive (false);
                SubCam.SetActive (true);
            }else{
                MainCam.SetActive (true);
                SubCam.SetActive (false);
            }
        }
    }

}

ソースコードについて

gameObject.SetActive (bool)
ゲームオブジェクトをアクティブ(動作・表示)/非アクティブ(非動作・非表示)にします
trueを渡せばアクティブ、falseを渡せば非アクティブになります。

gameObject.activeSelf (Read Only)
ゲームオブジェクトのアクティブ状態をboolで返す
trueならアクティブ、falseなら非アクティブという事です。
※親要素のアクティブ状態は関係ありません

Start関数
メインカメラとサブカメラのGameObjectを取得して変数に代入
MainCam = GameObject.Find("MainCamera");
SubCam = GameObject.Find("SubCamera");

サブカメラを非アクティブにしておく
SubCam.SetActive(false);

Update関数
spaceキーを押すと...
1.MainCam(メインカメラ)のアクティブ状態を調べる
2-1.アクティブだったらMainCamを非アクティブにして、subCam(サブカメラ)をアクティブにする
2-2.非アクティブだったらMainCamをアクティブにして、subCamを非アクティブにする

22
20
3

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
22
20