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

Unity中C#代码的spawnPoints数组未显示在Inspector面板求助

解决Unity中spawnPoints数组不显示在Inspector面板的问题

以下是直接的排查和修复步骤:

  • 确认脚本已挂载:检查场景中是否有GameObject挂载了GameManager脚本,且该对象处于激活状态。未挂载脚本的话,Inspector不会显示任何变量。
  • 强制刷新编辑器:
    • 保存脚本(Ctrl+S/Cmd+S)
    • 右键Project面板中的脚本文件,选择Reimport
    • 若以上无效,重启Unity编辑器
  • 检查变量修饰符:确保spawnPoints的定义是public GameObject[] spawnPoints;,如果是private或protected,Inspector不会显示该变量。
  • 排查编译错误:打开Unity控制台(Window > General > Console),查看是否有红色编译错误。脚本编译失败时,所有公共变量都不会显示在Inspector,优先修复错误。
  • 显式初始化数组:可以给数组添加初始化语句,让Inspector更稳定显示:
    public GameObject[] spawnPoints = new GameObject[0];
    

另外给你的代码提个优化建议:把随机数的上限从固定的3改成spawnPoints.Length,同时添加数组长度判断,避免数组为空时触发空引用错误:

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

public class GameManager : MonoBehaviour
{
    public GameObject spawnObject;
    public GameObject[] spawnPoints = new GameObject[0];
    public float timer;
    public float timeBetweenSpawns;

    void Start()
    {
        
    }

    void Update()
    {
        timer += Time.deltaTime;

        if (timer > timeBetweenSpawns && spawnPoints.Length > 0)
        {
            timer = 0;
            int randomNum = Random.Range(0, spawnPoints.Length);
            Instantiate(spawnObject, spawnPoints[randomNum].transform.position, Quaternion.identity);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:02:14