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

Unity报错:Transform.localRotation需对象引用,挂载脚本对象已有父物体

解决Unity中Transform.localRotation的对象引用报错问题

问题原因

报错Transform.localRotation requires object reference是因为你错误地通过Transform类名访问localRotation属性,但localRotation是实例属性,必须通过具体的Transform实例来调用。

在MonoBehaviour脚本中,直接使用小写的transform就是当前挂载脚本对象的Transform实例引用,而大写的Transform是类名,无法直接访问实例属性。

修正后的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GunToCursor : MonoBehaviour
{    
    void Update()
    {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        difference.Normalize();
        float rotation_x = Mathf.Atan2(difference.z, difference.y) * Mathf.Rad2Deg;
        // 将Transform改为小写的transform,访问当前对象的Transform实例
        transform.localRotation = Quaternion.Euler(rotation_x, 0f, 0f);
    }
}

补充说明

你之前用Transform.rotation能运行,大概率是实际代码中误写成了小写的transform.rotation(C#允许省略this.),而rotation是世界空间旋转,localRotation是相对于父物体的局部旋转,符合你对子物体设置局部旋转的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:57:18