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

Unity对象未按Random.Range设定范围传送问题求助

问题排查与解决

核心问题

你错误地使用transform.position来设置UI按钮的位置——UI元素的坐标系统和普通3D/2D对象不同,必须通过RectTransform的anchoredPosition属性来控制位置。直接修改transform.position会导致坐标空间不匹配,出现你遇到的“始终负坐标、范围超出预期”的异常。

修复代码

替换原有位置赋值逻辑,改用RectTransform的anchoredPosition:

using UnityEngine;
using UnityEngine.UI;

public class OnClick : MonoBehaviour
{
    public Text scoreText;
    public int score = 0;
    private RectTransform buttonRect;

    void Start()
    {
        // 获取当前按钮的RectTransform组件
        buttonRect = GetComponent<RectTransform>();
    }

    public void Teleport()
    {
        score += 1;
        // 使用anchoredPosition设置UI元素的位置
        buttonRect.anchoredPosition = new Vector2(Random.Range(-800, 800), Random.Range(-350, 350));
        scoreText.text = "Score: " + score;
    }
}

额外验证项

  • 确认Canvas渲染模式为Screen Space - Overlay或Screen Space - Camera,这两种模式下anchoredPosition的坐标逻辑和你的预期匹配。
  • 检查按钮RectTransform的锚点(Anchor)是否设置为(0.5, 0.5),这样(0,0)对应屏幕中心,你的正负坐标范围能正确映射到屏幕的左右上下区域。

内容的提问来源于stack exchange,提问作者CakeOnBake

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:39:20