1、新建一个3d工程
2、生成一个cube
3、生成一个脚本(名字要为move!!!)(右键生成选项)代码usi艘绒庳焰ng System.Collections;using System.Collections.Generic;using UnityEngine;public class move : MonoBehaviour{ private Transform son; public bool moveToLeft = true; private float speed = 2; private void Start() { son = this.transform; } private void Update() { Move(); } private void Move() { if (son.position.x <= -3 && moveToLeft) { moveToLeft = false; } else if (son.position.x >= 3 && !moveToLeft) moveToLeft = true; son.position += (moveToLeft ? Vector3.left : Vector3.right) * Time.deltaTime * speed; }}
4、将物体的相关脚本拖到层级视图新建的cube中
5、点击运行,就可以看到结果了!