Programming」カテゴリーアーカイブ

プログラミング全般に関するカテゴリーです。

UnityのUIをスクリプトから操作する方法

UnityのUI(Pos X/Pos Y/Pos ZやWidth/Height)はRectTransformlocalPositionizeDeltaを使って操作できるようです。

Pos X/Pos Y/Pos Z

// Pos X
GetComponent<RectTransform> ().localPosition.x;

// Pos Y
GetComponent<RectTransform> ().localPosition.y;

// Pos Z
GetComponent<RectTransform> ().localPosition.z;

Width/Height

// Width
GetComponent<RectTransform> ().sizeDelta.x

// Height
GetComponent<RectTransform> ().sizeDelta.y

ただ、そのまま使うとInspectorで表示される値とスクリプトで取得できる値が異なることもあり、取り扱いには注意が必要そうです。親Rect TransformやAnchors等の値が関係しているみたいです。

リンク

Unityの新しいGUI機能(uGUI)で実装されたRect Transformの仕様メモ – お米 is ライス
http://spi8823.hatenablog.com/entry/2014/10/27/024948

Unityでスクリプトからコンポーネントを削除する方法

Unityではスクリプトからコンポーネントを追加したい場合にGameObject.AddComponentというメソッドが使えますが、コンポーネントを削除したい場合はGameObject.AddComponentというメソッドが使えるそうです。

GameObject.Destroy(example.GetComponent<boxcollider>());

こんな感じで使うとBox Colliderをexampleオブジェクトから削除できるようです。

リンク

【Unity】RemoveComponentを拡張メソッドで実現する – コガネブログ
http://baba-s.hatenablog.com/entry/2014/06/30/092319

Unity – スクリプトリファレンス: GameObject
https://docs.unity3d.com/jp/current/ScriptReference/GameObject.html

Unityの自作スクリプトでEnable/Disableのチェックボックが表示されない場合

Unityでスクリプトを作りオブジェクトに適用してみると、稀にInspectorにEnable/Disableチェックボックスが表示されないことがあります。そんなときはStartメソッドを追加してみると良いそうです。

void Start()
{
}

困っている人は試してみてください。

リンク

component on/off checkbox not showing up in the inspector | Unity Community
https://forum.unity.com/threads/component-on-off-checkbox-not-showing-up-in-the-inspector.56980/