Unity Start nog called on real build - c#

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

Related

Unity - My script stops working on Editor but works on my builds(android, ios)

Installed Unity Version is 2020.2.1f1
I'm developing an online multiplayer game using Unity. I have 2 different connection types; Http and Websocket(using Websocketsharp: https://github.com/sta/websocket-sharp, I've installed it using Nuget). Http get/post, Websocket connect/send/close works totally fine but when I call function (directly or by sending events) after response, most of the time my code inside that called function is not completed on editor(works fine on builds-android,ios). I'm not sure if this problem is related to http/websocket but it's related to online connection because I've experienced the same issue when I was developing a real-time multiplayer game using Unity & Gamesparks.
I can do basic functions like print etc. until I call one of the following functions loadscene, update UI, or call another function in same/different script(only first one of these works, everything after that won't run). Console doesn't show any error and game doesn't pause or crash. It runs on same fps but that part of the code won't continue. Other scripts/updates works fine. I've searched a lot but couldn't even find a related topic.
WebSocket Client:
void OnBattleResponse(object sender, MessageEventArgs messageEventArgs) {
string message = messageEventArgs.Data;
if (messageEventArgs.Data.Equals(Constants.WEBSOCKET_ERROR))
return;
var webSocketData = JsonUtility.FromJson<BattleResponseSerializable>(message);
switch (webSocketData.type) {
case 0:
seed = webSocketData.user1.seed;
opponentSeed = webSocketData.user2.seed;
_connectionManager.BattleGetStart(seed, opponentSeed);
break;
.
.
.
}
Connection Manager:
public void BattleGetStart(int userSeed, int opponentSeed) {
_gameManager.StartWave(userSeed, opponentSeed);
}
Game Manager
public void StartWave(int userSeed, int opponentSeed)
{
UserSeed = userSeed;
OpponentSeed = opponentSeed;
UserRandom = new System.Random(UserSeed);
OpponentRandom = new System.Random(OpponentSeed);
StartWaveTimer(); // After this nothing will be run, it's not related to startWaveTimer, any function that I've mentioned causes the same issue.
print("DOESN'T WORK"); // This doesn't work on Editor but works on builds
_spawner.ActivateSpawner(true); // doesn't work
}
I've found a trick to handle this situation but I didn't like it as a proper solution and don't wanna spend resources for Update calls. When I call function (directly or by sending events) after response, inside the called function I set bool to true and in Update call I call the necessary function when the bool is true and the code works totally fine.
---The Trick---
Game Manager
bool startWave;
public void StartWave(int userSeed, int opponentSeed)
{
UserSeed = userSeed;
OpponentSeed = opponentSeed;
UserRandom = new System.Random(UserSeed);
OpponentRandom = new System.Random(OpponentSeed);
startWave = true;
}
void Update() {
if (startWave) {
startWave = false;
StartWaveTimer();
print("WORKS"); // With this trick, it works on editor too.
_spawner.ActivateSpawner(true); // works
}
}
What can be the reason of my script working on builds but not on unity editor?
Thank you!
Advice for those who will experience that kind of issue:
As I've found out Unity is not Thread safe. Unity limits us on calling their API from another Thread, which causes this issue.
So you have to call your functions/methods from main thread instead of another thread.

Oculus Go's controller not detected by OVRInput.IsControllerConnected()

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;
}
}

Unity:Time.timescale =0 not working

I am trying to display player tutorial when the user 1st starts the game using playerpref and want the game to be paused, the problem i am facing is that Time.timescale=0 is not pausing the game when placed inside start (tutorialCanvas gets displayed), but works when is called by a button(Pause button).
Following is the code I use
void Start()
{
if (PlayerPrefs.HasKey ("test4") ==false ) {
tutorialCanvas.SetActive (true);
Time.timeScale = 0;
}
}
Time.timeScale = 0 is really messed up for me so what i could recommend you is that if you just want to pause something like pausing a movement of a character then you can try it like this :
GameObject PlayerScript;
if(Input.GetKey(KeyCode.P)){
//lets disable the playermovement script only not the whole object
PlayerScript = GetComponent<PlayerMovement>().enabled = false;
}
I've been stucked there also so i made an alternative way. And you can also visit this one. If you want a free of that asset you can get it here
I had this issue recently, although it was only doing it on a build, and not in the editor. Changing timeScale to something like 0.0001f would fix it, but that wasn't a great solution. Creating an input settings asset (under Camera -> Player Input -> Open Input Settings) seemed to have fixed it for the builds.

Trouble stopping particle emission in unity

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.

Song doesn't play all the time in Monogame

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.

Categories

Resources