#archived-code-general
1 messages Β· Page 368 of 1
the script is using a reference to the SceneView type, which exists in UnityEditor namespace instead of the UnityEngine namespace, in other words, the SceneView type is only availably in the editor and not in builds
the reason it's failing is because it is trying to compile the class to include it in the build, but ofcourse it can't, since SceneView doesn't exist in builds
okay and hov do i fix it?
easiest solution is to just wrap the class with conditional compilation statements like this https://gdl.space/pumuvebara.cs
#IF UNITY_EDITOR .... #endif makes is so that all the code between is only compiled if the platform is the unity editor, else the code gets ignored
okay thanks
Right, but then the image shown is a lot darker than the original. What could be causing this?
hi
Hello!
if i want to instantiate a particle effect before a box gets destroyed
how do i do it ?
like cuz after the object is destroyed the particle is also destroyed with it
Spawn it as a separate object.
I suppose you're using unity's particle pack, all the particles are prefabs anyway
In addition to instantiating the prefab seperate from the object there's a timer script you can attach that will make the particle disappear after a few seconds
Heyo, so I have a hit box(collider) animated aligned with the player animation for when it attacks. My player flips when going/looking to the right direction, how would I flip the hitbox animation as well when i'm looking to the right direction?
animate the position of local values to the player
so animating the forward attack direction rotates with the player
Is there a way to create a custom AppDomain in Unity ?
Or any solution for load / unload plugins at runtime ?
load, yes. Unload, no
Yeah thats it.. Any tricky way to "unload" ??
nope, you cannot partially unload an app domain
That is a problem, this is not really viable to restart the game each time π¬
I have tried a lot of things beside the AppDomain but nothing works.. I have tried to unload all scripts references and do GC to collect and clean memory but nothing change π
if you want to put the effort into it you can have multiple app domains and use inter process communication to link them together
Whats a good RUDP project I could use?
Yeah but for example, i can't apply a Mono script on a gameobject from an external process :/
(If the monoscript is created in the dll and not in the game itself)
no, all Unity related stuff would have to be in the main AppDomain. But that is a design decision which can be dealt with
Is there a way to render only some objects in HDR and leave the rest in SDR? I'm working with a shader which only works properly when HDR is enabled. I have tried to render the main scene in SDR and then the objects in HDR with a separate camera, but I can't figure out how to overlay the HDR cam's output on the screen properly. Doing it with a UI RawImage (which draws a RenderTexture) works, but the objects I'm rendering have super low alpha values, so they are nearly invisible when shown on the SDR output. Maybe there's a way to somehow tonemap the HDR alpha values to SDR?
If I'm understanding this correctly, Unity's HDR automatically tonemaps the colors to SDR so that they can be shown on regular (SDR) displays such as mine, but the RT's alpha stays the same as the shader outputs it
On URP, there is camera stacking however in HDRP it does not seem to be as straight forward. Trying looking into the "Graphics Compositor" ? Never used it.
Oh, then you can either blit or not clear the buffer on one of the camera.
However, you should really consider switching to URP or HDRP if you want more intuitive support of such feature.
I have this code which makes a raid start. Each raid as the code does will spawn enemies and wait seconds for each to spawn. The thing I have now is that this won't let me have multiple raids to occur at once, and I believe it is due to the fact that the code will yield and wait. ```cs
IEnumerator SpawnRaid(Raid raid) {
yield return new WaitForSeconds(raid.startRaidTime);
DetermineRaidPathSpawnPoint(raid); // Determine spawn point for raid
foreach (EnemyType enemyType in raid.enemies) {
yield return new WaitForSeconds(enemyType.spawnDelayForThisEnemy);
int spawnedCount = 0;
int activeRaid = 0;
while (activeRaid < numberOfRaids) {
while (spawnedCount < enemyType.enemySpawnAmount) {
SpawnEnemy(raid.spawnPoint, enemyType, raid);
spawnedCount++;
yield return new WaitForSeconds(raid.spawnEnemyDelay);
activeRaid++;
print(raid.spawnEnemyDelay + " This is Raid Spawn Enemy Time Delay");
}
}
print("Raid Ended");
}
activeRaids--;
}The issue remains here I think, but the other issue is that I am calling foreach of the raids in each wave which make it wait for each other which isn't what I want.IEnumerator SpawnWaves() {
foreach (SOWaveData wave in waves) {
foreach (Raid raid in wave.raids) {
StartCoroutine(SpawnRaid(raid));
}
}```
If you do "StartCoroutine" for each raid you will have effectively one "SpawnRaid" execution per raid.
It has nothing to do with the Wait, but mostly because of your code.
Such as while (activeRaid < numberOfRaids).
So the issue is just how I call the Raids to start?
That being said, using coroutine this way is really, really not recommanded.
I do not know the issue, I just know it is not because an other raid is yield return.
Do you know how to make the logic happen the same in Spawn Raid with a Method instead of Coroutine?
Coroutine can work, but just creating a container for the SO data is another idea
but if you want to resolve your coroutine issues, consider debugging with breakpoints
It is not a question of using a method, but correctly designing your class to represent what you attempt to do will make everything easier. By example, if you were to stop a Raid it could cause some pretty hard to resolve situation.
Ideally, you would create a class "Raid" that handle all the logic.
public class Raid
{
public void Execute()
{
if(currentWave.IsEnded || Time.time > currentWave.StartAt + delayBetweenWave)
SpawnNext();
}
}
public class Wave
{
public void Spawn() {...}
}
Obviously this is a really bare bone implementation
I have a class for Raid that is part of another script. I can already try this
The thing is, how would I spawn enemies in that class if it isn't a monobehavior?
GameObject.Instantiate
Alright, I will try. Will let you know what happens.
And if it was truly an issue you could make an other script only for the spawning logic
No need to redefine your whole logic for a possible restriction like that
Instantiate doesnt work on pocos
Yes it does. Instantiate is also a static function
I am deciding just to create a new script called RaidManager. I'm not sure what you mean by changing Spawning Logic or making a new script for it.
yes but the type must be from UnityEngine.Object instead of System.Object
Which it is. He is spawning enemies not raid
And even if it was the case, the raid could easily be a monbehaviour
He probably was using the Instantiate from the UnityEngine.Object class and was wondering how to instantiate an object not from a MonoBehaviour
oh idk i read "it isn't a monobehavior? "
and then saw Instantiate, oh so i misunderstood?
No worries.
Is there a better way to handle the Raids when Spawning Enemies? I only used a Coroutine since they could Yield wait for seconds the specific amount I wanted.
public class WaveSO : ScriptableObject
{
[SerializeField] private int numEnemies;
public int NumEnemies
{
get { return numEnemies; }
}
public Wave InitWave()
{
return new Wave(this);
}
}
public class Wave
{
private WaveSO waveSO;
public int EnemiesRemaining = 0
public Wave(WaveSO waveSO)
{
this.waveSO = waveSO;
EnemiesRemaining = waveSO.NumEnemies;
}
}```
Usually what I like to do when creating a writable instance for the SO data
public class SOWaveData : ScriptableObject {
public List<Raid> raids = new List<Raid>(); // List of raids in this wave
}``` I just have one line of code. What is the extra there used for?
It's to create a writable instance to append to instead of creating a coroutine and creating local variables to it
then the idea is that on each update() you'd read in your list of Waves
public class SOWaveData : ScriptableObject {
public List<Raid> raids = new List<Raid>(); // List of raids in this wave
}
[System.Serializable]
public class Raid {
public RaidPathType pathType;
[Range(0.0f, 20.0f)] public int startRaidTime;
[Range(2.0f, 4.0f)] public float spawnEnemyDelay;
public float speedBoost;
public List<EnemyType> enemies = new List<EnemyType>();
public Transform spawnPoint;
}``` This is one script. Can't I use this and just make it work with Update instead of Coroutine?
Anything you can do in a coroutine you can do in Update
Does yield wait for seconds work on Update too?
usually by managing the instances in some form of a container you would iterate over each update
yield return is simply some timer if you think about it
Yeah
and you want it to not be a coroutine because?
I just need a way to wait for seconds. I guess I could use a simple timer, but I wasn't sure if doing so would result in the same issue. This issue is that the raids would wait for each other to finish, which I don't want.
Coroutines are fine too, but even what you're doing there should still be somewhat managed instead of creating them on a whim and forgetting
Should I change using a method instead?
I think it's more about defining your requirements well enough and writing code that matches.
Not that much a coroutine issue (but perhaps I am not understanding all the requirements of the system)
I haven't done a method since I don't know how to yield return and wait on them. I can't do them without a Coroutine.
A coroutine is effectively an automatic state machine. In state 1 it increasese a counter by deltaTime until some time is reached, in state 2 it spawns an enemy, in state 3... etc.
And that's more or less how you rewrite a coroutine into... something you can call each frame, lets say
I just encourage objects over coroutines because I find them easier to debug
otherwise like I was saying you'd probably want to start using breakpoints if you're running into issues and stepping through the code
It does give you more control... the state is kinda better defined and not behind the scenes. But I'm not sure that's the issue here.
The issue is that every time the first raid ends, the second doesn't wait for the seconds it is supposed to spawn the enemies. It ignores it. So then I have the second Raid just spawning enemies in stacks. I believe it is due to this Foreach loop ```cs
IEnumerator SpawnWaves() {
foreach (SOWaveData wave in waves) {
numberOfRaids = wave.raids.Count;
activeRaids = numberOfRaids;
foreach (Raid raid in wave.raids) {
StartCoroutine(StartRaid(raid)); // This here
}
yield return StartCoroutine(WaitForWaveToEnd());
yield return new WaitForSeconds(startNextWave);
}
}```
+1 for breakpoints and general debug skill - helps solve every problem faster π
you're starting all raids coroutines at the same time in parallel (in a sense)
if you want to wait for each raid, you need to yield return the StartCoroutine
I don't want each raid to wait for each other. I want them to start at the same time or have a delay that I specify
okay, so that's what you have in the code here
Can you explain more please?
you're starting all raids in parallel... so they should all be spawning (based on the code you just posted)
You're saying they are both starting at the same time?
foreach (Raid raid in wave.raids) {
StartCoroutine(StartRaid(raid)); // This here
}```
This will start as many raids as you got at the same time
It will start the coroutines anyway - they won't wait for each other
You are right. Then why do you think it cancels the delay for the spawn for the second one?
Anyway... best use breakpoints or debug.logs to see what's going on and where the problem is π
Me reading and executing 5 parallel coroutines in my mind is way less efficient than you checking the actual values at runtime π
Okay, but I am not sure where to debug. I tried a few area's and still not sure what the issue is.
any tips?
The issue is that this variable is 0 for the second raid Spawn Enemy Delay. raid.spawnEnemyDelay Any guess where it could be getting changed or override here? ```cs
IEnumerator StartRaid(Raid raid) {
yield return new WaitForSeconds(raid.startRaidTime);
// print("Raid Started");
DetermineRaidPathSpawnPoint(raid); // Determine spawn point for raid
foreach (EnemyType enemyType in raid.enemies) {
yield return new WaitForSeconds(enemyType.spawnDelayForThisEnemy);
int spawnedCount = 0;
while (spawnedCount < enemyType.enemySpawnAmount) {
SpawnEnemy(raid.spawnPoint, enemyType, raid);
spawnedCount++;
yield return new WaitForSeconds(raid.spawnEnemyDelay);
print(raid.spawnEnemyDelay + " This is Raid Spawn Enemy Time Delay");
}
}
activeRaids--;
}```
well, right click on the variable - find all references π
I forgot about that
It seems to be that there was no issue with the code at all. For some reason the Scriptable Objects were glitched and were having no delay. All I had to do was delete old Wave SO's and remake them. 
Is there a way I can make a Unity.Spline from a BezierCurve?
My main goal is to show something like this but in play mode (this is gizmo code)
Vector3 position = this.transform.position;
Quaternion rotation = this.transform.rotation;
var opaqueColor = Color.yellow;
// Draw bezier
Vector3 destinationPosition = this.destinationPortal.transform.position;
Vector3 destinationForward = this.destinationPortal.transform.forward;
Vector3 startTangent = position + (-this.transform.forward * 10f);
Vector3 endTangent = destinationPosition + (-destinationForward * 10f);
UnityEditor.Handles.DrawBezier(position, destinationPosition, startTangent, endTangent, opaqueColor, null,
2.5f);
Thing is with Unity.Spline I'm unable to set tangents manually it seems
An attempt I made but can't quite "connect the dots" π₯²
var startKnot = new BezierKnot(position);
var endKnot = new BezierKnot(destinationPosition);
var bezierCurve = new BezierCurve(startKnot, endKnot);
bezierCurve.Tangent0 = startTangent;
bezierCurve.Tangent1 = endTangent;
_spline = new Spline(new List<BezierKnot> {
new (bezierCurve.P0),
new (bezierCurve.P1),
new (bezierCurve.P2),
new (bezierCurve.P3),
});
This will look super square-y
I can also add BezierKNots directly to Unity.Spline but still, no tangent data
Im not quite sure, could be related to lighting, post processing, layers or multiple things, the RenderTexture should more-or-less have the same output as your camera (depending on the settings of the render texture), you should be able to see a preview of what your camera sees from the Scene view if you select it in the hierarchy (or disable all other cameras to see it in the Game view), if its also dark in the preview, it could be due to other factors unrelated to the render texture itself
it says your error is on line 19 but youre showing 170
also i think you might have to delete your library folder
it should regen and fix itself afterwards
Hey there, I know that having raycast target enabled on images consumes some performance, so I want to disable it in a default preset. Works well for TextMeshPro as well, but when I create a button, it needs to have RaycastTarget enabled on its image. Is there a way to change how objects are created via the right click menu in the hierarchy?
well i clicked on the error thingy and it sent me here
how do i delete the library folder?
if you right click on your asset folder in your project tab and click "show in explorer", you'll be sent to your file explorer. Then you should see the library folder there.
make sure your project is closed before you delete it though
depending on how large your project is, it might take a while for your library folder to regen upon startup, but that should fix your issue
so, im trying to transfrom a image from disk into base64 so i can generate ramdom Npcs with it(monster rancher style whre you put a cd you get a new creature, but in this case is images from the pc)
how do i do that?
mostly how i can transform a image from disk into a code i can run a algority over it
Check google pretty sure someone else asked the same question
This answer is equal to "ask chatgpt"
At least it's more reliable
you need System.Text.Encoding which can turn a byte array into a Base64 string
I absolutely hate my linux recognizes dotnet in terminal but not in vs or unity bru-
did you install using app manager
yea i deleted.....and the problem was still present and it got rid off my project files
Actually it's not, Gpt just fabricates shit, Google regurgitates shit others have written
which ones?
the project one?
what files were deleted
you shouldnt have deleted anything other than the library folder
i did?
I tried all things. And yes I did edit the bashrc
and then what happened
it got rid off my project files
i see, thx i was missing taht
it got rid off my assets and my prefabs in my project
no it didnt...
**you **did that
library doesnt do that on its own
what does your file explorer look like now?
maybe you can restore the files you deleted
i am
they should be in your recycling bin
ok i fixed it but....errors are still present
the same errors as before?
none of that answered what I asked. did you install VS through an app manager or from deb file for example.
Vs through app manager. Same goes for unity I think. Wait
Maybe I installed them as flatpak/snap?
Could that be the issue
yes that would cause issues
since that isolates the apps
i never used those app managers, always terminal app-get or deb file. Nary a problem
Hey! i'm working on a top down aerial shooting game, and i tried implementing a bomb that shoots out with a sudden burst of movement, then slows down quickly, but thats not really working. whats happening instead is the bomb just shoots out with a constant speed, any fixes?
private void Start()
{
rb = GetComponent<Rigidbody2D>();
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position;
Vector3 rotation = transform.position - mousePos;
rb.AddForce(new Vector2(direction.x, direction.y).normalized * bombSpeed);
float rot = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rot + 90);
DestroyObjectDelayed();
}
There is nothing in the code that slows it down.
yes i have yet realised that addforce isnt a literal push, how would one make it slow down? just by adding an opposite force after a timer?
Decrease speed over time
thank you sir, shall be tryin that
should i be doing that in fixedUpdate or Update?
Physics only updates in fixed update. So may as well do fixed
Im STILL trying to fix this
the code's available, debug it. Looks like something in your probuilder settings is wrong. I would just torch all those settings. It seems to use Unity's settings manager, so those might be in a json under ProjectSettings or in EditorPrefs
wait where?
where is what?
the probuilder settings
ProjectSettings dir or in EditorPrefs. Look at the code, specifically ProBuilderEditor and ProBuilderSettings
you might have bad entries in ProjectSettings/Packages/com.unity.probuilder/Settings.json, or maybe ProBuilder recovered an older settings file (see ProBuilderSettings) that's incompatible
well i found the json but dont know what to do with it
torch it all. Uninstall ProBuilder, close Unity, delete ProjectSettings/Packages/com.unity.probuilder dir, open Unity, re-install ProBuilder. Obviously make sure your project is in source control and current so you don't break anything
and reinstall right?
that is step 5 of the 5 steps I gave you yes
i deleted everything but i still get errors on console after reinstalling
same errors?
yea
do you have a file at ProjectSettings/ProBuilderSettings.json?
yea
repeat the steps from before, but this time delete that file too
i did
so you deleted two files?
yea
i deleted probuilder file
also something to note i haven't seen anything unusual besides the console error
then how did you have a file at ProjectSettings/ProBuilderSettings.json after reinstalling ProBuilder? Or did you mean you had one, and deleted it in addition to the other json?
i did delete it and it got back after reinstalling
are you using an ancient version of ProBuilder? that's the deprecated settings path. Maybe it'll be easier for you to create a brand new project and overwrite the json in ProjectSettings/Packages/com.unity.probuilder/Settings.json
pro builder 5.2.3
So I have this game build and every time I go to select an audio mixer group in my material it crashes. It's never happened before and idk what to do. Any help?
what does the error say?
also not a code question
... what am I supposed to do with this
This doesn't show the error log
!logs
id try updating versions, it seems you're on quite an old one. also theres log files printed by unity
ah didnt know we had a command for that
I can't imagine an old version being the cause of such an all-round bug
what do you mean? unity updates the editor for a reason. they fix stuff all the time
2022.3.13f is quite old, there is now 2022.3.45
2 years old is not "Quite old" in this case and I doubt that's the cause such a bug after such a basic operation
π€·ββοΈ you can doubt all you want. 2 years is an eternity in the software world.
and im not guaranteeing its the solution but its a likely one. unless they are doing some really weird editor stuff intentionally, its likely not their code thats the problem
fixed my issue by just deleting all the snapshots and mixer files I had
thx guys
Was one of them maybe corrupted?
most likely
I've seen an error with audio files before as a result of corrupted values so it might be worth checking their properties in file explorer
Hey people I am writing a modular Health and Damage system and I am wondering who should handle the Damage? Should the Player check if it has collided with the Enemy, an Arrow and explosion etc or should the enemy decide that it has Damaged the Player or took damage itself? Should the explosion decide if the Player or Enemy takes the damage?
Hope my question is clear enough
I would setup an IDamagable interface (you can name it however youd like) and the thing that should cause damage (arrow, explosion, enemy melee weapon, etc) could do a TryGetComponent<IDamageable> if it returns true, you can call something like IDamagable.TakeDamage(value) and the thing implementing it (player, enemy, breakable crate, etc) can decide what to do with that value, you could even set it up in a way where if the value is above zero it can be considered a "heal" and below zero considered "damage", the thing taking damage can also decide to scale the value based on something like armor if you wanted, for example if you multiply by a decimal you can reduce the value by a percent, so if the damage was 200, and you want 50% armor, you can 200 * 0.5 and get 100 damage instead
so if an enemy using melee hits me who should handle that?
the enemy or the player taking the damage
The damage source (melee weapon or enemy logic itself if it doesnt use physics) should check for something that can accept damage (IDamagable interface) and apply a number to that - if your player happens to implement IDamagable, they will receive damage when the melee weapon or enemy collider hits them, and the player can decide how to apply that damage to themselves
Np
I want to be gameplay engineer, should I focus on unity first or math? I have prior experience with a game engine like roblox studio for 4 years, so I think maybe math might be more important to land a job rather than engine, just want advice on what I should do.
You are more likely to get a job if you have experience in game engines than if you have experience in pure math, especially if you're planning on self studying
Might be a question better asked in #π»βunity-talk , although I can suggest that transferrable skills is going to be more applicable than engine-specific skills from my limited experience
Why Collision is a class? It does not even stays stable at Enter/Exit, changes.
Why shouldn't it be a class? https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct?redirectedfrom=MSDN
I also have no clue what you mean by it not staying stable.
You can scroll down to near the bottom for a short list of when you should consider defining something as a struct
Hm i should test that more. I meant the collision in the exit is not the same with enter's. But i believe it has something to do with GetHashCode(). It returns always the same. Wonder if they actually use single instance for every collision
If i had the access to their native code side this would be easier to find out damn
Project Settings -> Physics -> Reuse Collision Callbacks
What there iss? You are genius
I will test it oout
Yes evilreeper was right about this
Even if you needed to test that, you dont need access to their code to see. You could just store the instance and see if anything changes after having other collision events happen on other objects
Hash doesn't mean it's the same object. It depends on the hashing function. Which doesn't have to be based on the address of the object in memory.
Though, in this case it does seem to be related. Just remember that it's not always related.
question regarding colliders for tilemaps. i want to figure out each tile a bouncing ball hits (for a brick breaker game), however it seems that OnCollisionEnter2D only gets called on the first bounce each fixed update, furthermore each call only produces one contact point (in collision.contacts or collision.GetContacts()). is there a easy solution to this (otherwise i'l just not use a tilemap).
picture shows a example situation, it goes top left on start, and only the topmost brick collision gets its OnCollisionEnter2D
I have been working on this forever and feel like I've tried everything. The goal is to have the bullet script run when battling starts, the bullets script works perfectly fine but I can get it to be triggered when battel starts. Right now I have it integrated into my CombatUnitAuthoring script but I have also tried it in the Unit Authoring script. I believe the whole code is written properly I just think I'm doing something completely wrong. If you have a minute and don't mind looking I would greatly appreciate it. https://gdl.space/xatexesuho.cs
Sorry but your bullet script makes very little sense.
You move using transform.;Translate which does not respect physics
Your explosion will not happen as you destroy the gameobject it's on at the end of the frame
It works though π€·ββοΈ the explosion does happen at the end. If you think the complexity of it is what's making this so hard todo I could maybe change it
my bad, you are not parenting it, just positioning and rotating it.
Still the transform.Translate will not respect phyics
That's alright since the bullets don't require phyics for this application.
so I guess this
isInCombat = IsInCombat();
is the problem
gotta say this look horribly like AI generated code
if that is the case then you need to be debugging this
Collider[] hitColliders = Physics.OverlapSphere(transform.position, AttackRange);
foreach (var hitCollider in hitColliders)
{
if (hitCollider.CompareTag("Enemy")) // Replace "Enemy" with your tag for enemies
{
return true;
}
}
return false;
to see exactly what it is doing
It is since I tried to fix it with AI before coming here but it just rewrites the whole thing slightly diffrent
Ok thank you I'll try this!
you should know we have a policy of not providing support for AI generated code here
Didn't know that, thanks
I need a function that should overwrite variables in the class using variable from another instance of that class, but only those that have non-default values. Would this be the correct way of doing it, or there's a better way?
public void OverrideSettings(NPCSettings newSettings)
{
if (newSettings.scale != default (NPCSettings).scale)
scale = newSettings.scale;
if (newSettings.health != default (NPCSettings).health)
health = newSettings.health;
if (newSettings.immortal != default (NPCSettings).immortal)
immortal = newSettings.immortal;
//Ad nauseam...
}
Hello everyone. I never really cared about my code being too spaghetti but at the same time, I was suffering from how spaghetti it is. I think I just wanted to pretend that I didn't care. Problem is, I find it extremely difficult to apply any architecture to it. (SOLID, Design patterns) Let's say I'm starting a new project. Everytime, I'm too scared by over exhausting amount of "high-level" changes that I have to learn and apply. At some point, I'm like: I should do this, I have to do this. So I open a youtube tutorial about decorator pattern to learn so that I can make my stats & effects, perfectly added into game. This only guides me to a burn out from unity. Feeling of never going to understand how code itself works.
Any suggestions would be extremely appreciated...
Assuming you're talking about the default value of the type, then yes. If you're talking about the value that you defined initialy, then no.
If you're talking about the value that you defined initialy, then no.
You mean that if I have
public class NPCSettings
{
public float scale = 1.0f;
///....
}
then its (default)NPCSettings.scale value won't be 1.0f?
In the end, coding patterns are just that - coding patterns. You don't have to follow them to the T. It's good to get idea of them, because they make you more flexible. There is no point in learning them if you don't understand the actual code. Maybe step back a bit and make sure you understand the language enough first.
Yes. It won't be 1. default represents the default value of the type. For most nymerical types it's 0. For bools it's false, for references it's null, etc...
Shit. So how else can I go about it? Create and store somewhere a "master control" copy of the class, and compare values to that?
Pretty much yeah.
One way you can do it is to have an instance of the class defined with default values as a static field.
I think I also will have to change a couple of different parts in my code as well, since (default) doesn't work like I expected it to. =\
public class SomeConfig
{
static SomeConfig defaultConfig = new SomeConfig(){ a = 1f, b = true};
}
Shouldn't
static SomeConfig defaultConfig = new ();
suffice?
You need to initialize the default values. If you do it in the constructor, then yes. Or in the field initializers.
Then what's the point of allowing me to set up default values if they don't do anything and I need to make a constructor anyway?! Why isn't it highlighted as an error?
What default values are you talking about?
public class NPCSettings
{
public float scale = 1.0f;
///....
}
If you're talking about assigning 1 here, then it's a field initializer, and it's fine.
In this case you don't need a constructor.
You say I can't do
public class NPCSettings
{
public float scale = 1.0f;
///....
}
because it won't work, and I need instead do
public class NPCSettings
{
public float scale;
public NPCSettings()
{
scale = 1.0f;
}
}
yes?
No. As I said in the previous message, it's fine.
I don't remember saying that aside from when we were talking about default
When using (default), I mean
No, yes. Because default is the default value for that variable type. While what you do is initialize your field(with a non default value). It's not the same.
You just happen to initialize it in the field initializer.
I thought default should return... well, default state of the class. One that's hardcoded into it, such as via explicitly stating that scale must be equal to 1.0f
And it does. Except that it's the default of the variable type and not your class.
If it isn't, then... What's it is for, really? Seems entirely useless then.
It mostly is. I'm not sure I know any use casese for it either.
It is used to define the default value of any variable. For reference types this will be null, and for value types it will be the default state (0 for numbers, empty objects for structs)
But NPCSettings is a class, not a variable type.
If you don't know what it this, you probably don't need it
Yes, exactly. It's your class. But default is in relation to the variable that you use it on. Or rather, it's type.
Oh, fuck, so please tell me that it's just an error in my code and I simply forgot brackets and it should be ((default)NPCSettings).scale
Not sure what you mean

Like I said, reference types default to null
So this will be an NRE
It would still be the default value of that type. If it's a float, it would be 0.
Class is a reference types. This code is effectively null.scale
(default)SomeClass isn't even valid code.
Putting a float in your class, doesn't change the fact that it's a float.
Ah. yea, didn't notice the brackets, but also this code would give a null reference.
Okay this is the initial question
default does not mean the initially assigned value here
If you want to revert to the defaults, you check for the assigned value explicitly. default does not give you what you want here (it gives 0)
Not to mention you don't use default like this. Just use 0. default is used when a variable can be both a value type and a reference types (generic types)
If you have code like this, just make constants at the top of the class that define "default" here and check those instead
Do note that float is inaccurate so make sure you approximate it (Unity has a method for this)
So I got a script that creates a 3D prisms from 2d polygons. However, the result looks like this. What am I doing wrong? Here is the script: https://hatebin.com/mvupyvdtof
Looks like some of the normals are invertedπ€
An issue with the winding order.
I don't really like the idea of having to have three copies of every variable in code. Having to duplicate everything to get it to be read-only (since Unity doesn't show variables with "get/set" in the Inspector) was annoying enough... This should work, right?
private static NPCSettings _defaults;
public static NPCSettings Template
{
get
{
if (_defaults == null)
_defaults = new();
return _defaults;
}
}
public void OverrideSettings(NPCSettings newSettings)
{
if (newSettings.scale != NPCSettings.Template.scale)
scale = newSettings.scale;
if (newSettings.health != NPCSettings.Template.health)
health = newSettings.health;
if (newSettings.immortal != NPCSettings.Template.immortal)
immortal = newSettings.immortal;
//Ad nauseam...
}
This is very over complicated code
"variables with get/set" are properties. And you can show them in the inspector if you serialize the backing field.
Why not just have blank variables and assign them with a Reset method when the class is created?
Then you just have a single place, plus a Reset method
for the default values you only need this:
private static NPCSettings _defaults = new NPCSettings();
Assuming you initialize the fields with your default values in the field initializers.
if (newSettings.scale != _defaults.scale)
scale = newSettings.scale;
I guess I got overly paranoid after getting burned with the whole "this default is not the kind of default you think it is" =_=
What I don't understand is that some sides appear from some angles and some dissapear
Yes, that's typically what happens when the normals of the faces are inverted. They would only appear when their normals are facing the camera.
Hello, I dont know what pattern should i implement for this situation. Im thinking about mediator but idk. ( the images are 2 different visualization of the same thing ) (for the OnSelect of Button and float field, I get the current tag from the word parameter)
ty I fixed it
Seems overcomplicated, but maybe my brain just too simple to understand π Wanna explain what you're trying to do in words?
so i have a property drawer which selects a word from its words list and invokes the event OnWordChange, all the buttons and the float fields take what tag they want to change from the word param. When their values change they just tag.Set(newValue) and invoke the OnChange event so the Property Drawer knows to update.
Ah! Now I get it! I love examples, thanks π I'll think about it, see if I come up with something π
this is more of a vs thing but is there a shortcut to make cases for all of these?
right click the item in the switch(myItem) or ctrl + .
"Add missing cases"
Thanks!
This is a life saver
Not me, but one of my programmers in another project manually did 54 switch cases(who would eventually get his PR rejected)
holy hell
(But also, you could have an interface and different implementations and just call FindTarget(some params) on the instance that you get)
I cant exactly change the inherited interface at runtime
This is for a tower defense game where you can choose your targeting system for your tower
well you should be able to just switch the ITargetFinder instance π€·ββοΈ but sure, this will also generally work π
object oriented horrors beyond comprehension
okay, if you say so π
ah shit I made a terrible naming convention, theres now GameObject Tower.target and enum Tower.TowerSave.target
is there a better way of doing this
you don't need the elses
How is an equipment system usually handled animation-wise? How do you make the equipment follow the playerβs arm or body?
The most basic approach is simply to set the thing as a child of a desired bone in the rig
by "bone," do you mean creating a separate object for each body part?
sure, what i use is "handPivot" thats child of hand bone etc..
make sure you're child of the bones (thats what animates)
ty
This is how skinned meshes in Unity work already
You wouldn't be creating anything extra
They already exist if you're using a skinned mesh renderer/ animation rig
for the first time in a long while I made a basic mistake of using ontriggerenter instead of ontriggerenter2d
thats rite of passage for unity
hey ! i need help , i use UMA and i dont understand why when im in editor, i have a correct character and when i run, my character become shiny ahah ?
what is not working ?
This is a code channel, if you need help setting up animations, ask in #πβanimation
Is there any possibility that the built-in simulator does not correctly return touch positions?
sure there's a possibility. But what makes you say this
And which simulator do you mean
Well any of them
I'm trying to understand if I'm correctly converting touch positions to world positions or not
Bugs can happen everywhere, so I wouldn't be surprised if it was bugged in some certain scenario, but in general it seems to work fine.
I think the simplest way of finding out is to spawn a cube at that position or move a cube to that position. Then you can visually judge if it's in the correct place.
The x value seems kind of fine, however the y is really weird
Generally if your touch position returns (0, 0) to the bottom-left corner, and window resolution for the top-right corner, then the positions are working as intended. Then you worry about converting it to the world space.
Elaborate
I'm touching a cube at 0,0,0
x value of the touch positiΔ±on is 1.68
y value is 20.77
Is it a top-down view?
camera is placed at x,y axis
I'm using a seperate ortographic camera aside from my main perspective camera
To convert touch positions to world positions
I think it's better to apply conversion basing on the main camera.
I mean if it was an ortographic camera, why not?
Besides, does it make any difference if I use a seperate camera to handle touch position conversions?
Well, the results will surely be different. The point will surely not match the point you see on screen.
Wow
Nice drawing, ty now I understand
Then I guess I have to use raycasts?
Since I don't want to make my main camera ortographic
yes, you can easily get a ray from a screenpoint and use that for the raycast
this gives an example of how to do that: https://unity.huh.how/screentoworldpoint#using-physics
The .ScreenToWorldPoint should work fine even for the perspective, as long camera matches the settings of the main camera (or is the main camera).
you have to specify a distance with ScreenToWorldPoint or else it just returns the camera's position. and if the distance can change based on what is in the scene, that obviously wouldn't work. so the raycast would be the best option
I'm trying to use Steam Input so I can address the 2 control sticks and 2 touch pads on a Steam Deck as vec2. As far as I can tell the Unity Input System does not support this because the Steam Deck only presents itself to the game as an xbox controller.
I've setup Steamworks.NET and it has successfully init'd itself. I've created a game actions file and placed it on the Steam Deck, then I loaded my game and mapped the detected actions to the various inputs on the Deck.
I'm now at the point where I'm trying to get any sort of output from Steam Input. Right now I can't get anything out of it. Does anyone have any sort of Idea what I may be doing wrong?
Here is my Update() method in my SteamManager script.
protected virtual void Update() {
if (!m_bInitialized) {
return;
}
// Run Steam client callbacks
SteamAPI.RunCallbacks();
InputHandle_t[] handles = new InputHandle_t[16];
int connectedControllers = SteamInput.GetConnectedControllers(handles); //No controllers returned
InputHandle_t inputHandle = SteamInput.GetControllerForGamepadIndex(0);
InputActionSetHandle_t actionSetHandle = SteamInput.GetActionSetHandle("InGameControls"); //Returns 1, a valid set.
InputDigitalActionHandle_t aButtonHandle = SteamInput.GetDigitalActionHandle("a_button"); //Returns 9, the index for this action.
InputDigitalActionData_t aButtonResult = SteamInput.GetDigitalActionData(inputHandle, aButtonHandle);
Debug.Log(connectedControllers + "|" + aButtonResult.bActive + "|" + aButtonResult.bState); //Shows 0|0|0. No controllers, an no presses detected
}
In Desktop Mode on the deck, the game controllers section shows the Xbox controller. If I close steam, I see all the raw values for each discrete input device. The path for the xbox controller (before closing Steam) is /dev/input/js0. After closing Steam it switches to "Steam Deck" at the same path of /dev/input/js0.
TLDR: I want to address both sticks and both touch pads on a steam deck as Vec2s.
Okay so I have a 3D VR game, with 3D buttons, and a 3D arcade machine. How do I make a 2D minigame for the arcade in this 3D world?
make an arcade machine -> make 2d player via cube or anything else in the arcade machine -> make player controller using the buttons and make the players movement to the X and Y local axis of the screen object -> pretty much it
pls help. my solution explorer looks like this, and unity keeps reloading all the libraries. how do i fix this? tried googling but i cant find anything specific for visual studio 2022.
even if i "scope to this project", when i tab out and in, and save, it just resets.
go into the external tools settings in unity and uncheck the types of project files you don't want it to generate csproj files for
i love this forum. is this ok? anything else you would uncheck?
I unchecked it all, now it looks clean. THANK YOU.
first top two is default
Anyone knows how to do this? I have this object that is basically a conveyor belt, it already moves the objects on top of it forward, but i also want to make it gradually center on the conveyor local x axis without interfering with the forward movement. (image for hopefully some better context lol)
private void MoveControlledObjects()
{
Vector3 moveDirection = transform.forward * targetSpeed * transform.parent.localScale.x * Time.deltaTime;
foreach (Rigidbody rb in controlledObjects)
{
if (rb != null)
{
rb.MovePosition(moveDirection);
}
}
}
i have tried a few things already but nothing works :v
well if you dont want the items to respect collisions you can just use thier transform
Is there anything special you need to do to get rid of slope bounce on a rigidbody character travelling on a spherical surface?
well when working with rigidbodies and slopes you would usually add a down force if going up a slope to counteract the rigidbodies gravity being turned off
you can do the same when going down a slope as well, which is not recommended
but usually you would want to orientate the rigidbodies move direction with the slopes angle
you could use physics materials to control the bounciness, but overall a rigidbody is gonna be a bit more annoying to control in this scenario unless you're directly setting the velocity to be what you want every fixed update
I must not have been clear when I said slope bounce. I was talking about grounded characters having 0 vertical velocity when grounded, causing the character to start skipping when walking down a slope.
i ended up using lerp, its not the prettiest, its a bit junky, but will do the trick for now lol.
private void MoveControlledObjects()
{
Vector3 moveDirection = transform.forward * targetSpeed * transform.parent.localScale.x * Time.deltaTime;
foreach (Rigidbody rb in controlledObjects)
{
if (rb != null)
{
Vector3 currentWorldPosition = rb.position;
Vector3 localPosition = transform.InverseTransformPoint(currentWorldPosition);
localPosition.x = Mathf.Lerp(localPosition.x, 0, targetSpeed * Time.deltaTime * 5);
Vector3 centeredWorldPosition = transform.TransformPoint(localPosition);
Vector3 newPosition = centeredWorldPosition + moveDirection;
rb.MovePosition(newPosition);
}
}
}
the gravity is also local so i dont need to worry about objects falling sideways
either way my message stands. Directly set the velocity what you want it to be and its quite easy to control. You just need to project the movement onto the normal of the surface which is basically shown in every character controller tutorial
If I use navmesh, is there a way i can have non-cylindrical agents?
you can extract the path and just do whatever you want
you can do that with cars and write a steering behavior, for example
yeah this is what i was going for
but the path is determined based on the given width of the agent, no?
like it won't make a path that it believes it is too narrow for the given agent's width
i can use A* and do the same thing
but there's a lot of benefits of navmesh that i wanted
oh, well
it's also important that you understand that you'll need to use rigidbody addforce or velocity changes to steer the car.
manually updating the transform won't give you the desired behavior you want for that
you probably already realize that, but it's a simple thing to overlook
I know
I just want the path
then i'm going to use wheelcolliders
I know how to figure out the steer angle of a car, there's a pretty simple formula
i'm trying to change the FOV of the main camera but Camera component doesnt have a main, or fieldOfField i can change in script, or anything for that matter
is this something with unity 6's preview version or am i doing something wrong?
Do you mean this ?
Yes
So whats the problem ?
Anyone knows why this happens?
This is my game view
But in a exported version look like this
this is a coding channel, that looks like a UI issue
Is Copilot good with Unity C# scripting?
its AI. if you know what you're doing, then you're likely using it to autocomplete stuff you just dont wanna type. if you dont know what you're doing, then its only as smart as you
hey I am getting a really weird crash which I can't for the life of me find the source of. It crashes both in editor play mode and in a build, and both the player.log and editor.log have no consistent stack trace or show any error
The only error i've seen is this one but I can't reproduce that error, however the crash happens consistently.
The instruction pointer of the currently executing method is not on the recorded stack. This is likely due to a runtime bug. The 1 frames are as follow:
I have tried to debug using Visual Studio attaching its debugger and using breakpoints. I have spread Debug statements everywhere and putting a breakpoint at the last debug statement that show up in the crash doesnt work as unity crashes and VS then just exits debug mode without any errors
Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
=================================================================
Managed Stacktrace:
=================================================================
=================================================================
This is the end of the Editor.Log
Can somebody please help me at least figure out a better way to debug crashes im desperate lol
So you mean, the whole editor crashes? Did you try a more recent editor just to check, if that fixes the issue already?
i don't want to go through updating the whole project because im literally 2 weeks from release lol and it would take ages
if i cant find anything else i will try it with a copy
but im trying to find other ways rn
No git repo behind your project?
there is but git lfs for some reason replaced some files with git lfs links instead of their actual content so i mucked up that ...
thats how git lfs is working. Its linking your repo to the actual source files that exceed the max filesize. So you could just back it up, make another branch and just go one version up to see if that help. Apart from that, restart machine, delete library. try to figure out what you did before it happened. Did you add any third party plugins?
thats the thing, if i try to revert back to an earlier commit and i load the project, some .cs files are replaced with git lfs links which they shouldnt cuz i chjecked git attributes and there is no rule for .cs files
ive deleted library, restarted machine, reinstalled the same version of unity
its not unity related though because if i delete a certain function it doesnt crash but i still dont know where it crashes inside that function which is where my kefuffle is at
because it doesnt crash every time during that function, i made a trail of debug statements to let me see the last thing being executed but it doesnt really help
i also checked event viewer and it said something to do with ntdll.dll but that doesnt really help me either
i have some 3rd party libraries like LeanTween, but i dont see why they would suddenly stop working as I haven't messed with them in a while
Okay, "that function" was neever shown here, or did I miss it? You seem to have found the source of error, so why not share it π
oh yeah my bad lol wait
{
Debug.Log(gameObject.name + " STARTED DYING");
if (deathSounds.Count > 0)
{
AudioClip sound = deathSounds[UnityEngine.Random.Range(0, deathSounds.Count)];
PrefabManager.instance.PlaySound(sound, transform.position, 0.25f);
}
Debug.Log(gameObject.name + " PASSED DEATHSOUNDS CHECK");
CheckForEvents(EventChecker.onDeath, this, killer);
Debug.Log(gameObject.name + " CHECKED FOR EVENTS");
if (!(killer is PlayerEntity) && !ignoreOnKill) GameEvents.instance.OnEntityKilled(this, killer);
if (killer is PlayerEntity && !ignoreOnKill)
{
GameEvents.instance.OnEntityKilledByPlayer(this, killer as PlayerEntity);
}
Debug.Log(gameObject.name + " AFTER ENTITY KILLED BY PLAYER");
if (GetComponent<ReturnToPoolAtTime>() != null)
{
Debug.Log(gameObject.name + " STOPPED ALL COROUTINES");
gameObject.SetActive(false);
Debug.Log(gameObject.name + " SET INACTIVE");
}
else
{
if (score > 0)
{
Debug.Log(gameObject.name + " DESTROYING OBJECT RN");
}
Destroy(gameObject);
}
}
This is usually the last thing that runs before my massive chain of debug statements starts running
And did you carefully comment out one part after the other to see, what could trigger it?
yes but its not one thing that triggers it its the whole thing i think
i can double check but i think i tried that yesterday
because even when it crashes, the last debug statement i can see is the DESTROYING OBJECT RN one before the last Destroy function call
so it goes through everything inside it even when it crashes
let me double investigate the function itself ill come back to you
So maybe something is hooked to that gameObject you are destryoing at this point and it was not cleaned up correctly before destroying it?
yeah okay i just commented out teh whole of the inside of that function and it still crashed :|
i mean maybe
maybe some coroutine is linked to it in some weird way but i dont think so?
the only coroutine that affects it is when enemies flash white when they get hit but ive already tried commenting that out with no effect
=================================================================
Managed Stacktrace:
=================================================================
at <unknown> <0xffffffff>
at UnityEngine.MonoBehaviour:StartCoroutineManaged2 <0x00153>
at UnityEngine.MonoBehaviour:StartCoroutine <0x00212>
at ExplosiveBarrel:Die <0x00142>
at BaseEntity:TakeDamagePureNumbers <0x00f03>
at BaseEntity:TakeDamageWithPopup <0x0052a>
at BaseEntity:TakeDamage <0x0055a>
at BaseEnemy:TakeDamage <0x0029a>
at TakeDamageInsideCollider:Update <0x009e0>
at System.Object:runtime_invoke_void__this__ <0x00187>
=================================================================
Ok last time it crashed when i deleted that I got this at the end
so i think it is somehow to do with coroutines?
so i deleted everything inside the ExplosiveBarrel.Die function and it went back to crashing without errors
0xfff... is usually a sign of null reference access.
Did you try reproducing with the debugger attached?
yeah the debugger doesnt do anything because even with breakpoints, unity hard crashes and the VS debugger just disconnects
theres nothing in the output for it either apart from the disconnecting text
Try attaching to process instead.
is that the standalone one?
No. In your ide - debug - attach to process
ohh right
it only lets me to attach to unity
which is what I did
OHH
wait its separate
Never used rider, but there should be a way to attach to process instead of using the unity configured debugger.
im in visual studio
Oh, is it? The theme looks weird.
its the dark one :D
Then what I said debug - attach to process.
ok im attached give me a second
Donno. Looks different from the default one.
Though maybe it's just because it only shows one small part of the window.
ok as soon as I attach it it breaks and says current stack not found in a loaded module?
unity isnt crashed at this point because if I deattach VS unity resumes
Obviously you wouldn't have access to the unity C++ source code or debug symbols. But it's weird that it breaks right away.
do i try to untick that break when this exception occurs?
lemme try that
ok now its fine lemme find the crash
ok here comes the ntdll.dll shenanigans
and yeah if i deattach unity breaks
That might actually imply that there's an issue constantly and it only manifests as a crash sometimes.
what the heck XD
What process are you attaching to?
Are there other processes that have unity in their name or your project name?
Okay.
Can you take a screenshot of the whole window? I want to see what thread it is
yeah give me a sec
And while you're at it, switch to the main thread and take a screenshot of the stack trace as well
Oh,it is the main thread
Thia crash seems to be caused by the debugger being connect it seems.π₯΄
Yeah, I don't think the debugger is the root cause. It's just that it's not helping.
ok well is there any way to change previous git LFS commits on .cs files so i could try to rollback?
idk if uve worked with git lfs
Not sure about lfs, but normally you should be able to roll back previous commits.
yeah if i try to, lfs replaces some of my .cs files with the lfs link
What client are you using?
are you in need of using gitlfs? Just curious if you could remove it entirely
Ah, got it.
i found online someone saying to do git lfs install?
would that just reimport things or something?
It will just install git lfs again. I actually dont know the state of your lfs
how can i check or show you?
git lfs status
idk why its tracking the ExplosiveBarrel.cs because it doesnt have .cs files in the git attributes file
Try this to stop tracking the file: https://docs.gitlab.com/ee/topics/git/lfs/
u mean to do untrack or touch
when you untrack you have to touch it to convert it back to a normal file
icould do both with *.cs?
make a backup and try it.
I am here now and then, so just post when you got updates. someone will be there
so it hasnt done anything wrong im able to load the project without errors
now the question is, reverting back to the old commit do i do the same thing again after i checkout into a new branch based on the older commit i wanna use>
or does it touch the files in history too
Is there a way to have a particle system on a screen but whenever i click it adds a velocity to the particles to move to where i clicked on the screen or would it be easier to just do it with loads of sprites
update on my situation
I have updated to the next LTS version which is 2021.3.4f1, I don't want to upgrade further than that because its likely to break even more things and i dont think its caused by unity itself
I tried to revert to an earlier commit and then do git lfs untrack and then touch and it didn't do anything so back at square one
2021.3.4 was still a very unstable version. you should be on at least 2021.3.27. Upgrading to new patch releases of a minor version is very, very unlikely to break anything in your project which is not already broken
wouldnt 3.27 be before 3.4?
no. is 4 greater than 27 ?
ohh thats how they do it nevermind woops
wait lol i just realized i downgraded cuz originally i was on 33f1 lol im stupid
hello, my gizmo lines disappeared when i made a serialized variable static
oh my god i think i need to get my developers license removed LOL
yeah this crash makes total sense
this is causing an infinite loop... hence there are no errors or anything
yikes
thnak you so much for trying to help me @plucky inlet @cosmic rain but im sorry to say you wasted your time because i was just being stupid :D
am i not able to make static variables serializable?
dont u need the class to be static too?
no, you cannot
i might be having a brain fart but can you not assign a new value to static variables?
if (other.CompareTag("Player") )
{
CameraFollows.leftLimit = 25f;
keeps giving me the old value in debug
a little confused, I have my scene loaded with async
I click play
nothing happens...
the load scene non async didn't work either
nvm it was just because it wasn't on main thread ig
can anyone answer
Yes you can assign values to static variables. An obvious reason why its not is because that line of code is not running.
ic ok
You cannot run any unity APIs in anything BUT the main thread
Is C# Player's Guide book really good ?
PDF version is only $24 for the 5th edition
no
getting a book for 2024 is nonsense, soo many good FREE resources online
it would be a waste of money IMO
books are not always keeping up with latest anyway
I'm trying to use free and paid and all I get are really bad explanations from the content creator
sometimes no explanations at all. Just copy as I do approach
hear it from the horse's mouth https://learn.microsoft.com/en-us/
idk what that is
the creators of c# lmfao
Instead of reading, you should be doing it. It is a common mistake to read things and never actually apply them.
By example, if you want to create a Character that move, search this and make it.
agreed. Learning is easier by doing
https://learn.microsoft.com/en-us/training/browse/?products=dotnet
lots of stuff here c# specific
I'll take a look - thanks
I have a couroutine with a WaitForSeconds. Is there any way to cancel the coroutine while it's waiting? Or should I just add an check after the WaitForSeconds
actually you can do StopCoroutine(coroutine) to stop entire function, or a while loop with timer using Time.deltaTime instead..
break out of loop, there is also WaitWhile or WaitUntil.
or use async with cancellation tokens
StopCoroutine does this yes.
are you sure? I couldn't get it to work
Thats why I asked the question in the first place
Yes that's literally the only thing StopCoroutine does, and its purpose.
Beginners often use it improperly, it's likely you did not use it correctly.
you probably passed the function name instead of the Corotuine type
Proper use example:
Coroutine c = StartCoroutine(MyCoroutine());
StopCoroutine(c);
Improper use example (doesn't work):
StartCoroutine(MyCoroutine());
StopCoroutine(MyCoroutine());
@open plover
I passed the type
like the example above?
the improper use
thats not a type coroutine then
I'm just gonna call StopAllCoroutines
or learn to do it properly? what if you have multiple coroutines in same script
I learned it, but I just don't want to hold a reference to the coroutine
My code was like "StopCoroutine(SpawnObject());"
yeah, which won't work
StopAllCoroutines will work depending on your use case - but is obviously less flexible
as you cannot manage individual coroutines
compiler wont throw error but yeah its nonsense to do it that way.. its not being specific
Yea ik but this coroutine is definitely the only coroutine I'm gonna use in the app
Yea i guess so, I didn't think I would need references cuz I thought they worked differently
Like one method at a time
yeah coroutines are like fire-and-forget type methods, you can run so many of the same method (its like fake async lol)
You'd need to store it somewhere to tell computer exactly which one you want stopped etc.. ofc every object needs to be stored for later use
Ultimately you need to hold onto something, otherwise how would Unity (or anyone) know which coroutine you want to stop? Whether that something is the running coroutine itself, a signal that WaitUntil is watching, a CancellationToken for task, or whatever.
Yep obviously
How should I handle UI on my 2d sprites?
Do I create a separate world space canvas?
What if I want UI to follow a character above its head(like a health bar), do I make a world space canvas per unit in a game?
health bar can just be quads
I think I've seen people using UI for them, abit less performant but probably not a big deal for a handful of units
do I just calculate position in code?
pretty much
if I disable/enable canvas on hover to display a tooltip, would that be good?
it's just a position + offset from the unit
Then I can have 100 of canvases(1 per unit)
yeah the issue is that you can't easily see it in play until you run the game
either way works, but if you're using anchors to keep the text boxes in the screen alwaysy then UI may be ideal
or just having the structure of the UI box containers
canvas is UI right? World space or not
right a world space canvas
if it was just health id just render the quad, but if you have text then might as well use UI
Feels weird having 1 canvas per unit, but I like the idea of having it be part of an object with proper position etc
yeah, it's probably not ideal over instancing them but unless you're rendering hundreds of UIs at a time prob not a big deal
I will try and see if it causes issues
There is like 30 maybe(canvases) each having 3 small images which show tooltip on hover
Hope this is the right place to ask...
Does anyone know how to fix the jittery movement here? The sprites seem to jitter like crazy when moving. I am using rigidbody2D velocity to move and have interpolate set on the rigidbody component. I tried to show all the camera and resolution setup in the video but happy to answer any questions
Whats really strange is that the jitteriness is actually better in this video than on my monitor in play mode too
Actually let me try 1 thing, maybe its not as bad as I think
beyond making sure you're doing the logic in physic updates, and that you are interpolating everything, you have options on the camera there that say's smart update. Trying changing that around
Physics updates? I figured I could just update the velocity in update since the rigidbody is handling the movement. Here is the relevant code
void Update()
{
// Get input axes for movement
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
// Create a movement vector from input
Vector2 movement = new Vector2(x, y) * movementSpeed;
// Set the Rigidbody2D velocity to move the player in the direction of input
rb.velocity = movement;
}
I usually dont use rigidbodies for movement this way so its a bit new to me, but wanted to use physics this time if possible
in the documentation it encourages all calls to the rb component to be done in the physics update
input in update is fine though
(and more preferred)
Moving it to fixed update did slightly improve it I think? But still so much jitter
Wish it would come through in the video better. Wonder if the framerate is affecting the severity
i'd switch that camera mode then to explicitly update in fixed or late update
I would guess it has to do with snapping pixels at that tiny resolution blown up
No effect with these
worth a try ;p
Oh for sure. I appreciate it
Isnt this the traditional way to setup a pixel perfect camera tho? Followed two tutorials this morning that both did it this way
Is this normal for World space canvas image 1x1 size to be bigger than I'd expect? Am I not using correct sprite pixel per unit settings maybe?
https://i.gyazo.com/caac098292c1a2d4761f917dcbcaaef1.png
Do I need to redo all my sizes again?
Not sure. Pixel stuff I've played with rendered at native resolution and didn't try to have perfect pixels.
Getting rid of the pixel perfect camera stuff fixed the issue
So weird... guess I'l ljust do 16:9 and call it a day lol
Ty
Yea it's probably not going to be a problem when your pixels are this large on screen
This is just my curiousity, but when would pixel perfect camera be a good choice?
Ok, I'm trying to read the resolution and neither of the values I get from UnityEngine.Screen.width and UnityEngine.Screen.currentResolution.width match the game view.
This is what I get
Screen.currentResolution.height = 1440
Screen.width = 648
Screen.height = 1307```
Is this not the correct way to read the size of the screen?
Screen is the window size, resolution is the full resolution reported by the monitor.
Yeah but shouldn't screen be the Game view size I've set it to emulate (i.e 1280,x800)
What I get out has a greater height than width which isn't even the case for the game view window
In editor, you may get inconsistent results, especially when emulating a resolution. I expect that emulation means it is rendering to a back buffer of that size, but still displaying it at the actual resolution of the game window. My guess is that Screen ignores the backbuffer and is only reporting window size, but you may need to test that.
Resizing the game view does not impact the value I get back
Nor does calling SetResolution()
Is this only in Editor?
I can't really test it outside yet as I haven't implemented a way to change the resolution
Editor gets a bit funky with resolutions. The editor itself is running using Unity and the project runs in a subwindow, so it's not as straightforward as it would seem.
I'd test in build and, if you don't have resolution options yet, you can use command line args to change the resolution at boot. You can also open it as a resizable window.
But if it only works outside the editor it wouldn't be useful for what I'm trying to do which is repositioning objects based on resolutions
And having to build it out every single time to tweak a value would be.. highly annoying
ok, Camera.main.pixelRect does return what I expect
Good thing Camera.main isn't aweful these days
Ideally after how many sides would a prism look indistinguishable from a cylinder?
Depends on the shader and material used, the distance to the object, the screen resolution, lighting settings, and probably other stuff that I'm forgetting
I don't see the relation with code though
I procedurally generate the prism, thats why
Maybe not the best place to post it ur right on that
I checked the default βcylinderβ mesh and it has 20 sides
the important thing is the radius, the greater the radius the more sides you will need
Im creating a visual element, but after my implementation i want to be able to inject other codes without modifying my current code. So if i add a button to the visual element, I want another part of the code to add to the same visual element something else. I thought about making a IBuilder interface and then just loop thru all the types in the assemblies and call it. Is this the best approach or is there a better one?
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes();
foreach (var type in types)
{
var builderType = typeof(IBuilder);
if (!builderType.IsAssignableFrom(type) || type.IsInterface || type.IsAbstract)
continue;
var instance = Activator.CreateInstance(type) as IBuilder;
instance?.Build(_root);
}
}```
The visual element could register itself to some global list of elements when it is created
That way you don't need to use Reflection, just a simple foreach through the list, given that all your visual elements inherit from the same type (you'd put the registration logic in the base class constructor)
i dont think it will work, because where do u instantiate the visual elements? they still need a notification after my implementation
You tell us where you instantiate the elements - Unity does it for anything deriving MonoBehaviour, in this case use Awake instead of the constructor
There are DI frameworks compatible with Unity, so they do the heavy lifting for you
Something odd's happening, apparently my scene MainMenu doesn't have any root gameobjects? So I can't do anything to root gameobjects that don't exist... Thank you very much for your time.
Do you have Collapse turned on in your console window?
i did not, but here's a version of it with collapse on
same thing really
no no - collapse would be bad here
Can you print the scene count and the names of all the scenes?
how come only MainMenu is printing?
three total scenes, and it's these three. But MainMenu is a scene that, for some reason, has 0 gameobjects
why isn't it printing the name between each one?
name between each one?
oh i think i get what you mean
i did the search function to get the logs for each of the three scene debug.logs
it should be printing like
scene name
object count
scene name
object count```
why isn't it? Is your code saved?
at least according to the code you had here
i should've taken a bigger screenshot, that's my bad
each three corresponds to the other three for clarification
oh right i had it on ever since you mentioned
ill make better logs
collapse is off
oh i see why collapse is bad, if they repeat the order is off
exactly
Anyway do you have any code that is either destroying objects or moving them to different scenes, or perhaps DDOL singletons?
For example is this MainMenu object a DDOL singleton?
check the hierarchy at runtime
(assuming your screenshot is from edit mode)
no destroying/moving or DDOL singletons, here's a screenshot in runtime
i'm not actually sure what a DDOL singleton is but since i don't know i'm probably not using it
oh, i just looked it up, DontDestroyOnLoad?
i don't have any of that, I'm not sure what it is either
where is this code running?
i just realized it's doing at Awake, not sure if that's bad or not, but Settings and Main properly work so this should too right...
but here's where it's running
i'll try Start for one thing
In awake from what script in what scene?
Ok yeah it's probably running before the other scenes are fully loaded or initialized
oh
and the reason why it always hits MainMenu is because Unity loads scenes in some order
now it makes sense
let me try Start()
yep, it works
thank you praetor!
i'll be mindful of Awake() in the future
How can i check if mouse is over a specific ui element using the new input system?
doesnt Event System use a raycast regardless?
check the component on the raycasted elements
With 2d sprites I want the little circle that's selected to show above the bigger one that owns it. When I skew the scene view sideways the sprites show up but they're being hidden when it's the proper ortographic camera... is it the hierarchical order that's causing this? What solutions are available to me?
position = Pointer.current.position.ReadValue()
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);```
```cs
foreach (var result in results){
if (result.TryGetComponent(out MyComponent myComp))
{
// do something with myComp
}
}```
Something like that?
yeah
does the new input ui system not have something like the old event system?
yeah EventSystem.current.RaycastAll is the same(this is raycast for UI ) , only thing changes is Pointer.current.position.ReadValue() for example vs Input.mousePosition
using UnityEngine.EventSystems;
public class Test : MonoBehaviour, IPointerEnterHandler
{
public void OnPointerEnter(PointerEventData eventData)
{
if (eventData.pointerCurrentRaycast.gameObject != null)
{
Debug.Log("Mouse Over: " + eventData.pointerCurrentRaycast.gameObject.name);
}
}
}
nah more like this?
does it not work with new input system ?
did you update the Input module already ?
yeah
on event system
yeah i did
it should work afaik
is the code before the if statement running, put log before if statement
i did put a log in the void and it didint log it
you put this script on the UI item ?
yeah
With 2d sprites I want the little circle
make sure nothing is blocking it
trust me, there is only 4 elements and they are not even close to each other
well sometimes people make the rect transform huge without noticing
just checked and it doesnt look like it
can you show the rect transforms / scene setup
yeah just a second
tf
alright ima check again
im literially trying right now and its not working
WHYYY
thanks for the help,
still not working but ima try to do it myself
idk why i never seen your setup lol
right, well i just checked it with literially the same setup you have
so a single image on the ui
show the hierarchy and the canvas inspector
(dont mind the event thing, i just want an event to happend when hovering over)
show PC canvas
waht about Event System too why not
THATS WHAT IM SAYINGGGG
Expand the last component, it's collapsed
Looks fine to me. Do you have any actions in your Input Actions Asset that could somehow override all the "UI/*" paths here?
def not
did you put the interface ? (IPointerEnterHandler) in the Script right ? cause you sent Test before and this new script
i didnt even change the ui section
wdym?
ok good
Add logs in your script's Awake, OnEnable, OnDisable, OnDestroy. Make sure you have only the first two
make sure you also aren't possibly hiding regular logs from the console
i got quite a lot of logs in this project so def not
are you sure they arent just hidden in that mountain of logs then ? lol
and 2 more appeared when stopping the game
Yeah so this script is getting activated
yeah it def is
also always include the name of the component in your logs
right sorry
i just did a quick log
and typed anything to just check if its working
omfg im gonna combust internally
it was because my cursor was locked in the middle, even though i could move it when clicking escape
OPASNDP AJNSPDPAOSJND OP
thanks yall
im dumb XD
lol
I didn't even think about asking for locked cursor because I assumed how else were you hovering/clicking it and didn't see virtual cursors π₯²
The editor definitely needs to change the cursor icon when it's in the "editor unlocked" mode, so it can be differentiated from the "runtime cursor lock state" mode
hugee
even a measly dot next to the cursor or something that says Edit mode underneath, I wouldn't mind ..
Quick question: do scripts also get disabled when an object is culled by occlusion culling, and if not, can I do that manually?
No, but you can probably use OnBecameInvisible and OnBecameVisible to manually start and stop logic
found out that renderer.isVisible can tell as well
don't know if calling that every fixed frame would be a performance boost though
When your script is disabled FixedUpdate won't run
the callbacks mentioned by box are your best bet
right now im simply running
{
if (render.isVisible)
{
transform.Rotate(Rotation * Time.deltaTime);
}
}```
I'm trying to see if doing this will be a performance boost, since culling and freezing rotating platforms at the same time sounds pretty good, but in testing i have not found a clear difference.
Why are you talking about performance boosts? Do you actually have a performance issue?
Honestly not really, my game spikes sometimes to 30fps for a frame or two randomly but that almost never happens when built
I was just curious for the most part
You'll want to use the profiler to measure performance before and after the change
I see no big change, however I'd still like to keep what would be the more performant option.
Which I assume would be to stop rotations when the render.isvisible = false, is that a fair assumption to make?
I'm just not sure how expensive checking the render every fixed update would be
Without profiling data and tests, that would be a pure speculation.
Anyways, you should probably not waste time on something that might not make any noticeable difference. Especially if you don't have a problem in the first place.
true, I'll be running more tests on my own but I suspect there won't be much different regaredless, as the only thing within the FixedUpdate function is just transform.Rotate
Most likely the cost of FixedUpdate being called at all is a significant amount of overhead regardless of what's inside it. It would likely be more performant to use the callbacks mentioned above to disable the script entirely
anyone here using levelplay ad mediation and have time to help me out with some basic-level issues? i'm currently having issues with podfile generation
Does anyone have any good tutorials for getting a silhouette edge of a mesh facing towards a light source?
Wacky unity question, I love using the [Header()] function in code blocks, but is there like more things you can use to make your sections better and easer to separate. I kind of wish there were layers to headers
anyone know if this exists somehow
Naughy attributes has it
is that a plugin?
Its also in assetstore
that makes it far more convinient
anyone know possible reasons for why materialpropertyblock isnt changing values?
I am trying to change the offset value via script, but its not working
You never used the block with your Renderer.
See here for an example of how to use MaterialPropertyBlock https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html
ahh, could probably be it, let me test
Is there any way I can access a KeyPair value in a dictionary by index rather than key? Say for instance I know the KeyPair value I want in the dictionary is the 29th one, but I don't know exactly what key would unlock it.
In case someone asks why I'm even using a dictionary at all, I'm doing it because there are other parts (most of them in fact) of the code that need to look by key rather than index. It's just this one specific part that needs to look by index rather than key
No, dictionaries don't have an order
so there is no "29th one"
your options are to either create a list of the keyvaluepairs or use a foreach loop and a counter. but keep in mind that dictionaries are not ordered, so adding something to the dictionary would not necessarily add it "to the end"
Then why do they work just fine with a foreach loop?
because they implement GetEnumerator/IEnumerable
Well, I guess I could implement a counter. Guess I'm not used to thinking that way since it's a foreach loop
There is no guarantee that any particular element will be in any particular order, or that the ordering won't change when new elements are added or removed.
or that the iteration order will be stable across platforms etc
Actually that would explain some things
remember that the advice provided hinges on you already knowing the order of the kvps in the dictionary and not on the order you added them in. do not do this.
Could you explain the use case?
I have a list of randomly generated rooms and an algorithm that determines where to put exits and the rooms it attaches to (basically a roguelike). I'm specifically looking for the last room made so I can make sure it is the boss room (In debug I can tell which room is supposed to be the boss room after the dungeon is generated and shut off all potential exits the room may have except for one)
Is the room a class?
Could you just keep a reference to the most recently created room always?
It was at one point. Now it's a list of direction enums and a Vector3 representing the room's location being used as a key to find that collection of exits
Well List is a class
So you could just hold on to a reference to that most recently created List
whenever you create/add one
You can also keep the key around
for the most recently added one
and get it from the dict
I have a pinch detection for zooming, and I also have a two-finger camera movement. The problem is that both of them conflict with each other. That is, by pinching the camera moves, or I move the camera and the pinch action occurs. How can I protect from this?
Pinch:
public static float CalculateMobilePinchDifference()
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
float prevMagnitude = (touch0PrevPos - touch1PrevPos).magnitude;
float currentMagnitude = (touch0.position - touch1.position).magnitude;
float difference = currentMagnitude - prevMagnitude;
if (Mathf.Abs(difference) > 10f)
{
return difference;
}
return 0;
}
Two fingers move:
if (Input.touchCount == 2)
{
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
if (touchZero.phase == TouchPhase.Moved || touchOne.phase == TouchPhase.Moved)
{
Vector2 touchDelta = (touchZero.deltaPosition + touchOne.deltaPosition) / 2;
float moveSpeed = _parameters.speed;
Vector3 direction = new Vector3(-touchDelta.x, 0, -touchDelta.y);
input = direction * (moveSpeed * Time.deltaTime);
input = Vector3.ClampMagnitude(input, 2f);
}
}
I would compare the two touch position deltas.
If the deltas are similar, I would process it as a two-finger movement. Otherwise, process it as a pinch.
To do the comparison you would compare the deltas with Vector2.Distance(deltaOne, deltaTwo) and check if that value is within a certain threshold.
also for a pinch - the two deltas should be in opposite directions.
or in mathematical terms - their dot product should be negative,
yeah, the dot product helped, thanks
am i stupid or something? this code wont change my static variable:
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log(CameraFollows.leftLimit);
if (other.CompareTag("Player"))
{
CameraFollows.leftLimit = 25f;
CameraFollows.rightLimit += 37f;
}
Debug.Log("leave "+CameraFollows.leftLimit);
}
Firstly !code
Secondly, screenshot the console
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ok, so why do you not Debug.Log the other.tag?
oh is that why
I would have thought it was obvious. If the values are not changing then the other tag is not Player
ah yes
you got it
it's not finding the object with the tag
weird tho it works fine in another script
The code is just one part of the puzzle
The setup of the objects in the scene is also important
hm that's super weird
other.gameObject.CompareTag doesnt work
other.gameObject == GameObject.FindGameObjectWithTag("Player"); doesnt work either
all 3 work in other scripts
Why don't you just print the tag
And see what you're working with
Print the object's name while you're at it too
It's not working because the tag isn't Player. You should see what the tag actually is, and which object you're colliding with
Debug.Log(other.gameObject.tag); doesnt work
That's the same
Is it not printing at all, or is it just printing emptiness
Those are two different things
iirc an object with no tag prints 'UNKNOWN'
Untagged
o snap it says Untagged
ah it's triggering the weapon in front of the player
weird how it doesnt then trigger the player afterward
can i get a fix for this plz
cuz technically my guy can walk backwards
so im fucked
any fixes?
should i make the collider bigger
Hi guys, I'm having trouble with enemies having the ability to make a decision one more time after triggering an animation- Like here below
Frame 0
- Enemy can act, it makes a choice
- Enemy decides to attack
- Enemy can't act in the attack animation
- Animator starts transitioning to attack animation state
Frame 1
- Enemy can act, it makes a choice (again)
- Enemy decides to attack, an extra attack gets queued
- Animator finally applies the changes by the attack clip, enemy can no longer act
Frame 2
- Enemy can't act
- Attack animation is playing
Which ways are there to fix this?
I can currently only come up with:
- A bool that stops them from deciding the next frame
- An animation state machine, but it makes the variables of a clip scattered across different locations
hi, in Unity 6, how do I switch from script to a specific build profile by its name ?
I do not really get the issue here. You are describing whats happening but not, what you are expecting?
Well, the enemy makes a choice again after making a choice, but before the animation's influence sets in, leading to them queueing an attack twice or similar issues (The other issue I have is that it decides to flee from the player right after starting an attack, thus looking away during the attack)
The problem is that the animation influences everything like their movement speed, whether they can perform actions etc, but these variables are 1 frame too late in update
Ah got it. I would create a list/queue of the decisions made and wait for the action to be finished before continueing
You could generate a generic async task/method that waits for a passed in callback parameter before continueing/finishing and removing itself from the queue and starting the next action or just restarting the decision making process based on the new values
All good, take your time π Its just suggestions based on the vague knowledge of your whole setup. If its realtime, it would make sense, if its like turn based or something, thats another story too
Thanks, I think that that queue system could have a lot of potential in realtime combat (Yes it's realtime), sounds like it's essentially a state machine since the enemy goes through a line of behaviour states
Which might actually be cleaner than my current approach
Actually in one way, it could be made to act the same way as the current one, since mine is just making a single choice whenever it can
And you can easier debug the whole cycle without guessing, what state it is currently in by just knowing, its Task 1 from the List<Task> with a count of 5 or whatever number. Only thing using tasks or async in general is to be aware of knowing threading and what is possible on background threads and what is not, depends on how you gonna implement it. You can also just have async voids and dont use tasks at all too. But thats up to you
transform.position = Vector3.Lerp(startPos, new Vector3(Mathf.Clamp(endPos.x, leftLimit, rightLimit),
Mathf.Clamp(endPos.y, bottomLimit, topLimit), -10), percentComplete);
this isnt working
for clamping my camera
You've got a lot going on there.
What isn't working?
Do the operations separately and log each component of the equation.
For example:cs var x = Mathf.Clamp(endPos.x, leftLimit, rightLimit); var y = Mathf.Clamp(endPos.y, bottomLimit, topLimit); var endPos = new Vector3(x, y, -10f); Debug.Log($"x: {x}, y: {x}, start: {startPos}, end: {endPos}, before: {transform.position}"); transform.position = Vector3.Lerp(startPos, endPos, percentComplete); Debug.Log($"after: {transform.position}, progress: {percentComplete}");
whats the $ do
hm thats really weird
seems the camera uses different coordinate values than the objects
does anyone know anything about that
You could probably convert each point from screen to world position or something
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
(Z will be that of the camera's)
thx
Any idea what could be producing this crash and how to fix it? It looks like a problem in a memory allocator, but I don't understand much.
https://pastebin.com/wLs5yhrW
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Did you run out of memory perhaps?
There aren't many other reasons for an allocation to fail
I don't think so, I have 32 GB of RAM. Thought next time I get it will try to have openend the task manager
Might want to check your app memory from time to time. You might have a memory leak
I keep getting Firebase.FirebaseException: Missing debug token
#if UNITY_EDITOR
private const string debugToken = "MEOW";
#endif
public void Awake()
{
#if UNITY_EDITOR
DebugAppCheckProviderFactory.Instance.SetDebugToken(debugToken);
#endif
}```
```cs
public static void IntegrityCheck()
{
#if UNITY_EDITOR
FirebaseAppCheck.SetAppCheckProviderFactory(DebugAppCheckProviderFactory.Instance);
#elif UNITY_ANDROID
FirebaseAppCheck.SetAppCheckProviderFactory(PlayIntegrityProviderFactory.Instance);
#elif UNITY_IOS
FirebaseAppCheck.SetAppCheckProviderFactory(AppAttestProviderFactory.Instance);
#endif
FirebaseAppCheck.DefaultInstance.GetAppCheckTokenAsync(false).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Failed to get App Check token: " + task.Exception);
}
});
FirebaseAppCheck.DefaultInstance.SetTokenAutoRefreshEnabled(true);
}
According to docs this is all there should be to it
Where and when is IntegrityCheck() running? Are you sure it's not happening before that Awake? Have you tried putting logs into both functions to see which runs first?
do we have access to the API unity uses in the mesh importer to merge vertices/rebuild mesh in function of a target angle for normals smoothing?
More specifically, the normals checkbox in the importer where you can choose to either import from the mesh or generate within unity
public void Awake()
{
#if UNITY_EDITOR
DebugAppCheckProviderFactory.Instance.SetDebugToken(debugToken);
#endif
}
public void Start()
{
RedTTGLogin.Initialize();
//...
}```
```cs
public static void Initialize()
{
IntegrityCheck();
InitializeFirebase();
configuration = new GoogleSignInConfiguration
{
WebClientId = GoogleWebClientId,
RequestIdToken = true,
};
PlayGamesPlatform.Activate();
_initialized = true;
}```
I had it inside of the IntegrityCheck function before to set the debug token and that didn't work so I thought I'd move it out a bit but that didn't change the error
the error itself is at the Debug.LogError here
if I skip that set of code auth fails saying permission denied, so that doesn't work idk what to do
Are you running the code in the editor, or somewhere else?
Also wait - surely this isn't correct?
private const string debugToken = "MEOW";```
yes in the editor I want to be able to login using email and test my firestore connectivity while insuring the app has app check
dw it is set and I double checked it in firebase
I have it with the lines as firebase console gave it to me
Meaning your code doesn't actually say "MEOW"?
no haha
yea, very odd, like I even asked copilot maybe I missed something but it just gave a stupid response as it typically does
Maybe best to move to more google focused support channels
hmm, are there any? I mean I could message google directly
anyone know a nice way of getting the material from either a Image renderer or Sprite Renderer and ignoring what type they are? i just want to get / set the material
Renderer r = GetComponent<Renderer>();
Material m = r.material;```
Although actually Image is not a renderer afaik
nope image is not a renderer and therefore my question T_T
You could do something like:
void ExamineMaterial(Component c) {
if (c is Renderer r) {
mat = r.material;
}
else if (c is Image im) {
mat = im.material;
}
else {
// explode
}
}```
that is something i can try. thank you
well restarting unity fixed it, however there are still ```SignInAnonymouslyAsync encountered an error: System.AggregateException: One or more errors occurred. (An internal error has occurred.) ---> Firebase.FirebaseException: An internal error has occurred.
at Firebase.Auth.FirebaseAuth.SignInAnonymouslyAsync () [0x0002c] in /home/runner/work/firebase-unity-sdk/firebase-unity-sdk/linux_unity/auth/swig/Firebase.Auth_fixed.cs:3544
--- End of inner exception stack trace ---
---> (Inner Exception #0) Firebase.FirebaseException: An internal error has occurred.
at Firebase.Auth.FirebaseAuth.SignInAnonymouslyAsync () [0x0002c] in /home/runner/work/firebase-unity-sdk/firebase-unity-sdk/linux_unity/auth/swig/Firebase.Auth_fixed.cs:3544 <---
you can also write it something like this if you prefer
var mat = c switch {
Renderer r => r.material,
Image im => im.material,
};
The values I get from transform.localEulerAngles does not seem to match the values that appear in the inspector.
Inspector rotation seems to go from -180 to 180.
While the values from transform.localEulerAngles seem to go from 0 to 360 or 0 to -360.
correct, you should never read from eulerAng;es only write to them
I would like to display the rotation of an object in that -180 to 180 range.
Any tips?
keep your own rotation in euler angles