LoginSignup
7
8

More than 5 years have passed since last update.

Unity NGUIでアスペクト比にかかわらずGameObjectの位置を指定する方法

Last updated at Posted at 2013-07-03

iPhone4,5や、Androidで異なるアスペクト比の画面サイズに対して

画面上、左端からボタンを配置したいということが、UnityのIDEで設置するだけではできないが、
スクリプトを対象のボタンなどのGameObjectに付加することで実現できる

追記:すなおにAnchorを使ったほうがいいと思います。Anchorの使い方がわからなくて自力実装したので、Anchorで表現しきれないところをハックして実装したい方には参考になるかもです。Unity4の最新版は2D 対応したのでソッチのほうがいいかもね!

[Unity]NGUIで画面サイズに合わせる(NGUI2.3.0対応版)http://udasankoubou.blogspot.jp/2013/05/unitynguingui230.htmlなんかを同時に利用する場合はもう少しこねくり回す必要あり。またSprineの場合はBoxColliderがないので少し違う。

このスクリプトでは、対象のオブジェクトを設置するx,y位置設定は、左上から表示が始まる位置とする(Webと一緒)

using UnityEngine;
using System.Collections;

public class NGUIPositionDitector : MonoBehaviour {
    BoxCollider boxCollider;
        public float x,y;
    // Use this for initialization
    void Start () {
        boxCollider = (BoxCollider)GetComponent("BoxCollider");     
        transform.localPosition = new Vector3(-Screen.width / 2  +boxCollider.size.x/2 + x, Screen.height /2 - boxCollider.size.y/2   , y);
              SendMessage("SetTweenPos",transform.localPosition);
    }

}

UIButtonOffsetを拡張する必要もある。ボタンを押した時のアニメーション位置が位置の変更に対応している無いので、UIButtonOffsetのmPosをセットできるようにする。

// Vector3 mPos;
 protected Vector3 mPos;
using UnityEngine;
using System.Collections;

public class UIButtonOffsetExtender : UIButtonOffset {  
    void SetTweenPos(Vector3 newPosition){
        mPos=newPosition;
    }
}
7
8
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
7
8