You need to enable JavaScript to run this app. Unity VideoPlayer结合Vuforia虚拟按钮实现暂停播放时报CS0120错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Unity VideoPlayer结合Vuforia虚拟按钮实现暂停播放时报CS0120错误求助

Vuforia虚拟按钮控制视频播放的编译报错解决方案

报错明细

编译阶段触发的CS0120错误如下:

Assets\vp_time.cs(23,9): error CS0120: An object reference is required for the non-static field, method, or property 'VideoPlayer.Pause()'
Assets\vp_time.cs(27,9): error CS0120: An object reference is required for the non-static field, method, or property 'VideoPlayer.Play()'

错误原因

  • Unity引擎内置的VideoPlayer类中,Play()、Pause()均为非静态实例方法,必须获取场景中实际挂载的VideoPlayer组件实例才能调用,不能直接通过类名VideoPlayer.Play()/VideoPlayer.Pause()触发——这种调用方式等价于把非静态方法当成静态方法使用,是CS0120报错的触发本质。
  • 原代码逻辑中,虽然在Start()方法里执行了vbVpObj.GetComponent<VideoPlayer>(),但没有把获取到的组件实例存储为类内的可访问字段,导致按钮回调方法中没有可操作的VideoPlayer对象引用。

修正后的可运行代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using Vuforia;

public class vp_time : MonoBehaviour
{
    public GameObject vbBtnObj;
    public GameObject vbVpObj;
    // 存储场景中实际的VideoPlayer组件实例,供回调方法调用
    private VideoPlayer _targetVideoPlayer;

    void Start()
    {
        // 绑定虚拟按钮的按下、抬起回调
        vbBtnObj = GameObject.Find("VideoBtn");
        vbBtnObj.GetComponent<VirtualButtonBehaviour>().RegisterOnButtonPressed(OnButtonPressed);
        vbBtnObj.GetComponent<VirtualButtonBehaviour>().RegisterOnButtonReleased(OnButtonReleased);
        
        // 从指定对象上获取VideoPlayer组件,赋值给私有字段
        _targetVideoPlayer = vbVpObj.GetComponent<VideoPlayer>();
    }

    public void OnButtonPressed(VirtualButtonBehaviour vb){
        // 通过实例调用暂停方法
        _targetVideoPlayer.Pause();
    }

    public void OnButtonReleased(VirtualButtonBehaviour vb){
        // 通过实例调用播放方法
        _targetVideoPlayer.Play();
    }

    void Update()
    {

    }
}

落地注意事项

  • 确保vbVpObj指向的场景对象上已正确挂载VideoPlayer组件,且视频源、渲染目标已配置完成
  • 建议将vbBtnObj、vbVpObj的引用通过Inspector面板直接拖拽赋值,不要完全依赖GameObject.Find做运行时查找,避免场景物体命名变更导致的查找失效
  • 按钮逻辑可根据需求调整,比如将默认的“按下暂停、抬起播放”逻辑修改为单次点击切换播放/暂停状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 09:15:09