2015-03-13 3 views
-4

Я разработал проект дополненной реальности. Но у меня проблема. Существует сценарий видеопроигрывателя, который может воспроизводиться на видео. Я хочу добавить кнопку добавления. Итак, я создал для этого еще один скрипт, но я не мог установить соединение между обоими сценариями. Я имею в виду, я хотел бы кнопку, которая может запустить функцию воспроизведения из VideoPlayBackBehaviour.csКак я могу назвать функции из C# в единстве

VideoHelper.cs

/// <summary> 
/// Initializes the VideoPlayerHelper object 
/// </summary> 
public bool Init() 
{ 
    return videoPlayerInit(); 
} 


/// <summary> 
/// Deinitializes the VideoPlayerHelper object 
/// </summary> 
/// <returns></returns> 
public bool Deinit() 
{ 
    return videoPlayerDeinit(); 
} 


/// <summary> 
/// Loads a local or remote movie file 
/// </summary> 
public bool Load(string filename, MediaType requestedType, bool playOnTextureImmediately, float seekPosition) 
{ 
    SetFilename(filename); 
    return videoPlayerLoad(mFilename, (int) requestedType, playOnTextureImmediately, seekPosition); 
} 


/// <summary> 
/// Unloads the currently loaded movie 
/// After this is called a new load() has to be invoked 
/// </summary> 
public bool Unload() 
{ 
    return videoPlayerUnload(); 
} 


/// <summary> 
/// Indicates whether the movie can be played on a texture 
/// </summary> 
public bool IsPlayableOnTexture() 
{ 
    return videoPlayerIsPlayableOnTexture(); 
} 


/// <summary> 
/// Indicates whether the movie can be played fullscreen 
/// </summary> 
public bool IsPlayableFullscreen() 
{ 
    return videoPlayerIsPlayableFullscreen(); 
} 


/// <summary> 
/// Set the native texture object that the video frames will be copied to 
/// </summary> 
public bool SetVideoTextureID(int textureID) 
{ 
    return videoPlayerSetVideoTextureID(textureID); 
} 


/// <summary> 
/// Return the current status of the movie such as Playing, Paused or Not Ready 
/// </summary> 
public MediaState GetStatus() 
{ 
    return (MediaState) videoPlayerGetStatus(); 
} 


/// <summary> 
/// Returns the width of the video frame 
/// </summary> 
public int GetVideoWidth() 
{ 
    return videoPlayerGetVideoWidth(); 
} 


/// <summary> 
/// Returns the height of the video frame 
/// </summary> 
public int GetVideoHeight() 
{ 
    return videoPlayerGetVideoHeight(); 
} 


/// <summary> 
/// Returns the length of the current movie 
/// </summary> 
public float GetLength() 
{ 
    return videoPlayerGetLength(); 
} 


/// <summary> 
/// Request a movie to be played either full screen or on texture and at a given position 
/// </summary> 
public bool Play(bool fullScreen, float seekPosition) 
{ 
    // On Android we use Unity's built-in full screen movie player 

    // On iOS we overlay a native full screen player as a new subview of the main window 
    // (note that the Unity engine is not paused in this case) 

    if (fullScreen && (Application.platform == RuntimePlatform.Android)) 
    { 
     if (mFilename == null) 
     { 
      return false; 
     } 

     Handheld.PlayFullScreenMovie(mFullScreenFilename, Color.black, FullScreenMovieControlMode.Full, FullScreenMovieScalingMode.AspectFit); 
     return true; 
    } 
    else 
    { 
     return videoPlayerPlay(fullScreen, seekPosition); 
    } 
} 


/// <summary> 
/// Pauses the current movie being played 
/// </summary> 
public bool Pause() 
{ 
    return videoPlayerPause(); 
} 


/// <summary> 
/// Stops the current movie being played 
/// </summary> 
public bool Stop() 
{ 
    return videoPlayerStop(); 
} 


/// <summary> 
/// Tells the VideoPlayerHelper to update the data from the video feed 
/// </summary> 
public MediaState UpdateVideoData() 
{ 
    return (MediaState) videoPlayerUpdateVideoData(); 
} 


/// <summary> 
/// Moves the movie to the requested seek position 
/// </summary> 
public bool SeekTo(float position) 
{ 
    return videoPlayerSeekTo(position); 
} 


/// <summary> 
/// Gets the current seek position 
/// </summary> 
public float GetCurrentPosition() 
{ 
    return videoPlayerGetCurrentPosition(); 
} 


/// <summary> 
/// Sets the volume of the movie to the desired value 
/// </summary> 
public bool SetVolume(float value) 
{ 
    return videoPlayerSetVolume(value); 
} 


/// <summary> 
/// Gets the buffering percentage in case the movie is loaded from network 
/// Note this is not supported on iOS 
/// </summary> 
public int GetCurrentBufferingPercentage() 
{ 
    return videoPlayerGetCurrentBufferingPercentage(); 
} 


/// <summary> 
/// Allows native player to do appropriate on pause cleanup 
/// </summary> 
public void OnPause() 
{ 
    videoPlayerOnPause(); 
} 

PlayBackBehavior.cs

private VideoPlayerHelper mVideoPlayer = null; 
private bool mIsInited = false; 
private bool mIsPrepared = false; 

private Texture2D mVideoTexture = null; 

[SerializeField] 
[HideInInspector] 
private Texture mKeyframeTexture = null; 

private VideoPlayerHelper.MediaType mMediaType = 
     VideoPlayerHelper.MediaType.ON_TEXTURE_FULLSCREEN; 

private VideoPlayerHelper.MediaState mCurrentState = 
     VideoPlayerHelper.MediaState.NOT_READY; 

private float mSeekPosition = 0.0f; 

private bool isPlayableOnTexture; 

private GameObject mIconPlane = null; 
private bool mIconPlaneActive = false; 

#endregion // PRIVATE_MEMBER_VARIABLES 



#region PROPERTIES 

/// <summary> 
/// Returns the video player 
/// </summary> 
public VideoPlayerHelper VideoPlayer 
{ 
    get { return mVideoPlayer; } 
} 

/// <summary> 
/// Returns the current playback state 
/// </summary> 
public VideoPlayerHelper.MediaState CurrentState 
{ 
    get { return mCurrentState; } 
} 

/// <summary> 
/// Type of playback (on-texture only, fullscreen only, or both) 
/// </summary> 
public VideoPlayerHelper.MediaType MediaType 
{ 
    get { return mMediaType; } 
    set { mMediaType = value; } 
} 

/// <summary> 
/// Texture displayed before video playback begins 
/// </summary> 
public Texture KeyframeTexture 
{ 
    get { return mKeyframeTexture; } 
    set { mKeyframeTexture = value; } 
} 


/// <summary> 
/// Returns whether the video should automatically start 
/// </summary> 
public bool AutoPlay 
{ 
    get { return m_autoPlay; } 
} 

#endregion // PROPERTIES 



#region UNITY_MONOBEHAVIOUR_METHODS 

void Start() 
{ 
    // Find the icon plane (child of this object) 
    mIconPlane = transform.Find("Icon").gameObject; 

    // A filename or url must be set in the inspector 
    if (m_path == null || m_path.Length == 0) 
    { 
     Debug.Log("Please set a video url in the Inspector"); 
     HandleStateChange(VideoPlayerHelper.MediaState.ERROR); 
     mCurrentState = VideoPlayerHelper.MediaState.ERROR; 
     this.enabled = false; 
    } 
    else 
    { 
     // Set the current state to Not Ready 
     HandleStateChange(VideoPlayerHelper.MediaState.NOT_READY); 
     mCurrentState = VideoPlayerHelper.MediaState.NOT_READY; 
    } 
    // Create the video player and set the filename 
    mVideoPlayer = new VideoPlayerHelper(); 
    mVideoPlayer.SetFilename(m_path); 

    // Flip the plane as the video texture is mirrored on the horizontal 
    transform.localScale = new Vector3(-1 * Mathf.Abs(transform.localScale.x), 
      transform.localScale.y, transform.localScale.z); 

    // Scale the icon 
    ScaleIcon(); 
} 

void OnRenderObject() 
{ 
    if (!mIsInited) 
    { 
     // Initialize the video player 
     if (mVideoPlayer.Init() == false) 
     { 
      Debug.Log("Could not initialize video player"); 
      HandleStateChange(VideoPlayerHelper.MediaState.ERROR); 
      this.enabled = false; 
      return; 
     } 

     // Initialize the video texture 
     InitVideoTexture(); 

     // Load the video 
     if (mVideoPlayer.Load(m_path, mMediaType, false, 0) == false) 
     { 
      Debug.Log("Could not load video '" + m_path + "' for media type " + mMediaType); 
      HandleStateChange(VideoPlayerHelper.MediaState.ERROR); 
      this.enabled = false; 
      return; 
     } 

     // Successfully initialized 
     mIsInited = true; 
    } 
    else if (!mIsPrepared) 
    { 
     // Get the video player status 
     VideoPlayerHelper.MediaState state = mVideoPlayer.GetStatus(); 

     if (state == VideoPlayerHelper.MediaState.ERROR) 
     { 
      Debug.Log("Could not load video '" + m_path + "' for media type " + mMediaType); 
      HandleStateChange(VideoPlayerHelper.MediaState.ERROR); 
      this.enabled = false; 
     } 
     else if (state < VideoPlayerHelper.MediaState.NOT_READY) 
     { 
      // Video player is ready 

      // Can we play this video on a texture? 
      isPlayableOnTexture = mVideoPlayer.IsPlayableOnTexture(); 

      if (isPlayableOnTexture) 
      { 
       // Pass the video texture id to the video player 
       int nativeTextureID = mVideoTexture.GetNativeTextureID(); 
       mVideoPlayer.SetVideoTextureID(nativeTextureID); 

       // Get the video width and height 
       int videoWidth = mVideoPlayer.GetVideoWidth(); 
       int videoHeight = mVideoPlayer.GetVideoHeight(); 

       if (videoWidth > 0 && videoHeight > 0) 
       { 
        // Scale the video plane to match the video aspect ratio 
        float aspect = videoHeight/(float) videoWidth; 

        // Flip the plane as the video texture is mirrored on the horizontal 
        transform.localScale = new Vector3(-0.1f, 0.1f, 0.1f * aspect); 
       } 

       // Seek ahead if necessary 
       if (mSeekPosition > 0) 
       { 
        mVideoPlayer.SeekTo(mSeekPosition); 
       } 
      } 
      else 
      { 
       // Handle the state change 
       state = mVideoPlayer.GetStatus(); 
       HandleStateChange(state); 
       mCurrentState = state; 
      } 

      // Scale the icon 
      ScaleIcon(); 

      // Video is prepared, ready for playback 
      mIsPrepared = true; 
     } 
    } 
    else 
    { 
     if (isPlayableOnTexture) 
     { 
      // Update the video texture with the latest video frame 
      VideoPlayerHelper.MediaState state = mVideoPlayer.UpdateVideoData(); 

      // Check for playback state change 
      if (state != mCurrentState) 
      { 
       HandleStateChange(state); 
       mCurrentState = state; 
      } 
     } 
     else 
     { 
      // Get the current status 
      VideoPlayerHelper.MediaState state = mVideoPlayer.GetStatus(); 

      // Check for playback state change 
      if (state != mCurrentState) 
      { 
       HandleStateChange(state); 
       mCurrentState = state; 
      } 
     } 
    } 

    CheckIconPlaneVisibility(); 
} 


void OnApplicationPause(bool pause) 
{ 
    if (!mIsInited) 
     return; 

    if (pause) 
    { 
     // Handle pause event natively 
     mVideoPlayer.OnPause(); 

     // Store the playback position for later 
     mSeekPosition = mVideoPlayer.GetCurrentPosition(); 

     // Deinit the video 
     mVideoPlayer.Deinit(); 

     // Reset initialization parameters 
     mIsInited = false; 
     mIsPrepared = false; 

     // Set the current state to Not Ready 
     HandleStateChange(VideoPlayerHelper.MediaState.NOT_READY); 
     mCurrentState = VideoPlayerHelper.MediaState.NOT_READY; 
    } 
} 


void OnDestroy() 
{ 
    // Deinit the video 
    mVideoPlayer.Deinit(); 
} 
добавить

ButtonScript, также я попробовал это , но его не работает.

void OnMouseDown(){ 

VideoPlayerHelper otherScript = GetComponent<VideoPlayerHelper>(); 

     otherScript.Play(); 
    } 
+0

ли попробовать прибегая к помощи? if not http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html – Dinal24

+0

Я знаю этот метод. Но я не мог интегрироваться, чтобы играть, останавливать функции. – Cracked

ответ

0

Я действительно не знаю, в чем проблема, если вы хотите получить доступ к скрипту из другого.

Просто создать переменный с типом сценария:

MyScript.cs 
then: 

private MyScript script;  
script = GetComponent<MyScript>(); 

В переменном сценарии теперь у вас есть экземпляр MyScript и все методы. Это будет работать, только если вы привязали все сценарии к одному и тому же GameObject. Если ваш скрипт присоединен к другому объекту игры, то вам нужно использовать:

private MyScript otherScript; 
anotherScript = otherGameObject.GetComponent<MyScript>(); 

где otherGameObject является ссылка на геймобжекты, где у вас есть сценарий, который вы ищете. Вы также можете напрямую назначить редактор, свой сценарий для своей переменной (переменная должна быть общедоступной), просто перетащите скрипт.

Вам следует попытаться лучше объяснить ваше предложение и не ставить весь код, если это не обязательно. Только точно проблема. Трудно проверить весь код. Если у вас есть больше неприятностей проверить это: вы

http://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent

+0

Эй, я не знал, что это возможно. Итак, скажем, для BScript для доступа к AScript через ваш метод, должен ли AScript находиться в папке с ресурсами? Или что-то другое? –

+0

Все ваши сценарии должны находиться в папке с ресурсами. – superpichon

1

Два решения для вас. И они будут работать исправно, но вы должны изменить свой код в соответствии с решениями:

  • Установите кнопку в качестве дочернего элемента видео в Unity.
  • Или, при вызове playBackBehaviour.cs убедитесь, что вы включили глобальных переменную для видеоэлемента, так что вы можете прикрепить видео, который должен быть воспроизведен непосредственно к кнопке через инспектора панели.
Смежные вопросы