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

Unity替换游戏对象报错CS0117:Quaternion无Indentity定义如何解决

问题说明

需要在Unity中实现对象替换功能:按下A键时,将地图中指定的破损对象替换为预先配置好的新对象。代码运行时触发编译错误,报错信息如下:

Assets\Replacement.cs(31,63): error CS0117: 'Quaternion' does not contain a definition for 'Indentity'

原实现代码如下:

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

public class Replacement : MonoBehaviour
{
    public GameObject Broken_Table;
    public GameObject Table;
    private bool used = false;

    void Start()
    {

}

    void Update()
{

    if (!used && Input.GetKey(KeyCode.A))
    {

        Replace(Broken_Table, Table);
        Debug.Log("Replaced");
        used = true;
  }

}
    void Replace(GameObject obj1, GameObject obj2)
{

        Instantiate(obj2, obj1.transform.position, Quaternion.indentity);
        Destroy(obj1);

    }
}
错误原因

属于拼写错误:Unity中表示“无旋转”默认四元数的字段是Quaternion.identity,代码里错写为Quaternion.indentity(字母顺序写反,正确拼写为i-d-e-n-t-i-t-y,错写为i-n-d-e-n-t-i-t-y),编译器找不到对应字段就会抛出CS0117错误。

修正方案
  • 基础修复:把Quaternion.indentity修正为正确拼写Quaternion.identity即可解决编译错误
  • 朝向适配优化:如果希望新生成的对象和原破损对象的旋转角度完全一致,直接传入原对象的旋转值obj1.transform.rotation即可,避免原对象有摆放角度时新生成对象朝向不对
  • 按键逻辑优化:按键检测用Input.GetKeyDown(KeyCode.A)替代Input.GetKey(KeyCode.A),仅在按键按下的瞬间触发一次逻辑,更符合单次按键触发交互的直觉;原代码虽然有used标记不会重复执行,但GetKey会在按住按键时每帧都进入判断,存在不必要的性能开销

修正后的完整可运行代码:

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

public class Replacement : MonoBehaviour
{
    public GameObject Broken_Table;
    public GameObject Table;
    private bool used = false;

    void Start()
    {

    }

    void Update()
    {
        if (!used && Input.GetKeyDown(KeyCode.A))
        {
            Replace(Broken_Table, Table);
            Debug.Log("Replaced");
            used = true;
        }
    }

    void Replace(GameObject obj1, GameObject obj2)
    {
        // 若要保留原对象旋转,替换为 obj1.transform.rotation
        Instantiate(obj2, obj1.transform.position, Quaternion.identity);
        Destroy(obj1);
    }
}

内容的提问来源于stack exchange,提问作者Jaafar Ben Bouker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 04:27:23