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

Unity 2D赛马游戏中访问预制体实例脚本变量的问题

解决Unity中无法访问GameObject挂载脚本变量的问题

核心原因

你直接通过GameObject对象访问horsePos变量是行不通的,因为horsePos是定义在挂载于该GameObject的自定义脚本中的成员,而非GameObject类本身的属性。

具体解决步骤

假设你的自定义脚本名为HorseController(如果不是,替换成你实际的脚本名称):

  1. 获取脚本组件
    找到GameObject后,通过GetComponent<T>()方法获取对应的脚本实例:

    // 先声明脚本类型的变量(替换成你实际的脚本名)
    private HorseController horseOneScript;
    private HorseController horseTwoScript;
    
    void Start()
    {
        GameObject horseOne = GameObject.Find("Horse");
        GameObject horseTwo = GameObject.Find("Horse (1)");
        
        // 获取挂载在GameObject上的脚本组件
        horseOneScript = horseOne.GetComponent<HorseController>();
        horseTwoScript = horseTwo.GetComponent<HorseController>();
    }
    
  2. 访问脚本中的变量
    之后在Update中就可以通过脚本实例访问horsePos了:

    void Update()
    {
        // 先判断脚本是否存在,避免空引用错误
        if (horseOneScript != null && horseTwoScript != null)
        {
            if (horseOneScript.horsePos < horseTwoScript.horsePos)
            {
                Debug.Log("horse 1 infront");
            }
        }
    }
    

优化建议(可选)

如果后续会有更多马匹实例,建议用列表管理所有马匹脚本,避免逐个查找:

private List<HorseController> allHorses = new List<HorseController>();

void Start()
{
    // 查找场景中所有挂载了HorseController的对象
    allHorses.AddRange(FindObjectsOfType<HorseController>());
}

// 后续可以遍历列表判断领先者
void CheckLeader()
{
    if (allHorses.Count == 0) return;
    
    HorseController leader = allHorses[0];
    foreach (var horse in allHorses)
    {
        if (horse.horsePos < leader.horsePos)
        {
            leader = horse;
        }
    }
    Debug.Log($"当前领先的是:{leader.gameObject.name}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:07:25