How can I loop the video when I left click on it? - c#

Here's the code I'm using :
[RequireComponent (typeof(AudioSource))]
public class video : MonoBehaviour {
public MovieTexture movie;
public bool loop;
private AudioSource audio;
// Use this for initialization
void Start () {
GetComponent<RawImage> ().texture = movie as MovieTexture;
audio = GetComponent<AudioSource> ();
audio.clip = movie.audioClip;
movie.Play ();enter code here
audio.Play ();
movie.loop = true ();
}
// Update is called once per frame
void Update () {
}
void onMouseDown (){
if (Input.GetKeyDown(KeyCode.Mouse0)&& !movie.isPlaying)
movie.Play ();
else if (Input.GetKeyDown(KeyCode.mouse) && movie.isPlaying)
movie.Pause ();
}
}
What I want is when I click the video, the video plays, finishes, and if I click the video again, it restarts the video.

movie.loop = true;
Just Google next time: http://docs.unity3d.com/ScriptReference/MovieTexture-loop.html

I think what is needed is a check to see if the movie is finished playing or not.
I've not done any work with movies in Unity, so this is hypothetical, but something like this might work:
if (Input.GetKeyDown(KeyCode.Mouse0) && movie.hasFinishedPlaying)
{
movie.Play ();
}
What this sort of pseudocode is saying is that, if the movie has finished, and we click the mouse down, then we play the movie again.
I've just glanced at your code again. What you seem to be doing is doing a pause method in the OnMouseDown function, and setting the movie.loop to true.
However, setting something to true should be like this:
movie.loop = true;
And not like this:
movie.loop = true();
Unless it is different for using movies in Unity, but I don't know :) Give it a try!

Related

Hide vision of image temporarily in Unity

I'm going to enable bloody screen when got attack then disble it for two seconds.
The first way I tried is using SetActive (true/flase) .
It could work once but never worked back anymore.
I found the question by google, it seems that function will disable everything of that component.
So I found the second way which is using Image Class to do this.
but I not sure whether the way I used correctly or not.
The error msg : Object reference not set to an instance of an object
First Way (working once)
public class GameControllerScript : MonoBehaviour {
public GameObject bloodyScreen;
void Start () {
bloodyScreen.gameObject.SetActive (false); // disable at first
}
void Update () {
}
public void zombieAttack(bool zombieIsThere ){
bloodyScreen.gameObject.SetActive (true);
StartCoroutine(WaitTwoSeconds());
}
IEnumerator WaitTwoSeconds(){
yield return new WaitForSeconds (2f);
bloodyScreen.gameObject.SetActive (false);
} }
Second Way (not working)
public class GameControllerScript : MonoBehaviour {
public Image image;
void Start () {
GameObject go = GameObject.Find("Canvas");
if (!go)
return;
image = go.GetComponent<Image>();
image.enable = false;
}
void Update () {
}
public void zombieAttack(bool zombieIsThere ){
image.enabled = true;
StartCoroutine(WaitTwoSeconds());
}
IEnumerator WaitTwoSeconds(){
yield return new WaitForSeconds (2f);
image.enabled = false;
} }
Sorry for my english if soemthing is not clear.
What my object likes https://i.stack.imgur.com/DChuS.png
there are so many ways of doing the BLOODY SCREEN.
1.)
STEP 1
Make an array of texture then put all of your texture there
STEP 2
On your OnTriggerEnter or OnCollisionEnter or what ever function you want and try implementing this code
Texture[] arrayOfTexture = new Texture
foreach(Texture textures in arrayOfTexture){
//set the alpha here from 1-0/0-1
}
2.)
You can do it also in an Update() function and put it on a timer you can do it something like
float timer = 10f;
void Update(){
timer -= time.DeltaTime;
if(timer < 1){
//reset timer here
}else{
//do the alpha thing here
}
}
void ResetTimer(){
timer = 10f;
}

Detect when VideoPlayer has finished playing

I have a MovieController class that manages videos in my project. I'm using the new video player component introduced in Unity 5.6.
I would like to call a method when a movie has finished playing. So far, this method is only a Debug.Log, as you can see:
using UnityEngine;
using UnityEngine.Video;
public class MovieController : MonoBehaviour
{
private VideoPlayer m_VideoPlayer;
void Awake ()
{
m_VideoPlayer = GetComponent<VideoPlayer>();
m_VideoPlayer.loopPointReached += OnMovieFinished; // loopPointReached is the event for the end of the video
}
void OnMovieFinished(VideoPlayer player)
{
Debug.Log("Event for movie end called");
player.Stop();
}
}
My issue is that the OnMovieFinished is not called at the end of the video, and I just end up with a black screen and nothing in the console.
I don't trust or use the events from the VideoPlayer API because I've ran into problems with them too. What you see is a bug that hasn't been fixed for months.
If you want to detect if video has finished playing, use a coroutine to to check videoPlayer.isPlaying every frame in a while loop. When the while loop exists, it means that the video has finished playing.
while (videoPlayer.isPlaying)
{
yield return null;
}
//Done Playing
I can't test this right now to check if the pause function affects videoPlayer.isPlaying but you can test that by yourself.
Another way to do this is to check if frame is the-same as frameCount. When this is true, you know that the video has finished playing.
if(videoPlayer.frame == videoPlayer.frameCount)
{
//Video has finshed playing!
}
If none of these solved your problem then file for a bug report.
Funnily enough, this still doesn't work completely as expected in Unity 2018.4.25 (current version I'm working with). Playing videos on start-up will often result in isPlaying being false (jumping out of the video without playing it, whilst and testing for
(videoPlayer.frame == videoPlayer.frameCount)
doesn't seem to work reliably on mobile devices (android) as the video will stop playing (isPlaying == false) before the video has played all its frames (usually a couple short, which I assume is frame skipping).
I found
if (( videoPlayer.frame) > 0 && (videoPlayer.isPlaying == false))
captures the use case problems I was running into on mobile, however there may be more interesting use cases and combinations to deal with. I put the test above into an update() rather than a co-routine.
HTH.
using UnityEngine.Video;
private VideoPlayer vid;
private float beginning;
void Awake()
{
vid = GetComponent<VideoPlayer>();
beginning = Time.time;
vid.Play();
StartCoroutine(waitmethod());
}
IEnumerator waitmethod()
{
while (Time.time - beginning < vid.length)
{
yield return null;
}
runyournext();
}
You can use
videoPlayer.loopPointReached += OnMovieFinished;
//the action on finish
void OnMovieFinished(UnityEngine.Video.VideoPlayer vp)
{
vp.playbackSpeed = vp.playbackSpeed / 10.0F;
}
you can see more here https://docs.unity3d.com/ScriptReference/Video.VideoPlayer.html

Start a movie on click

I have been having difficulty getting my movie to start playing once a certain button is hit. I can get it to work with void Start() but then the video starts playing as soon as the scene is loaded which I don't want. I have tried this for when the button is pressed to start playing the movie.
public MovieTexture myMovie;
public RawImage myLayer;
private new AudioSource audio;
public void onClick()
{
GetComponent<RawImage>().texture = myMovie as MovieTexture;
audio = GetComponent<AudioSource> ();
audio.clip = myMovie.audioClip;
myMovie.Play ();
audio.Play ();
}
The movie will show but not actually play. I'm sure I'm missing something obvious but as I am a noob at coding I can't figure out what it is. Any help would be greatly appreciated!
Make a custom method which will contain
void Play()
{
myMovie.Play ();
audio.Play ();
}
and assign it to the button component in the inspector
EDIT:
I meant, don't use onClick as you use Start etc, it's not executable like that. There are 2 ways:
1) You make a custom method (called whetever you want) e.g as I listed above and assign it to the onClick field in the inspector, press +, add a script and select a method from that script;
2)
public Button yourButton;
void Start () {
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){
Debug.Log ("You have clicked the button!");
}
like in the reference: docs.unity3d.com/ScriptReference/UI.Button-onClick.html
You can add a Video Player using Create -> Video -> Video Player
Set video player video clip, Render Mode as Camera Far Plane and Select camera as Main Camera
Create script as given below. Just call the playMovie() method in any button event

Sound stops working when function's added

When I add EndGame();
The sound stops playing when the game ends.
If I remove the function, the sound plays fine.
I tried adding the gover.Play to EndGame, but that didn't work either.
This bug doesn't really make sense to me as to why it's happening.
Happens in both Editor and on live device.
Thank you.
Here is my code:
Update() {
if (Input.GetMouseButtonDown(0))
{
}
else
{
AudioSource[] aSources = GetComponents<AudioSource> ();
perfecthit = aSources [0]; // Works
gover = aSources [1]; // Works without EndGame()
miss = aSources [2]; // Works
gover.Play ();
EndGame ();// Adding this makes gover.Play stop working
}
}
private void EndGame()
{
Social.ReportScore (scoreCount, "--", (bool success) => {
//SUCCESS or FAIL
});
PlayerPrefs.SetInt("byte", PlayerPrefs.GetInt("byte") + scoreCount / 2);
if (PlayerPrefs.GetInt ("score") < scoreCount)
PlayerPrefs.SetInt ("score", scoreCount);
gameOver = true;
endPanel.SetActive (true);
theStack[stackIndex].AddComponent<Rigidbody>();
stack.SetActive (false);
demoObj.SetActive (true);
}
I am assuming that it stops playing due to the AudioSource no longer being available.
Inside the EndGame() you are setting stack.SetActive (false);. If this AudioSource is attached to the object, then it will be no longer available. Especially considering you are re-obtaining your AudioSources At least 30 times a second!
With that I would also like to advice you to move your audio logic outside of the Update and maybe look into using the Start, or awake instead

Fading out animated Unity loading screen

I am trying to have a simple animated loading screen between my menu scene and the game scene. I am trying to do this by loading the game scene in my loading scene asynchronously. I also want the loading screen to fade in and fade out.
I got the fade-in to work. However, I have two problems which I have been working on for hours, but without any succes. These problems are:
I cannot get the fade-out to work. I tried setting the 'allowSceneActivation' to false for my asynchronous loading, however this causes the loading to not occur at all. Removing this line makes the game load, but it then lacks the fade out.
The animation works very (and I mean VERY) choppy. I understand that the game is loading stuff, so I expect it to be bad, but it's litterally doing a frame every 2 seconds. I tried using a low thread priority (see code below), but no luck. I found people with similar problems, but the frames turned out reasonable when using a lower thread priority.
This is my code for the loading screen:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LoadIntro : MonoBehaviour {
private bool loaded;
private bool fadingOut;
private bool loading;
AsyncOperation async;
void Start(){
loaded = false;
fadingOut = false;
loading = false;
Application.backgroundLoadingPriority = ThreadPriority.Low;
}
// Use this for initialization
void Update() {
//wait for loading screen to fade in, then execute once
if (!GameObject.Find ("SceneFader").GetComponent<Image> ().enabled && !loaded && !loading) {
loading = true;
async = Application.LoadLevelAsync(mainMenuButtons.leveltoload);
async.allowSceneActivation = false;
StartCoroutine (LoadLevel (async));
}
//if next scene is loaded, start fading out loading screen
if (loaded) {
GameObject.Find ("SceneFader").GetComponent<SceneFadeInOut> ().FadeToBlack();
fadingOut = true;
}
//when faded out, switch to new scene
if (GameObject.Find ("SceneFader").GetComponent<Image> ().color.a >= 0.95f && loaded) {
async.allowSceneActivation = true;
}
}
IEnumerator LoadLevel(AsyncOperation async){
yield return async;
Debug.Log("Loading complete");
loaded = true;
}
}
I have a seperate piece of code for the actual fading, which the code above calls:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SceneFadeInOut : MonoBehaviour
{
public float fadeSpeed = 1.5f; // Speed that the screen fades to and from black.
private bool sceneStarting = true; // Whether or not the scene is still fading in.
public bool sceneEnding = false;
public string scene;
private Image fadeTexture;
void Awake ()
{
fadeTexture = GetComponent<Image>();
}
void Update ()
{
// If the scene is starting...
if(sceneStarting)
// ... call the StartScene function.
StartScene();
if (sceneEnding)
EndScene();
}
void FadeToClear ()
{
// Lerp the colour of the texture between itself and transparent.
fadeTexture.color = Color.Lerp(fadeTexture.color, Color.clear, fadeSpeed * Time.deltaTime);
}
public void FadeToBlack ()
{
// Lerp the colour of the texture between itself and black.
fadeTexture.color = Color.Lerp(fadeTexture.color, Color.black, fadeSpeed * Time.deltaTime);
}
void StartScene ()
{
// Fade the texture to clear.
FadeToClear();
// If the texture is almost clear...
if(fadeTexture.color.a <= 0.05f)
{
// ... set the colour to clear and disable the GUITexture.
fadeTexture.color = Color.clear;
fadeTexture.enabled = false;
// The scene is no longer starting.
sceneStarting = false;
}
}
public void EndScene ()
{
// Make sure the texture is enabled.
fadeTexture.enabled = true;
// Start fading towards black.
FadeToBlack();
// If the screen is almost black...
if (fadeTexture.color.a >= 0.95f) {
// ... reload the level.
if (scene == "") Application.Quit();
else Application.LoadLevel (scene);
}
}
}
Does anyone have an idea how to solve the issues described above? I've litterally tried every topic I could find, but none of them seem to work. Building my game did not resolve the issues either.
Many thanks in advance!
You are fading out when scene loading gets done. What are you expecting when loading is done? :)
//if next scene is loaded, start fading out loading screen
if (async.isDone) {
GameObject.Find ("SceneFader").GetComponent<SceneFadeInOut> ().FadeToBlack();
fadingOut = true;
}
Obviously it will change the scene and you code doesn't getting enough time to perform fade-out operation. :)
For instance if consider your point. You wrote,
//if next scene is loaded, start fading out loading screen
if (loaded) {
GameObject.Find ("SceneFader").GetComponent<SceneFadeInOut> ().FadeToBlack();
fadingOut = true;
}
//when faded out, switch to new scene
if (GameObject.Find ("SceneFader").GetComponent<Image> ().color.a >= 0.95f && loaded) {
async.allowSceneActivation = true;
}
in Update. Here your loaded check doing 2 things.
1- Start fading out.
2- Switching scene.
Again, why it should wait for fading it out completely while its getting loaded and you are checking alpha >= 0.95 which should execute at first frame when you get loaded to true, because I believe that in first frame alpha would be greater than 0.95.

Categories

Resources