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

Unity中公共GameObject在脚本中不显示的问题求助

问题:Unity脚本中public GameObject无法在编辑器显示并赋值

脚本里声明的public GameObject(Interaction_info_UI)在编辑器中无法显示,无法进行赋值。尝试过安装Visual Studio扩展,但未解决问题。其中InteractableObject是另一个可正常工作的脚本组件。

相关代码

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

public class SelectionManager : MonoBehaviour
{

    public GameObject Interaction_info_UI;
    Text interaction_text;
 
    private void Start()
    {
        interaction_text = Interaction_info_UI.GetComponent<Text>();
    }
 
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            var selectionTransform = hit.transform;
 
            if (selectionTransform.GetComponent<InteractableObject>())
            {
                interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
                Interaction_info_UI.SetActive(true);
            }
            else 
            { 
                Interaction_info_UI.SetActive(false);
            }
 
        }
    }
}

解决方案

  • 确认脚本已挂载:检查SelectionManager脚本是否正确添加到场景中的某个GameObject上,未挂载的话编辑器不会显示公共变量。
  • 排查编译错误:打开Unity的Console窗口,查看是否存在语法错误或引用缺失。比如InteractableObject的命名空间是否正确、是否存在编译失败的情况,编译错误会导致公共变量无法显示。
  • 强制重新编译:右键点击Project窗口中的SelectionManager脚本,选择Reimport;或者通过菜单Assets -> Reimport All重新编译所有资源,修复可能的缓存问题。
  • 检查访问修饰符:确认Interaction_info_UI确实是public修饰,没有被误写为private或protected。
  • 重启Unity:缓存异常可能导致显示问题,重启Unity编辑器和Visual Studio可以解决这类问题。
  • 验证对象类型:确保要赋值的目标是GameObject类型,而非Text或其他组件类型,类型不匹配会导致变量无法正常显示和赋值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:47:05