You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#通过函数实现物体随机移动出现CS0136错误如何解决

问题修复方案

错误原因

你遇到的CS0136报错是C#的基础命名冲突错误:random函数的参数已经命名为target,函数内部又再次声明了同名的Vector3 target局部变量,同一作用域下不允许重复定义同名参数/变量。

另外你的代码还存在逻辑问题:当前Update方法每帧都会生成新的随机目标点,会导致物体永远无法抵达固定目标,只会无规则乱飘,无法实现「移动到随机位置后再前往下一个随机点」的需求。

修复步骤

  1. 删除random函数无用的传入参数,同时去掉重复的target变量声明
  2. 调整调用逻辑:仅当物体抵达当前目标点后,再生成新的随机目标
  3. 移除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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:45:01