I am trying to only allow the particle system to emit particles when something is visible. The particle system knows when to start if a Boolean named avail is true. The code I thought would work for this is the following:
if (avail)
{
GetComponent<MeshRenderer>().enabled = true;
GetComponent<ParticleSystem>().enableEmission = true;
print("Mesh enabled");
}
However, this failed. I also tried:
if (avail)
{
GetComponent<MeshRenderer>().enabled = true;
GetComponent<ParticleSystem>().emission.enabled = true;
print("Mesh enabled");
}
However, this too failed. On every site I have searched in, these two "solutions" came up but they don't work for me. the first example said "this method of doing this is obsolete" and the second example says I can't set "emission.enabled" to a variable because it is a getter not a setter. Any help with figuring this out is extremely appreciated.
I don't have unity opened right now, but I think that
GetComponent<ParticleSystem>().Stop();
is what you need. You can restart the system using
GetComponent<ParticleSystem>().Play();
Also, if you do this often, you should consider keeping your particle system in a class variable.
Related
I have a Unity game that runs on both Android Cardboard and Oculus Go. I'm trying to determine whether the Go's controller is connected.
I imported the Oculus integration package from the Unity asset store (though I'm not sure it's actually required... I've gotten the impression that Oculus support has been built into Unity since at least 2018.3, if not 2018.2 or earlier). I also deleted Cardboard and added Oculus as Virtual Reality SDKs in Player settings.
The following code executes in the Start() method that initializes most of my game:
void Start() {
// ...
if (OVRInput.IsControllerConnected(OVRInput.Controller.RTrackedRemote)) {
// do something visible
}
// ...
}
The problem is, OVRInput.IsControllerConnected(...) always returns false, and the code inside the block never executes.
Other things I've tried:
Moved the call to OVRInput.IsControllerConnected() from Start() to Update(), just in case it's an initialization-time issue. No success. Same result.
Instead of using OVRInput.Controller.RTrackedRemote as the argument, I tried the other objects... LTrackedRemote, Active, All, Gamepad, LTouch, RTouch, Remote, Touch, Touchpad, and None. All of them except '.None' returned false. '.None' returned true.
I set a breakpoint on the line calling OVRInput.IsControllerConnected() (after moving it to Update()), then called OVRInput.GetConnectedControllers() in VS2017's immediate window... it returned "None". Ditto for OVRInput.GetActiveController().
The game itself began as Android Cardboard. So far, the only major changes I've made to it are:
Importing the Oculus support library from Unity's Asset store.
In Player -> XR Settings, I deleted "Cardboard" and added "Oculus" as a VR SDK
In Build Settings, I changed the build method from 'Gradle' to 'Internal' (Gradle builds failed... I've seen posts from summer 2018 saying it's a Unity bug, but I'm not sure whether that's still current info... regardless, changing from Gradle to Internal made THAT error go away).
Most notably, I have NOT added any Oculus-specific prefabs, or changed/removed any of the GoogleVR-specific prefabs.
I know you tried moving IsControllerConnected to Update but did you try GetConnectedControllers in Update after a second? That's what did the trick for me. So in Update():
// initialize hand once after one second of start
if(!handInitialised){
initialWait += Time.deltaTime;
if(initialWait > 1f){
OVRInput.Controller c = OVRInput.GetConnectedControllers();
if(c == OVRInput.Controller.LTrackedRemote || c == OVRInput.Controller.LTouch){
//
}
//
handInitialised = true;
}
}
I've made a dice app as a project to learn to work with unity (it was so good in my eyes that I put it on the google play store) but when I downloaded it from there, the Start function of at least 2 scripts isn't called and I have no idea whether the other Start functions are being called.
Here you can see 2 of the Start functions that aren't called
void Start()
{
light = light.GetComponent<Light>();
GetComponent<Button>().onClick.AddListener(TaskOnClick);
rawImage = GetComponent<RawImage>();
isLockMode = false;
rawImage.texture = getIconLock(isLockMode);
}
void Start()
{
Screen.fullScreen = false;
Dice.AddDie();
Input.gyro.enabled = true;
GlobalConfig.onShowShadowsChanged += onShadowsEnabledChange;
}
They work when I use Unity Remote on my smartphone and they also work when I just use unity without the remote...
the first script is attached to a UI element and the second script is attached to an empty GameObject called 'App'
It's also even more weird because they used to work but then I switched pc's (but used the same code).
I think something is wrong with the building itself
Found out the problem, the build was generating two files, an .apk and an other .odb or somethingl ike that (might be another extension). I had to untick 'split application binary' in the player settings
I'm trying to make a multiplayer game and in my program there is a spawnSpots code that I made and it's saying that it doesn't exist but it clearly does.
Here's the code:
void Start()
{
spawnSpots = GameObject.FindObjectOfType<SpawnSpot>();
}
Then there is:
if(spawnSpots == null)
{
Debug.LogError("No Spawns Placed.");
return;
}
SpawnSpot mySpawnSpot = spawnSpots[Random.Range (0, spawnSpots.length)];
So everytime the word spawSpots is written, the error is saying:
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'spawnSpots' does not exist in the current context Multiplayer-FPS.CSharp C:\Users\desha\Documents\Multiplayer-FPS\Assets\NetworkManager.cs 15 Active
How can I fix this?
Ok if you are setting up a networked multiplayer game then you will need to have a NetworkStartPosition component on each of your spawn point in the scene.
It is also worth noting that the NetworkManager you would need in your scene also has some spawn settings. Including a spawn method, which if you select "round robin" will randomly spawn players at each of your NetworkStartPositions for you.
Hope this helps.
Here is a link to an excellent video covering the basics of network multiplayer. It is by far the most useful I have found. UnityNetworkTutorial
You are using GameObject.FindObjectOfType incorrectly, it looks like you want to set up an array then pick a random one. Lookup arrays, how to add to the array.
find object of type: https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
Heey,
We created a game with Monogame but we got the following problem.
We got a themesong that plays when you have loaded the game now is the problem that the themesong sometimes plays but sometimes just doesn't. We convert it by the XNA pipeline to a wma and load it into our game with the .xnb together but just sometimes the music doesn't wanna start.
We just use the standard code for starting a song and all of this code does fire.
internal void PlayBackgroundMusic()
{
if (MediaPlayer.GameHasControl)
{
MediaPlayer.Volume = mainVolume;
MediaPlayer.Play(backgroundMusic);
MediaPlayer.IsRepeating = true;
}
}
We also use SoundEffects but these work 100% of the time it's only the song that won't play everytime you start. Windows RT runs it fine by the way.
Make sure that the debugger gets into the if statement through debugging (or remove the statement temporarily). Another possibility might be that the function is running before the game is fully initialized. You could try delaying the function until the game has been fully loaded.
PS: I can't comment on questions yet so here's an answer.
Edit:
Alright, after some messing around with the Song class and looking in the implementation in MonoGame I came to the conclusion that the SoundEffect class is easier to use and better implemented.
backgroundSound = Content.Load<SoundEffect>("alarm");
protected override void BeginRun()
{
// I created an instance here but you should keep track of this variable
// in order to stop it when you want.
var backSong = backgroundSound.CreateInstance();
backSong.IsLooped = true;
backSong.Play();
base.BeginRun();
}
I used this post: using BeginRun override to play the SoundEffect on startup.
If you want to play a song, use the Song class. But make sure you are using ".mp3" instead of ".wma" before converting them into ".xnb".
backgroundMusic = Content.Load<Song>("MainTheme");
MediaPlayer.Play(backgroundMusic);
MediaPlayer.IsRepeating = true;
See MSDN.
I am trying to play a short sound when user taps on the specific button. But the problem is that I always receive Object reference not set to an instance object. means Null!
I first tried MonoTouch.AudioToolBox.SystemSound.
MonoTouch.AudioToolbox.AudioSession.Initialize();
MonoTouch.AudioToolbox.AudioSession.Category = MonoTouch.AudioToolbox.AudioSessionCategory.MediaPlayback;
MonoTouch.AudioToolbox.AudioSession.SetActive(true);
var t = MonoTouch.AudioToolbox.SystemSound.FromFile("click.mp3");
t.PlaySystemSound();
Let me notice that "click.mp3" is in my root solution folder and it is flagged as Content.
The other approach is MonoTouch.AVFoundation.AVAudioPlayer.
var url = NSUrl.FromFilename("click.mp3");
AVAudioPlayer player = AVAudioPlayer.FromUrl(url);
player.FinishedPlaying += (sender, e) => { player.Dispose(); };
player.Play();
But same error. I googled it and I see that many people has this problem. We need to know whether it is a bug or not.
About using SystemSound and MP3 see this question and answer: Playing a Sound With Monotouch
For AVAudioPlayer be aware that the following pattern is dangerous:
AVAudioPlayer player = AVAudioPlayer.FromUrl(url);
player.FinishedPlaying += (sender, e) => { player.Dispose(); };
player.Play();
since Play is asynchronous. This means the managed player instance can get out of scope before FinishedPlaying occurs. In turn this out of scope means the the GC could already have collected the instance.
A way to fix this is to promote the player local variable into a type field. That will ensure the GC won't collect the instance while the sound is playing.
Your code looks correct (I compared to the code here, which is able to play audio).
What might be the problem is that the audio file isn't included in the app bundle somehow. You can easily check it with this code:
if (!System.IO.File.Exists ("click.mp3"))
Console.WriteLine ("bundling error");
In most cases it would be the File does not exist. If you are like me, and you made sure that the file exists. Ensure the following:
The Path of the file should be relative to your Class (ie: Sounds\beep.wav) (Absolute path did not work for me on the simulator)
Ensure that you are defining the SoundSystem in the class level. This is because MT has a ver agressive Garbage Collector and could dispose your SoundSystem before it even starts playing. see this question