So I am currently making a game where you are running and defeating enemies. When you get to the boss and kill him he has a death sound, but what happens is that is plays the death sound all distorted. I don't know what is going on, sometimes are better than others but they are all distorted. MonsterA is my boss Monster and enemy health is his health. here is my code(This is in the Draw() Method):
if (enemyHealth == 0)
{
sprite.PlayAnimation(deathAnimation);
if (spriteSet != "MonsterA")
{
killedSound.Play();
}
if (spriteSet == "MonsterA")
{
bossKilledSound.Play();
}
isDead = true;
}
Put your code in the Update method. The Draw method is ment (pretty much) only for drawing. Also, it's not very clear to me, but the Draw function does't fire just every time after Update. I think it's kind of async, but watis for Update. It's a foggy topic for me, but try putting that code in Update instead of Draw. If that's not the case, try running the game on another PC that is much slower or much faster than the one you are debugging on. That should lead you to the next clue why is this happening.
EDIT:
... assuming that you are not starting the sound on every fire of Draw/Update, witch is not likely because from your explanation, other sounds play well, and only this one is the problem.
Related
I am currently working on translating a VR game to the Oculus Quest 2 from a PC standalone version. In this game, the game menu cannot be accessed by the player wearing the headset, as it is not visible to the player; it is instead accessed by another party at the computer itself. When the person at the computer clicks, start game, a number of processes begin, including a coroutine to spawn multiple instances of a game object in a non-player enemy's hands.
Part of the translation process includes allowing the player to start the game from the Oculus Touch controllers, I am attempting to implement a feature where either of the four face buttons will start the game.
if (OVRInput.GetDown(OVRInput.Button.One) || OVRInput.GetDown(OVRInput.Button.Two) || OVRInput.GetDown(OVRInput.Button.Three) || OVRInput.GetDown(OVRInput.Button.Four))
{
startGameClick();
}
However, it seems like calling startGameClick(); more than once, whether in the same script or otherwise, causes the game to not run certain processes, chief among them the ball spawn coroutine. This causes the NPC enemies to activate their throwing animations without having a ball to throw, and they do not return to their idle animations afterwards. I am unsure why this is, however it has been a major roadblock in attempting the platform translation.
Additionally, this is the startGameClick(); function:
// If the start game button is clicked
public void startGameClick() {
StandaloneServer.startgame = true;
if (Master.usingMM && ServerController.IsServerReady())
Master.ready = true;
else if (!Master.usingMM)
Master.ready = true;
roundController.startInput();
beginGameButton.GetComponentInChildren<Text>().text = "In Progress";
beginGameButton.interactable = false;
}
My assumption is that one of the references in this function is the source of the issue, but I cannot pinpoint which one.
Base Information
Unfortunately, to answer your question, we would need to see all of the related scripts for this function which just isn't feasible as that would also require us to be kind enough to sift through your code to find your error.
A Cheap Solution
However, there is a cheap solution to your issue. You can simply reload the scene (or reset the script if it's DNDOL) and it should work again.
It seems I've found a solution at long last.
Instead of calling the startGame() function again, I decided to invoke onClick() to simulate the effect of clicking the button with a mouse, although the player is actually touching the button in the VR space. This worked, and the game is running as it should.
Original question on the Unityforums here
I've been trying to get an animation to not only slow down and speed up, but also play backwards depending on user input for my Hololens-application. I am using the Mecanim system, not legacy animations.
The whole thing is supposed to happen at runtime, through dynamic user input.
I know that it's possible through scripting, as I had it working before I lost local progress and some files during some Unity-Collaborate issues. As stupid as it sounds, since then I have not been able to remember what I did different from my current approach.
Right now I'm manipulating the value Animator.speed, but that only works for values >= 0.
Any help would be greatly appreciated!
Edit: In case the link is not working or visible for anybody, here is my code:
private Animator anim;
//...
anim = gameObject.GetComponent<Animator>();
//...
public void OnManipulationUpdated(ManipulationEventData eventData)
{
if (anim.isActiveAndEnabled)
{
anim.speed = eventData.CumulativeDelta.x;
anim.Play("KA_Cover_Anim");
return;
}
//...
}
Edit2: Incorrectly marked as dupicate! The linked question does not regard a similar problem and required a different solution
Edit3: For clarification, the linked "duplicate" uses the legacy animation system which is irrelevant for my question. In Mecanim, the new animation system in Unity 5.xx, you can not access the Animations directly as shown in the selected answer. Neither is it possible to alter the animation speed as shown in in the second answer.
I'm not exactly sure what you're end goal is, but you can play animations backwards and at different speeds by using a parameter.
On the animation state, you can make it watch a parameter and multiply it against the default speed of the animation. All you need to do in code is something like
animator.setFloat("Speed",-1.0f);
Hope that helps.
I'm doing a chess game with AI in it.
There are some functions that handle the rule of game, like DoMove(), DoSkill().
But for some reasons (most for display cool effects), the function return type is IEnumerator instead of void. So the usage of the function look like this :
yield return StartCoroutine(DoSkill());
Now the problem comes, AI is a heavy work, but I've heard that Unity's Coroutines is not suitable for heavy calculating. When I change functions to IEnumerator, the speed of AI obviously getting very slow.
I'm sure that there isn't any WaitForSeconds(someFloat) will be execute in AI(I use some parameter & if/else to skip it), it just seems like the performance is really poor if I continuously call StartCoroutine again and again.
The possible solution I can think of is write two kind of DoSkill() funtion, one's return type is void , the other is IEnumerator. but it's really not a good way. because I have to maintain lots of similar functions, and it's ugly too.
Any suggestions would be greatly appreciated.
Coroutines are nothing magical - they are a way to have a function keep giving up control mid-execution, and continuing on next time they are pumped. They exist really to allow developers to avoid writing multi-threaded code.
The reason they don't work for heavy calculations is that they are executed in the main thread, so any long running code would effectively kill your frame rate.
They do work where you know you can do a small deterministic pieces of work and defer for next time - such as processing downloaded byte streams, copying data, etc. So if you are running smoothly at 60FPS you know you have 16 ms to do everything in a frame, and heavy calculations might be variable in time and hard to know ahead. If you exceed 16 ms in total (everything including your calculation) the FPS will slow down and the game will appear jerky.
I suggest in your case you run the calculations in a background thread. It's basically:
using UnityEngine;
using System.Threading;
public class ChessAI : MonoBehaviour
{
Thread aiThread;
void StartAI()
{
aiThread = new Thread(new ThreadStart(AIThread));
aiThread.Start();
}
void AIServer()
{
// do stuff here - be careful of accessing data being changed by main thread
}
public void OnApplicationQuit()
{
// It is crucial in the editor that we stop the background thread when we exit play mode
aiThread.Abort();
}
}
I Need to apply DontDestroyOnLoad on Scene.is it possible?
I Need to Do not disturb the scene when going in to another scenes also.here i'm sending mail,when ever clicking send button its going to authentication in mail server in this time my scene idle means not responding anything until come back to the response from mail server,so on that time i show one loading bar in my scene.this is not do process.the entire scene is hang until came response from mail server,so how to solve this?
void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
After reading so many non-answers I finally found the answer in a Unity forum. DontDestroyOnLoad ONLY works if the game object in question is at a "root level" meaning right under the scene, not nested under any other object. This is not mentioned anywhere in the documentation.
When loading a new level, scene, all Game Objects of the previous scene are destroyed by Unity.
If you want to protect a Game Object you can use the function.
DontDestroyOnLoad(gameObject);
It is important to note that when you say: this.gameObject you are pointing to pretty much the same thing, it just happens that this points directly to the script attached to that gameObject. So you don't need the this part, just gameObject will do.
Ideally you could protect that gameObject inside void Awake()
void Awake()
{
DontDestroyOnLoad(gameObject);
}
The above code will prevent Unity from destroying that gameObject unless your game closes completely or at a later point you call Destroy() on it. That means you can change from scene to scene and the gameObject will survive. However, if you make it back to the scene that creates that gameObject you are protecting you may run into problems if you do not have the logic implemented that prevents you from protecting a second, third, or many of that gameObject.
Your second question, if I understand it correctly:
You want to send mail when you change scenes, but your progress bar wont progress while changing scenes, it just stays there, static.
If that is the case then your problem is in Application.LoadLevel(sceneName); If you have the free version of Unity, then you need to come up with your own creative way of showing that progress bar, because Application.LoadLevel() will halt everything until it takes you to the new scene.
I don't completely understand what you are saying.
But because in your context, this in represents most probably a Monobehaviour, try the following:
void Awake() {
DontDestroyOnLoad(this.gameObject);
}
or
void Awake() {
DontDestroyOnLoad(gameObject);
}
See http://docs.unity3d.com/Documentation/ScriptReference/Object.DontDestroyOnLoad.html
I recommend you use a coroutine, with the 'yield' statement
check out this documentation of the WWW class, which likewise involves writing code to cope with waiting for a response from the web, without hanging your Unity3d program
coroutines are pretty powerful if you're working with tasks that take more than a frame or two. Richard Fine (AltDevBlog) has posted a really detailed description of what they are and how to use them, which I thoroughly recommend.
I've modified my physics from the last post: Updating physics engine ina separate thread, is this wise? like so:
public void PhysicsThread()
{
int milliseconds = TimeSpan.FromTicks(333333).Milliseconds;
while(true)
{
System.Threading.Thread.Sleep(milliseconds);
world.Step(milliseconds / 1000.0f);
}
}
As before it's running in its own thread. I'm finding something odd which I'm not sure I quite understand, it's a bit difficult to explain so I made a video recording of it: http://www.youtube.com/watch?v=qFf6oSRfVt8
If you look carefully you can see the object being fired from the cannon occasionally stutters and appears to move backwards a set amount of distance. This is only noticable on fast moving objects (such as the projectile being fired).
This has baffled me completely. I've even created a system where I cache the position of bodies in the game logic thread so that as the physics thread may update bodies positions it won't affect the positions being read in by the game logic until an update function is called within the game logic thread which updates the physics bodies positions for the game logic to read.
Any ideas what aspect of multithreading may be causing this issue? I don't think it's the physics engine updating the bodies positions during game logic and drawing as I've alrady mentioned I cache that and it remains constant throughout...
My first guess is that you may have a classic race condition, where multiple threads are competing to update the object's position without locking or ordering guarantees.
You can check Wikipedia to learn more about race conditions, locking, and other fundamentals of multithreading/multiprocessing.
It's hard to say more without seeing more of your code, especially the part that does the update.
Edit: One thing you can do is to store DateTime.Now on each loop, and compare it with the previous value. If your time delays are inconsistent you'll see it.
Another thing to check is to see how long your world.Step() function is taking to execute (again using DateTime.Now and some logging, or whatever).
If both of these indicate consistent timing, then my suspicion would fall on the physics engine. Check the position of the object before and after calling world.Step(), and if you see any weird jumps that should tell you where to look.
This should probably be a comment, but it would be difficult to post code. If you're trying to do realtime then this code is prone to time jitter as there's no guarantee that Thread.Sleep will sleep for the perscribed time. I'd use a stopwatch to measure elapsed time and use that to drive your world.
public void PhysicsThread()
{
int milliseconds = TimeSpan.FromTicks(333333).Milliseconds;
var stopwatch=System.Diagnostics.Stopwatch.StartNew();
while(true)
{
System.Threading.Thread.Sleep(milliseconds );
world.Step(stopwatch.ElapsedTicks);
stopwatch.Restart();
}
}