Unity C#通过函数实现物体随机移动出现CS0136错误如何解决
问题修复方案
错误原因
你遇到的CS0136报错是C#的基础命名冲突错误:random函数的参数已经命名为target,函数内部又再次声明了同名的Vector3 target局部变量,同一作用域下不允许重复定义同名参数/变量。
另外你的代码还存在逻辑问题:当前Update方法每帧都会生成新的随机目标点,会导致物体永远无法抵达固定目标,只会无规则乱飘,无法实现「移动到随机位置后再前往下一个随机点」的需求。
修复步骤
- 删除
random函数无用的传入参数,同时去掉重复的target变量声明 - 调整调用逻辑:仅当物体抵达当前目标点后,再生成新的随机目标
- 移除
Update里多余的局部target变量声明,直接复用类层面定义的全局target变量
修复后完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { public float speed; // 全局存储当前要前往的目标点 Vector3 target; // Start is called before the first frame update void Start() { // 初始化第一个目标点 target = GetRandomPosition(); } // Update is called once per frame void Update() { // 向当前目标点移动 transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed); // 抵达当前目标后,生成新的随机目标点 if (Vector3.Distance(transform.position, target) < 0.1f) { target = GetRandomPosition(); } } // 专门生成随机坐标的函数,不需要传入参数 Vector3 GetRandomPosition() { float min = -100.0f; float max = 100.0f; float randomX = Random.Range(min, max); float randomZ = Random.Range(min, max); // 直接返回生成的坐标,不需要额外声明重复变量 return new Vector3(randomX, 10.0f, randomZ); } }
内容的提问来源于stack exchange,提问作者Constant
相关产品推荐
相关产品推荐

