構成
No.1 ボタンを作り出す
No.2 動かすオブジェクトを作り出す
No.3 ボタンにスクリプトを追加する
No.4 クリックしたら関数を呼び出すようにする
No.1 ボタンを作り出す
とりあえずボタンを生成します。
そしたらそれの位置を左下あたりにします。
No.2 動かすオブジェクトを作り出す
動かす用のオブジェクトを作ります。
左下らへんにオブジェクトを配置させて、動かすためのスクリプトを追加させます。
スクショしてたけど保存するの忘れたので画像なし…
スクリプトも以下のような感じに調整します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCube : MonoBehaviour
{
private const float m_overLeftX = -10.0f;
private const float m_overRightX = 10.0f;
private const float m_moveSpeed = 0.1f;
public bool isMoveLeft;
// Start is called before the first frame update
void Start()
{
isMoveLeft = true;
}
// Update is called once per frame
void FixedUpdate()
{
if(isMoveLeft)
{
if (this.transform.position.x < m_overLeftX) return;
Vector3 pos = this.transform.position;
pos.x -= m_moveSpeed;
this.transform.position = pos;
}
else
{
if (this.transform.position.x > m_overRightX) return;
Vector3 pos = this.transform.position;
pos.x += m_moveSpeed;
this.transform.position = pos;
}
}
}
No.3 ボタンにスクリプトを追加する
ちょっとややこしい名前にスクリプトにしましたが、こんな感じにスクリプトを作成します。
そしたら中身も調整します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonMoveToRight : MonoBehaviour
{
public GameObject moveCube;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnClick()
{
moveCube.GetComponent().isMoveLeft = false;
}
}
そとから動かすオブジェクト引っ張りたいのでUnityの方も少し弄ります。
No.4 クリックしたら関数を呼び出すようにす
クリック時の動作を決めたいので画像の「+」をクリックします。
そしたらなんか入れ子があるので、None(Object)にクリックしたら動作をする関数を持っているスクリプトを持っているオブジェクトを入れます。
今回は自分自身なのですが、入れないといけないので入れます。
そうしたらNo Functionが弄れるようになったのでOnClick()を指定します。
はい、これで実行したら右に動きます。
同様に右側にボタンを配置してCubeのisMoveLeftをfalseに変える感じで同じようなものを作ればいいです。やろうと思ったのですがめんどくさくなったのでやめときます。