#archived-code-general
1 messages · Page 412 of 1
spent my time in paint to let you visualize what you did wrong, and it aligns with the behaviour in video you provided
in video you provided the lever is initialy over the upper angle limit so you can drag it with low force to open position
you can do it because its not hold by the limits
but when it goes back to start position ( the red line) then its back in bounds of angle limits
so you cant move it over the angle limit without big force
so it should be like that?
when ı first tried it was like this but I could move it
I am sending you a new video
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
now it have good angle limits, but you breaking those limits anyway with high force
but it just looks like just the point where joint takes as starting point is not correct.Because if I broke the joint I could be able to move it freely dont I?
why you would want it to break the limits? it should stay in the limits, and the joint start point looks now correct according to the open state angle of trapdoors
next time you should provide scene view which show behaviour of the lever and angle limits, with inspector open at the lever, so it would be much less of guess game
try asking in the game's modding community. modding discussions are not permitted here
alr
Hello, I’m an XR game dev who mainly just focuses on making vr games, but I wanted to try a PC project again, I haven’t made a PC project in two years, and I really wanted to try it again. I made this prototype in hdrp, although there are some things i need to fix and need help with.
-
When I move my mouse, you can see the UI has some motion blur, I don’t know why that is
-
Animations are snappy, they aren’t smooth as desired, i’m using all mixamo animations. I don’t make PC projects so I kinda have no clue how to fix these issues
Neither of these seem like code issues.
#💥┃post-processing
#🏃┃animation
Thank you
Undo.RecordObjects(objects, "Destroy missing scripts");
foreach (GameObject target_object in objects)
{
Component[] componentsAttached = target_object.GetComponents<Component>();
foreach (Component component in componentsAttached)
{
if(component == null || component.GetType() == null) {
DestroyImmediate(component);
compsRemoved ++ ;
}
}
}
I am trying to destroy missing script references on objects in a scene, but it does not do anything, finds the missing scripts correctly, but they are not destroyed.
Yeah it does increment that counter
It is confidently logging out "Destroyed 221 Missing Scripts 😎 "
Are you targeting prefabs or scene objects or both?
Scene objects only..
What if you mark them dirty with EditorUtility.SetDirty afterwards
I am now trying to deserialise the object and then remove componets mnaully
It helps with saving changes, but I am unable to make any changes for them to be saved
Yeah I think it's because you are passing null into DestroyImmediate so it doesn't know what to destroy
Well then remove the null flag in if-statement and directly pass the componet if Type is null ?? this is confusing, because unity leaves the component on objects if the component used to carry a script, so component itself is not actually null....
@potent sphinx Wait.. since when was this a thing
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/GameObjectUtility.RemoveMonoBehavioursWithMissingScript.html
Jeez
Apparently it's been around forever, never heard about it lol
Just saw it mentioned in a discussions thread
And it worked
😭
Thank you so much
I had been looking at unity forum posts from 2010
limits were correct I think.Its about my grab script.Because I cant get the lever to right side this way
maybe, its more like of a guess game with provided informations
can you take a look at my grab script. I cant see a problem but maybe you can see. Because problem occurs when I grab.
i can check it later but record how you interact with the lever with scene view focused on the lever, and inspector have to show the HingeJoint2D component during interactions
is there a way to copy a component to another object?
At runtime?
Reflection I guess
yeah
What for
Again, JsonUtility can do that
i mean, i suppose you could serialize and deserialize it
You'd just need to AddComponent first
yeah i just thought of that xD, but i was wondering if there was a more direct way
Direct way (reflection), performant way (json)
Serializing then deserializing is pretty much direct way
how would you do it with reflection anyways?
you get the fields for that component (class) and then get values from your source and set the fields in your target
Don’t do that tho
You don’t know what fields Unity use internally
And what is going to happen when you blindly copy them
well i am going to use it for my own scripts for the most part
Serializing is more robust way since you can control what is serialized
also, i dont think they json utility thing works on built in components
Yeah but if you just copy all of the data then it might break things
JsonUtility is same serialization as you save to prefab or scene
Both have their pros and cons. If you use some unserializable properties for example or what not. And same goes for copying field values with reflection. As long as you know, what you do, you will work your way around one or the other, and I suggest the json way too.
There we go already 😄
The doc only mentions MonoBehaviour/ScriptableObject support yeah
Nothing about builtin components (This doc i mean https://docs.unity3d.com/2020.1/Documentation/Manual/JSONSerialization.html)
Newtonsoft might be more useful in any case too
newtonsoft doesnt work either
can you show, what you are trying to serialise?
i tried, it cant serialize either because the monobehavior has the gameObject property
which causes an endless loop
Don’t use newtonsoft for this
so you not gonna show your class you want to serialise? 😄
i already said engine components, could be anything
for example linerender i guess?
In any case, it’s just better to find a way that works with either Instantiate or manual logic
okay it was about grab script.It sets limits for the joint I create on my hand to grab things.I set use limits to false and everything works now.
most of my custom scripts work fine tho
For your question mark Newtonsoft is not suitable for unity object serialization
you may want to use something like this in addition to newtonsoft to fix the "unity" problems. However you still can't use it to instantiate monobehaviours https://openupm.com/packages/jillejr.newtonsoft.json-for-unity.converters/
"object", thats like everything. Do you have an example?
UnityEngine.Object
“Unity object”. UnityEngine.Object
yes ive already done this, doesnt help
create that component in runtime (in script) then assign the values from other script by referencing.
you can use newtonsofts .Populate() API to write a serialized state to an existing instance
I guess, you have to write your own custom classes for the builtin ones then, that just hold the values for the builtin ones so you can serialise and deserialise them
its a good idea to use a memento pattern when serializing monobehaviours
as i said newtonsoft cant serialize components because of circular dependencies, even with converters
sure it can, you just have to do it right
It’s probably the references your class is holding
also you should not serialize references anyway, that causes more problems than it solves
its a fundamental feature of any save-system that you come up with a maintainable way for referencing stuff in savegames
I was having the same discussion yesterday hehe
no because the object can mutate at runtime
What do you mean
after instantiated from prefab
wym o;o
Or use it as prefab, ig
Instantiate is essentially copying the game object you pass in
oh yeah right, i think we have mixed a couple different problems here
anyway, ill figuere out
thanks all
That's an issue with Unity, not Newtonsoft. Considering there are packages available to fix a lot of these issues I assume one also exists for this
It’s issue of neither. It’s simply not the right tool for the job.
JsonUtility shouldn’t be looked as json serializer competing with Newtonsoft, it should be looked as Unity serializer
The way I do component serialization is just making a load manager and create lookup tables to bind IDs to components
and JsonUtility works just fine
then create a whole GO from it
It works when you don’t really care about result being Json
Whatever specifically Json is required Newtonsoft should be used, JsonUtility is just utility happened to choose format as Json
Are you saying that JsonUtility is able to deserialize into MonoBehaviour classes whereas Newtonsoft can't do it?
I’m saying that JsonUtility is there as a serialization utility that follows Unity rule, such as SerializeField. And not as universal Json serializer.
It’s not important that format is Json, it would do the same if format is XML
And it’s sane to use it for serializing what Unity saves
That's not what I asked, and even then this is configurable. Even easier if you use [JsonIgnore]
I don't see what benefit JsonUtility has over Newtonsoft in any way. Pretty sure even Newtonsoft can have support for fields
It's very limited compared to when you can serialize at editor time, not everything usually you can [SerializeField] work with JsonUtility I noticed
Not that I think you should switch, I just don't see why we would praise a clearly outdated and worse serializer
Especially when most (all?) of the quirks against Newtonsoft come from the bad conventions that Unity has made
The only reason why JsonUtility even works here is because it also uses the outdated BinarySerializer that Unity itself uses
Which, by the way, is very likely to be gone when they switch to CoreCLR since it's been removed from .NET due to it being really, really bad
(Source)
NewtonSoft does actually do magic compared to Unity's but that usually comes at a cost a larger amount of data serialization. Ultimately getting everything down to IDs would be the way if you're constructing whole GOs
Newtonsoft doesn’t know Unity serialization rule by itself, and you’d have to provide custom serialization config to handle Unity object which just duplicated logic
Use Newtonsoft for when you actually need Json. It’s not praising JsonUtility at all lol
what does that even mean
I'd love to see an example where JsonUtility is actually a better choice compared to Newtonsoft
personally, because its not compatible with unity
which is a unity problem, i agree
? What field would use binary formatter
It's compatible with Unity, there's even a specific package available for it
I’ve been saying they are not competing, and you were clearly not reading
Unity and JsonUtility use the BinaryFormatter. That's why you always have to plaster everything with [Serializable]
for example you cant serialize monobehaviors directly
even with the package
You're not supposed to do that anyway
Serializable is just flag attribute and if you see the content that is not binary formatted
What if you want to copy a component's data onto another
why not, its just code
And even if you want to do that, you should use the actual Unity API and instantiate it. There's a PopulateObject method for setting data
How do you instantiate a single component
Without cloning the whole gameobject
It's clear that you guys rely way too much on this if you think it should be able to do all this
i am saying you cant even serialize the component to begin with, how are you populating it
It's a serializer, not a full on object creator
how can I make this object to look up like this at start?
So why not use JsonUtility where it does the job better and simpler?
You are just getting super defensive about newtonsoft for no reason.
JsonUtility doesnt serialize components, no?
not engine components, but it can your monobehaviors
But not with builtin components AFAIK
For my last project, I just build equivalents to builtin components, like a serializablevector3 for example and what not
but what happens if you try to serialize an object reference?
vector3 is not a component...
alsoit should be serializble by default
giving json to you guys was a mistake 😆
You also seem to conveniently forget that JsonUtility is unable to deserialize a lot of common types, which is the main reason why you would not use it
It becomes as Unity serializes it
Probably object ID
UnityEngine.Object or just object in general?
Ideally you shouldnt be trying to serialize stuff at a reference level. Grab data then point to some identifier so next time you recreate it you can do it at runtime
but who is json? 🤔
I'd imagine the behaviour is the same as copy/pasting a component in the editor
was more of an example of how you can adapt your objects to something useful and reassign them. But you right, vector3 per say was not related to the component specifically
Yes
That’s the whole point
You don’t care about content as long as it contains data that Unity serializes, and it’s weird to go through the hoop just to use Newtonsoft with it
I'm not denying that, but it's also not the point of this discussion. You can always use a serializable dictionary (for example) to get around that
Which is not going through hoops with an alternative to get things working?
Not a massive hoop IMO
Let's not forget nullable types here. JsonUtility can't use those either
Seems like quite a hoop to me
I like how things align with unity's own serialization
Because that's literally what it is
You don’t need that if you want to follow Unity serialization
Feels like this discussion ran out of sight from the actual question, didn't it? 😄
Json is always a hot topic :p
what features do you think should be considered when registering a swipe gesture?
The real issue here is Unity like always
yeh not taking myself out of here being a driving force, too. It just started to be like a subjective opinion fight rather then sticking to the topic now 😄
not sure, what you mean with that question
i'd just go learn some networking and learn how to do serialization proper, so when you f up you pay the cost in bandwidth
It is certainly subjective and usecase dependent
Saying that X is always better than Y is naive
Whatever is not supported in Editor, like Dictionary, is not necessary for JsonUtility
udp and messagepack ftw 😉
Because it’s not JsonUtility to support whatever Unity doesn’t support
Wdym with features? Like methods to use to detect swipes?
Have you read this?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Touch.html
again, what does that even mean
Unity does support dictionary
you guys wanna throw that discussion in a thread probably?
I don't understand this take. Are you saying you never use dictionaries or nullable types because JsonUtility doesn't support it?
Unity doesn’t support Dictionary serialization
well yeah but thats begging the question isnt it?
whats a thread? /s
If you want to serialize data properly use something like protobuf or bebop (not sure if its supported in unity but still)
if everything isn't a struct with value types you're doing it wrong and that's what I've concluded after fighting with Unity for years
i mean, i am not sure about that...but what is making me confused is, should swipe be considered when a finger(touch) is lifted from screen aafter a fast movement? or it can stay stil on the screen after a fast movement?
true
Gosh, if you need Json, use Newtonsoft. If you want what Unity serializes, use JsonUtility. Is it hard to understand?
yes because it doesnt make sense
This has nothing to do with that
What doesn’t
i've done swipe detection before and its usually detecting some velocity between inputs within some time. id say its up to you if you want it to require a pointer exit/up.
That is totally up to your gameplay tbh. So as always, depends on what you wanna achieve
my guy wants the easy way out to json serialize a whole scene
Why not just serialize the whole game while we're at it
Who needs a binary executable
I've a load manager specifically for each type of object I serialize
I want a "let it go" frozen emote so bad right now 😄
Sorry, I'm just having fun at this point
At least it's somewhat unity related
how does your load manager work btw because now i am curious
sry to bother lol
like do you serialize the prefabs id and then go the manager to get the og prefab?
If we're talking the bare minimum amount of data needed to serialize an object it's simply an ID which you can create a lookup table for, so when you load up your game, pass that serialized identifier into it and point to the required loading process
Along with what ever other value types you bundled with that ID
Now, to make things even more simpler, if the object you're constructing was previous part of a prefab, you've now some blueprint to build upon
For a game I work on with 1000+ objects each has a configuration entry with a unique string id. Each has an address for its prefab which is used to load it back another time.
so i want to load in eggs, i pass an egg identifier, which goes to the eggloader?
lol, yeah. You can also use interfaces like an ILoadable to implement on each type of object that can be serialized
IWritable, ect
Okay, I'm getting closer to finishing my game's control-scheme with the help of my bro...
But I've got quite a few steps left to go...
I wonder what I should tackle first...
step 1: save all of the process's memory to a file
I tried development build but the error is still there.
This is from the debug stack
I don't get these errors when I use Quest Link and hit play on Unity. I only get this when I am exporting APK to Quest.
What does your ServerLoadManager do on Start?
can you show that method. I guess, your quest cant connect to something your editor can but you still try to access it. Logging might help
alot of this effiecient loading and saving is similar to networking data transfers.
If you care about size and efficiency when doing these tasks, you can approach it from a similar perspective
Thanks! I am loggging errors. Here's ServerLoadManager script.
public class ServerLoadManager : MonoBehaviour
{
public float currentLoad { get; private set; } // Current server load percentage
public float NormalLoadThreshold = 50f; // Below this is considered Normal load
public float HighLoadThreshold = 80f; // Above this is High load
public float OverloadThreshold = 95f; // Above this is Overload
public bool isServerOnFire = false;
public string serverStateString { get; private set; }
public ServerLoadState currentState;
private ServerLoadVisualizer serverLoadVisualizer;
public Color serverResponseDataPacketColor { get; private set; }
// States
public NormalLoadState normalLoadState = new NormalLoadState();
public HighLoadState highLoadState = new HighLoadState();
public OverloadState overloadState = new OverloadState();
public ServerDownState serverDownState = new ServerDownState();
public UnityEvent onServerStateChanged;
public float ipDistributionSliderValue, trafficVolumeSliderValue, requestFrequencySliderValue;
public float ipDistributionWeight, trafficVolumeWeight, requestFrequencyWeight, overallConstant, maxPossibleLoad;
public DataPacket dataPacket;
private ServerLoadState lastState; // Store the last state
public ServerSO serverData;
private float variationRate = 2f;
private float fluctuationInterval = 1f;
private float targetLoad;
private float fluctuationValue;
public static ServerLoadManager Instance;
private bool serverShutdown = false;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
void Start()
{
serverResponseDataPacketColor = Color.green;
if (onServerStateChanged == null) onServerStateChanged = new UnityEvent();
ipDistributionSliderValue = IPDistributionPanel.Instance.ipDistributionSlider.value;
trafficVolumeSliderValue = TrafficVolumePanel.Instance.trafficVolumeSlider.value;
requestFrequencySliderValue = RequestFrequencyPanel.Instance.requestFrequencySlider.value;
IPDistributionPanel.Instance.ipDistributionSlider.onValueChanged.AddListener(OnIPDistributionSliderValueChanged);
TrafficVolumePanel.Instance.trafficVolumeSlider.onValueChanged.AddListener(OnTrafficVolumeSliderValueChanged);
RequestFrequencyPanel.Instance.requestFrequencySlider.onValueChanged.AddListener(OnRequestFrequencySliderValueChanged);
serverLoadVisualizer = GetComponentInChildren<ServerLoadVisualizer>();
if (serverLoadVisualizer == null) Debug.LogError("ServerLoadVisualizer not found");
dataPacket = FindObjectOfType<DataPacket>();
Debug.Log($"Datapacket before calculate server load: {dataPacket.currentState.DataPacketStateName}");
CalculateServerLoad();
if (currentLoad <= NormalLoadThreshold)
{
SetState(normalLoadState);
}
else if (currentLoad > NormalLoadThreshold && currentLoad <= HighLoadThreshold)
{
SetState(highLoadState);
}
else if (currentLoad > OverloadThreshold)
{
SetState(overloadState);
}
InvokeRepeating(nameof(CalculateServerLoad), 0.3f, 1f);
StartCoroutine(DelayedFluctuationStart());
}
Basically, serverload manager is a state machine.
Again, this all is working fine via quest-link. But not when I export it to APK (i.e., build and run option).
Like two debug.log on your entire start() is not logging tbh. you never check your dataPacket for example. just access its values
Id say, get some logging in to check if everything as expected, then maybe comeback here if you didnt find out yet. and next time pls !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
hello
Thanks. I'll do that. I want to know why this works fine in Unity but not when I build an APK.
random side-note, consider using a "singleton monobehaviour" base, makes things super easy like https://gist.github.com/ErikOG/dbc8d831bb22531cb870c57e098a1172, I use this pattern every time I'm prototyping, over time it's a pretty solid time save ^^ (the lazy loading is nice too, don't have to interject into awake or start)
Okay I did this and the error is when I'm trying to find ServerLoadVisualizer in children.
So this works in the Unity but for some reason when I'm building in the apk it's failing.
Debug.Log("Server Load Manager Start6");
TrafficVolumePanel.Instance.trafficVolumeSlider.onValueChanged.AddListener(OnTrafficVolumeSliderValueChanged);
Debug.Log("Server Load Manager Start7");
RequestFrequencyPanel.Instance.requestFrequencySlider.onValueChanged.AddListener(OnRequestFrequencySliderValueChanged);
Debug.Log("Server Load Manager Start8");
serverLoadVisualizer = GetComponentInChildren<ServerLoadVisualizer>();
Debug.Log("Server Load Manager Start9");
if (serverLoadVisualizer == null) Debug.LogError("ServerLoadVisualizer not found");
dataPacket = FindObjectOfType<DataPacket>();
Debug.Log($"Datapacket before calculate server load: {dataPacket.currentState.DataPacketStateName}");
A few things to check. Is get component allowed to get from inactive objects? Is this an addressable scene?
Scratch that. The error is down below. It's sort of the same one. I don't know why this is an error. What am I missing. This works fine in Unity. Not when I am building apk. I just can't wrap my head around this. If this was a problem, wouldn't this also show up in Unity?
if (serverLoadVisualizer == null) Debug.Log("ServerLoadVisualizer not found");
Debug.Log("Server Load Manager Start10");
dataPacket = FindObjectOfType<DataPacket>(); //Error Here
if(dataPacket == null) Debug.Log("DataPacket not found");
if(dataPacket != null) Debug.Log($"DataPacket found");
Debug.Log($"Datapacket before calculate server load: {dataPacket.currentState.DataPacketStateName}");
CalculateServerLoad();
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Thank you kind sir
Okay. I fixed the issue. I wasn't able to access properties of dataPacket. They were initialized in the Start and I moved them to Awake. This worked. I'm still not sure why it worked on Desktop but not after building APK. Should I raise a bug request on Unity? I just want some explanation of what's happening so that I don't run into issues like this.
any advice how to figure out how someone's game crashes? There's a specific player who's game is crashing. Looked through the code and I load things with addressables. But it's very light stuff (a main menu). How can I help this player? He aint tech savvy, any advices?
The best way would be to look at the logs. If it's an android game, use Android LogCat. If it's a PC game...there will be an application that generates logs.
Always be in control of what oyu loading and what to expect from other classes. Dont just trust in asyncs running inthe same order as in editor or other stuff in parallel 🙂
pc game hmmm
The order of execution for things like Start and Update (amongst types with the same script execution order value) is completely arbitrary. You get whatever order Unity decided to store the objects in.
If your game depends on a specific order, you must enforce it
You can use unity cloud or firebase or sentry or bugsnag to have crash reports be uploaded, could be worth doing if you have many users.
I wonder if you could scramble the order of objects to help detect that kind of issue
thank you! Just tried installing cloud diagnostics, seeing how that works
Should work decently. You should check the docs for the platform for how you upload symbols (needed for crash stack decoding)
symbols?
the names of functions and whatnot
the built game does not inlcude this information
well, more notably, the symbols give you line numbers
I've been having problems getting symbols to upload, so I just see weird gibberish in my stack traces. I do still get function names.
I don't think you can get line numbers for il2cpp ever cus I've not seen it work.
But symbols are needed for crashes as otherwise the stack is unreadable.
ah okay ill have to figure out how to get em
Symbols are output with a build so just upload em, the docs should explain where
If using mono it may not I forget
Can someone tell me where in game dev would I need to use dsa intensively?
You mean like competitive programming stuff?
I need to make a project related to data structure and algorithm and I was wondering if I could make a game that uses dsa alot like the sokoban(box moving game)
Basically asking for recomendation of games that uses concept of linkedlist, list, queue, stack, tree, graph, hashing alot
You can shoehorn these into any project, except linked list, that’s a mostly useless datastructure in games, but you can obviously use it if you want to make bad choices.
But what type of game would it be most suitable in, tower defense? 🤔
Alright I'll just pick one and look into it then
do anything with physics or pathfinding —> tree & graph, you can’t make a game without lists. Any lookup is a hash map or hash set.
Okayy thankyou
Any list is also a stack, queue is useful for message/command/action ordering
Got it, thankyou for your help
How does one enforce it?
you can have one object call a "setup" method on a second object, rather than using Awake or Start on both of them
Something like this?
public class GameManager : MonoBehaviour
{
public string GameSettings { get; private set; }
private void Awake()
{
GameSettings = "Hard Mode";
// Find and set up PlayerController
PlayerController player = FindObjectOfType<PlayerController>();
player.Setup(this);
}
}
public class PlayerController : MonoBehaviour
{
private GameManager gameManager;
public void Setup(GameManager manager)
{
gameManager = manager;
Debug.Log("Game settings: " + gameManager.GameSettings);
}
private void Start()
{
// Setup ensures this data is ready by the time Start is called.
}
}
If I create an animation for an object how can I do so the anim just changes his position and rotation based on the own object
and not the global coordinates?
Because when the game starts all the objects with that anim go to the same spot
best practice is to have the animator on a parent object
and the thing being animated on a child object
Animator always animates local positions, but if your object has no parent, a local position is world position
okay, and then if i want to use the same animation for 3 different objects but when the game starts I want them to be at different positions so they are not moving at the same pace (To make it kinda dynamic) what can I do
do what I said
And it will work
i remember being able to do this before and now I've forgotten how to do it even though it seems so simple in theory.
basically, I've been trying to get a system that cycles through a List<T>, the intended behaviour is if you try to cycle beyond the list you just get sent back to the start again and vice versa if you cycle beyond the start.
I seriously have no idea why this is isnt working because it's not even throwing any errors or anything but nothing is happening, so it could be a case of it breaking instantly but yeah I have no idea (if this made no sense i can try to explain better but i dont want to write a 1500 word essay in a single message, also yes I am using new input system with invoke unity events)
Below is a link to the cycling function and attached is an image of the list in the inspector
A tool for sharing your source code with the world!
The code doesn't really make sense to me
why is there a for loop here at all?
i think the way i planned for it to work is
- loop through the list until the current projectile name matches the index's projectile name
- get the new projectile from the list based on the input of the 1D Axis action (aka, if -1 then get the previous element in the list, otherwise get the next)
but in reality it didn't really work at all, i had an older version that was able to go up one time and got stuck afterwards but it couldnt go back without an OutOfRangeException but i dont think I had any failsafes for that in place
there's no need to loop through anything as far as I can tell
Just something like this:
https://paste.mod.gg/bdjdfaydggrp/0
A tool for sharing your source code with the world!
(also I'm asssuming your list is a List<Projectile>)
but I have no idea what it is so that part is just a guess
yeah its a custom class
the definition is public List<PlayerProjectile> projectiles = new List<PlayerProjectile>();
{
animator.SetBool("Dashing", false);
dashing = false;
transform.Find("FireEffect").gameObject.GetComponent<SpriteRenderer>().enabled = false;
}
for some reason the enabled on my FireEffect component is not being changed
Why not use a dictionary
becasue you're not setting the enabled on your FireEffect component
you're setting it on the SpriteRenderer component
Well you're using GameObject.Find so that's a red flag immediately
oh?
yes and no
How did you verify 1
I am calling another function right above it in the same block and thats running fine
That's not good enough
there's an if statement here, and who knows what other code may be doing.
use Debug.Log
make sure it's getting printed
if you mean c# dictionaries then i cant do that because every KVP in a dictionary is the same type, in my case i need multiple different types
if it didnt run, wouldnt the dashing bool of animator not be false?
Use Debug.Log
you are making assumptions
I did its running
and that's what leads to bugs
Why not use the string for the name? I’m not sure I understand ur problem
If the code is running and there's no errors - then it's working fine
SOmethiung else is probably disabling the renderer
or you're enabling the renderer of the wrong object
i dont have multiple projectile objects im changing the sprite of the clones i make from the original instance, so just getting the name of the sprite directly seemed to cut out the clutter
There's only one FireEffect in the whole scene?
yes, and this is the only code the accesses it
Also you could write
index = ((index + step) % listcount + listcount) % listcount
How do you know there's only one
because I manually create it
and there is only one
People make mistakes
Search the scene at runtime
I understand completely
yep, only one fire effect
what did you mean by "Find" is a red flag though, is it some unity anti-pattern
Then if you used Debug.Log, the code is working. What makes you think the renderer is not enabled?
DId you look at theinspector and see it still disabled?
absolutely yes
how so
Is there a specific reason that you're using transform.find as opposed to just a serialized reference to it?
thought it would be easier but its evidently not
Find is:
- Slow. It searches the entire scene for the name
- Fragile - renaming an object in the scene breaks it without any notice
- inconsistent - having multiple objects in the scene with the same name is possible and there's no way to differentiate
- It also can't find deactivated objects
Wait also you're uising transform.Find is that intentional?
Is this part of the same object hierarchy this script is on?
Sorry thought it was GameObject.Find
That's a different story
yes
Can you show some screenshots of the hierarchy and which components are on which objects?
can you show the inspectors for the Player and FireEffect objects?
had to tweak it a bit but this works, now there's the problem of the function firing 4 times in a single press which i have absolutely no idea why thats happening, might take that to #🖱️┃input-system though idk
what do you want the player for? there is a lot there
Oh wait so the sprite renderer is stating as disabled? Are you then enabling it somewhere else??
Where is it that you're enabling it? That could be working against you trying to disable it in your dash code
Are you sure it's actually staying disabled though? Maybe it's just behind something
And can you show the full script
I already checked its order in layer is above all else
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
in a controller under Player
how else do people make sprites invisible if not disabling
they do disable and enable
something is wrong here because that works
huh
im new to unity as an engine so prob some small setting
I'm still not totally convinced the code is actually running
it is.
having not seen the Debug.Log and the console
because when you've been working on something for a long time, sometimes you can miss small details. doesn't hurt to have another set of eyes to check over your work
happens to the best of us
Im a programmer by trade I understand that part
but I already assured him and checked myself twice that its running
I can send a video if you really want it
that would generally be preferable, yes
Because I deal with a lot of people here who are very new to Unity and think they did something but didn't actually do it, no matter how earnest and well intentioned they are
it's not a personal attack
I understand, I deal with that a lot too. But from someone who did programming as a trade for a while here is a video of it the code running
this server supports skill levels from Never Coded in my Life™️ to Has Been Coding Since Fortran™️, and frankly, we're not gonna remember who's who lol. we tend to have the same standard of "show your work".
Ah ok found the bug
Someone can help me. Im triying to do a movement by tiles, i create a empty gameobject with the tag "Tile" and i want the player move to the closest tile that is in front of him.
it is not a grid movement, because in each tile there is a different distance
if it's grid-based movement you would just keep track of the player's current grid coordinates, and when they move increment x or y by 1 in the appropriate direction. Then animate moving the player toward the corresponding world space location
So what is it
Can you share images/screenshots or an example of what you mean?
yep
The player is now in a tile, i want he moves to the next tile that is in front of him
yeah i did that but the 2nd question was different
there is a tile empty gameobject to detect the tile in each tile
but how are tiles defined
if I have a power up that moves on y axis a little bit and rotates, and then comes back to its position, and i want to use this animation in other 2 power ups, how can I do so when i spawn them not all of them have the same exact movement? I mean not on the same position but the movement being the same. I want one of them to start the animation in different keyframes so even they have the same anim they dont start in the same keyframe
i dont define any connection
Ideally you build up a graph (I mean this kind of graph: https://en.wikipedia.org/wiki/Graph_(abstract_data_type)) of tiles and then the player can navigate to whichever nodes in the graph are connected to his current node.
And another thing, when i did what you said I had to move the prefab into the hierarchy, put it inside an empty object and then this new object save it as a prefab, is there a way to override the original prefab into the new prefab i want which is an empty object with the orighinal prefab as a child? So i dont have to create 2 different prefabs
Not sure, what you really want here? But if you want to nest a prefab into itself, thats not possible
Hey, is anyone able to help me with a small issue that i have?
If you describe your issue and what you have tried, im sure someone may be able to help if they can/know about the issue
guys why does my GameObject spawn at its pivot point rather than its centre point
because the pivot point is where it's transform.position is
That's what the pivot is. It's the actual location of the object according to the engine
okay following question. why is the pivot positioned at the bottom of my object.
That depends on what we're talking about here
is it a MeshRenderer?
A SpriteRenderer?
Because that's where the origin/pivot of your 3D model is
How do you change it you mean?
change yeah
It's the 0,0,0 coordinatre in the mesh's coordinate system
Depends on which 3d modeling software you're using
but.. just google, e.g. "Change mesh origin in blender"
oooh. i made a mesh in unity. 0,0,0 was at the bottom of my mesh
You mean ProBuilder?
nah just in code
oh then - it's just your code
0,0,0 is the pivot/origin
in terms of vertex coordinates
when you create the vertices you can just add some offset if you want to move the origin.
thank you i'll have a play around with the vertices
does anyone know where I could find the resources to develop a multiplayer DOTS game?
resources? like learning materials?
if you're familiar with unity's netcode then this will help
thanks!
and it's been a bit but I've tinkered with it before
honestly i dont really understand how dots multiplayer would play out, it seems like a lot of data to sync
Hi all, getting to learn UI Toolkit on my own right now and I would like to get some help regarding order of operations or something else. My code returns this error when I try to set my gameobject to active.
Here is my code. I noticed that the Awake method runs even before the scene with the script is loaded. At least in the editor. This seems to result in my Visual Element being set to null. In what order should I run code in order to prevent my Pause Menu from being set to null in the controlling script?
public class UIController : MonoBehaviour
{
public VisualElement m_ui;
protected virtual void Awake()
{
m_ui = GetComponent<UIDocument>().rootVisualElement;
}
public virtual void Enable()
{
gameObject.SetActive(true);
}
public virtual void Disable()
{
gameObject.SetActive(false);
}
}
public class PauseMenuController : UIController
{
public GameSceneEventChannelSO _GameSceneEventChannelSO;
public Button m_resumeButton;
public Button m_restartButton;
public Button m_exitButton;
protected override void Awake()
{
base.Awake();
gameObject.SetActive(false);
}
private void OnEnable()
{
Time.timeScale = 0;
InstanceManager.Instance.isPlaying = false;
m_resumeButton = m_ui.Q<Button>("btnResume");
m_resumeButton.clicked += OnResumeButtonClicked;
m_restartButton = m_ui.Q<Button>("btnRestart");
m_restartButton.clicked += OnRestartButtonClicked;
m_exitButton = m_ui.Q<Button>("btnExit");
m_exitButton.clicked += OnExitButtonClicked;
}
private void OnResumeButtonClicked()
{
Time.timeScale = 1;
InstanceManager.Instance.isPlaying = true;
gameObject.SetActive(false);
}
private void OnRestartButtonClicked()
{
_GameSceneEventChannelSO.RaiseEventSceneChange(SceneManager.GetActiveScene().name, true);
}
private void OnExitButtonClicked()
{
_GameSceneEventChannelSO.RaiseEventSceneChange("Main", true);
gameObject.SetActive(false);
}
}
The structure of my scenes:
And would it be advisable to unsubscribe from the handlers on disable?
I want to implement a game where I will have many characters. None of them share common characteristics, but many of them could share common abilities. For example, many could move with a basic movement, some could jump, some could control gravity, some could fly, and so on. To achieve this, I thought of creating components, like the PlayerMovement class, the PlayerJump class, the PlayerGravity class, where I will define parameters and methods. Then, for each type of cube (or player), I will use GetComponent and use the methods from these classes. For example, in the Player1 class, I will get the jump movement component, while in Player2, I will get the component and then use the methods from these classes
Each player will have different animations, but I could implement them in each script, for example in PlayerMovement, like this. I couldn’t create a separate animation script unless it's a different one for each player, or I could implement it directly in their respective controller.
Could someone give me some advjse??
solved: i had the ui document disabled in the inspector, as well as conflicting key press code that disabled the menu right after enabling
Maybe wrong channel but couldnt find a better one. Does anyone know if you can set tiles in tilemap to either be colliding or not, or do you need to make a seperate layer in order for it to collide?
Have a dual grid system so could maybe use my base grid to create collisions polygons, havent done that before though so not sure how to
#🖼️┃2d-tools
but also you need to separate the collidable tiles onto a different tilemap
Ok, ill post there
i mean, okay, but i did just answer your question so i don't see why you would need to repost it
Cool, what was your answer to this?
"Have a dual grid system so could maybe use my base grid to create collisions polygons, havent done that before though so not sure how to"
yeah it's not even clear wtf that means if it isn't directly related to asking about your tiles being collidable. the tilemap collider applies to every tile assigned on the tilemap it is assigned to. therefore your collidable tiles will need to be on a separate tilemap
Great, then im happy to explain. Basicly I have a 50 * 50 grid that is beeing generated based on a texture input, this grid holds all relevant data. Then I have another grid offsetet by half a cell size that looks at the underlaying 4 cells in order to generate display tiles. This lets me get away with 16 tiles to cover all possible options and just needs basic binary addition in order to find the right tile
So I thought that using that to generate a collision map might be a good option.
Was that clear? @somber nacelle
I want to implement a game where I will
i have a bit of a problem
public void myfunc(){
myvirtualfunc();
}
public virtual void myvirtualfunc(){
}
i am running something like this, and the virtual function is called instead of its override, not sure why
only the names are different though, signatures are the same (its a simple script)
Did you add the override modifier to the method in the child class?
This should call the overridden method, so you are doing something wrong
wait
when i call it inside a for loop it doesnt work, but in a foreach one it does huhhhh?
Nobody can help without code
probably you operates on 2 different types, in foreach you seems to cast it to what you want(what you expect to be correct) so it works, in for loop you operates on the base type so the virtual gets called
This is very unclear because there is no code here using the override keyword, please share this
One reason whyt his might happen is when you use the new keyword in a method signature. You should not be using this.
Vector3 currentPointAlongToolAxis = GetPointAlongToolAxis();
if (currentPointAlongToolAxis == Vector3.negativeInfinity)
{
return;
}
Debug.Log(currentPointAlongToolAxis);
Vector3 newPos = currentPointAlongToolAxis - startPointAlongToolAxis + selectedPropPosBeforeMove;
selectedProp.transform.position = newPos;
// Move the tool objs to the new position
toolObjsHolder.position = selectedProp.transform.position;
``` Is it not possible to compare a Vector3 to Vector3.negativeInfinity?
compare in what way?
GetPointAlongToolAxis() returns Vector3.negativeInfinity;
If you assign an object's position to infinity, that will be a problem.
In the If statement
Imagine you are comparing something endlessly, imagine how long it would take 😉 forever probably
that's not how infinity works though.
What about startPointAlongToolAxis and selectedPropPosBeforeMove?
depends on the infinity 😉
not really, no
Another conversation not really related to this I guess 😄
but definitely not helpful to the situation
@rustic ember Ah nvm just saw you logging it before you use those
Looks like it should work: https://dotnetfiddle.net/xFhrQx
Test your C# code online with .NET Fiddle code editor.
Unity overrides Vector3 == operator, not sure if it works with infinity values
I think this is the key
Hmm... 🤔
nvm just saw that lol
Ahah
public static bool operator ==(Vector3 lhs, Vector3 rhs)
{
float num = lhs.x - rhs.x;
float num2 = lhs.y - rhs.y;
float num3 = lhs.z - rhs.z;
float num4 = num * num + num2 * num2 + num3 * num3;
return num4 < 9.9999994E-11f;
}
But it is logged as infinity before those values are used 🤔
Yeah here's the problem
return sqrmag < kEpsilon * kEpsilon;
is not going to work properly for infinity
Equals probably works
any difference of infinities would result in NaN
It just compares x y and z with ==
oh, so that's what the difference between those 2 are
"// Returns false in the presence of NaN values." Is infinity a NaN value? Or just a really high value?
you could compare your values to mathf.infinity tho and then clamp them to 0 for example
-Infinity - -Infinity is NaN
that's what he's trying to do
Try if(currentPointAlongToolAxis .Equals(Vector3.negativeInfinitiy))
@rustic ember are you aware with floating-point values as a concept?
What if it was positive infinity instead?
He is comparing to vector3.infininity, not mathf. to the separate axis
Yes
Infinity - Infinity is also NaN
Test your C# code online with .NET Fiddle code editor.
That makes no sense to me. It should be 0 right?
Infinity is not defined, so no value to substract from the "no value" infinity
Vector3.positiveInfinity and negativeInfinity use float.Pos/Neg Infinity
this is wrong.
How is it wrong? whats right?
But I could use Vector3.one * 1000000?
ahhhhhh nope lol
B-but... But math?
Yes, infiinity is weird
floating-points are not exact, they are approximations
0 is an approximation for anything that's too small (magnitude) to represent as a non-zero value; that's why there's -0 and 0, for positive and negative close-to-zero values
±Infinity are approximations for anything that's too big (magnitude) to represent as a finite value
so when you have 2 values that are represented by Infinity, you don't actually know if one is bigger than the other
10f**1000f and 10f**1001f are both Infinity, if you subtract them, you shouldn't get 0
you wouldn't really know what else to give though; it's impossible to reasonably represent, so you get NaN
But this would work right?
What are you actually trying to do here
use a magic value to represent something?
Why don't you use Vector3? (nullable)
this is also why x/±0 where x is any non-zero value will result in ±Infinity, but ±0/±0 will give NaN
Both ways are valid IMO
Infinity is well-defined for floating-points
this isn't math
this is an approximation of math for computers to use
see IEEE 754
I should have probably explained this from the beginning.
Vector3 pointAlongAxis = Vector3.negativeInfinity;
if (plane.Raycast(ray, out float _enter))
{
Vector3 hitPoint = ray.GetPoint(_enter);
pointAlongAxis = Vector3.Project(hitPoint, b - a) + a;
}
return pointAlongAxis;``` This is what teh GetPointAlongToolAxis() method is doing. I just figured I could return Vector3.negativeInfinity if the ray didn't hit the plane
Right!
you could also use a Try pattern
I would either:
- replicate the TryGet pattern in THIS method as well
- Return a
Vector3?
I could just return null
But just to conclude my suggestion, this one
Debug.Log("Vector3: " + (infVector == Vector3.positiveInfinity));
Debug.Log("Float: " + (infVector.x == Mathf.Infinity));
results in this screenshot
not directly for a Vector3, it's a value type, it can't be null
So thats what you could do to check if its infinity
because == is overloaded for Vector3 to do an epsilon check, not an equality check. you would use Equals instead, like osmal mentioned
public bool TryFindPoint(Plane plane, Ray ray, out Vector3 pointAlongAxis) {
if (plane.Raycast(ray, out float _enter))
{
Vector3 hitPoint = ray.GetPoint(_enter);
pointAlongAxis = Vector3.Project(hitPoint, b - a) + a;
return true;
}
pointAlongAxis = default;
return false;
}```
Using the Try pattern^
Ah, guess I missed the confirmation
@plucky inlet
Hi, I am having massive trouble with working with UI Toolkit scripting.
What load order here could be incorrect such that my InstanceManager is still null? This is not a problem in the editor, only built executables have this issue.
Where do you set the instance? And why are you setting booleans of another class in your mainmenuclass, if its not on method call but on enable? Or does your mainmenu get enabled later?
well if MainMenuController is loaded first, then that would be an issue
Awake+OnEnable are called together for each object (ref: #archived-code-general message)
The InstancManager is a persistent singleton of many Managers. It is instantiated on load in the scene entry point of the game.
I am unfortunately struggling to get something as basic as buttons to function so I have been hacking my code apart in search of a working method.
public class InstanceManager : MonoBehaviour
{
public static InstanceManager Instance { get; private set; }
[Header("Managers")]
public AudioManager audioManager;
public GameSceneManager gameSceneManager;
public InterfaceManager interfaceManager;
public TimerManager timerManager;
public ICineMachine iCineMachine;
public AstarPath aStarPath;
public bool isInMainMenu = true;
public bool isPlaying = false;
private void Awake()
{
audioManager = GetComponent<AudioManager>();
gameSceneManager = GetComponent<GameSceneManager>();
interfaceManager = GetComponent<InterfaceManager>();
timerManager = GetComponent<TimerManager>();
iCineMachine = GetComponent<ICineMachine>();
aStarPath = GetComponent<AstarPath>();
if (Instance != null && Instance != this)
Destroy(this);
else
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
Does the order in which game objects are listed in the scene affect this?
In fact, I don't really have any idea on what the standard practises for holding UI Documents and Scripts is for Unity. Would it be possible to point me in the right direction please?
You should not at all rely on your hierarchy to drive your scripts execution. Rather have something control your flow of data and enable/disable depending on states rather then just all at once
For example, should UI Documents and associated scripts be all persistent singletons that persist across all scenes?
your InstanceManager is instantiated?
So in this case, perhaps my UI game objects should be enabled and disabled based on a controller
It sure is, else my game would not function past a blank screen
Okay, but then you really have to get a statemachine going to tell your game, what is happening. First, setup of managers or what not, like your instancemanager, then setup the UI with your controllers and so on.
Okay, I'll try that. Thank you
Would it be advisable to use SOs to function as event channels for communication between locations where calls to enable and disable UI documents?
Not really. SOs should be used as data providers.
You rather have some kind of UI Manager reacting to for example gamemanager states or user inputs and what not
when activating the debugger in visual studio it sometimes causes unity to infinate load so that i cant launch the game or do anything, it happens off and on but sometimes it can persist making it impossible to debug, does anyone know anything about this issue?
async tasks in Unity continue after play mode has stopped... 
I think I need UniTask...?! Which avoids such things by default?
It can be slow but is not infinite for me at least. However if I cancel debugging while on a break point in VS then I have to wait WAAAYYYY too long!
Or you can add a Cancellation Token that is triggered by EditorApplication.playModeStateChanged
Yes so I read this but seems like I would be adding coding overhead. however the doc does also not actually give an example where as seems like this should be checked everywhere
Do async tasks end on closing a .Net app, is this some unity issue? What would be a reason to allow tasks to continue?
Your editor isn't closed when you exit play mode.
Indeed. Interesting discussion recently here: https://discussions.unity.com/t/on-async-await-with-awaitables-as-a-coroutine-replacement/1554090
Erm yeah fine for editor code, but you can run async code in play mode, stop playing your app and it continues to mess with your scene in the background!
yeah, you would need MonoBehaviour.destroyCancellationToken which should be available in 2023 and above
wait, I think Unitask is doing that already via it's own custom playerloop, oh you're not using uitask,, misread, yeah you need the method above
That's what I'm pointing out with the .NET app comparison, when you close the .NET app, the entire process is gone and dead, but exiting play mode isn't comparable because the editor process is still very much alive and kicking.
Doesn't Unity cancel running asynchronous processes through cancellation tokens?
it doesnt, thats why they give us MonoBehaviour.destroyCancellationToken
So if you combine your cancellation tokens with this (assuming you use them), you can cancel running Task instances
@placid summit ☝️
I will continue to recommend UniTask 😄
What does UniTask have to do with cancelling the Task? Does it do it automatically?
unitask uses it's own custom player loop, which is based on the undocumented PlayerLoop
it can cancel all tokens when exitting the editor properly
Is PlayerLoop still undocumented
Neat, can definitely be beneficial there
I assume this can be configured so I can keep tasks running? I can imagine you might want this
Does UniTask just cancel all tasks on exiting play mode in editor?
(play mode tasks)
Really the problem is glTFast decided to scatter Task throughout its codebase and I have to deal with Tasks now
depends how how you started them, there is no guarantee.
barely
I haven't used UniTask but it sounds very useful to have
I do think it would be overkill to pick it when you can just use the CancellationToken, but at least a nice alternative to consider
I feel like having control with CancellationTokens would be so much easier to manage, though perhaps prone to issues if you forget to implement them
if you do anything with tasks, unitask is not overkill, regular tasks in unity have so many gotchas you need to know about
Awaitable is meh
it (UniTask) is one of those packages made by someone with extensive experience with real world problems they wanted solved
not sure what that means, but Awaitable is quite lacking of useful methods like what regular Tasks has
Unitask covers most of those
Awaitable does exit at end of play mode?!
try it
its best to not rely on it and always pass a onDestroyCancellationToken that every component has
it seems to exit, but I know nothing of using tokens
then you should learn about them, you can't use tasks sensibly without them
by default a (runaway) task will only automatically terminate when the process (App) that owns it is terminated
async functions wont stop when playmode ends unless a cancellation token is used, you check for null or an exception is thrown
unitask tracker can help you check this (if using unitask that is)
its more than just terminated, you'd need to properly dispose them, even when they're cancelled/completed, they can leak in the grand scheme of things
you cant leak program owned memory when the process terminates...
So everyone still using Unitask? Havent looked into awaitables yet
not that any of this stuff works for webgl :(
must be a webasm limitation and well js "threads" are a joke
JS is fully capable of multi threading.
but hey, I'm blowing up peoples GPUs overhere
It's also up to the runtime (not the language) to provide multi threading capabilities, and all popular runtimes have them, eg web workers in browsers, Node.js workers in Node.js, etc.
This is something you should definitely learn. It's heavily used, even outside Unity
It's the main way to stop asynchronous Tasks from running gracefully
Or not gracefully, that's also possible 😄
but ya know, spectre vulnerability and stuff and services don't want to support them
awaitable does not have Forget() so... seems annoying. How should an Awaitable be triggered from a synchronous function to avoid warning?
There are that many browsers?
and devices
probably multiplying the 2
they support discard iirc _= MyAsyncMethod()
1998 devices
Firefox,
Chrome
As in a fire and forget method? I'm not sure how Awaitables work in this matter but the base Task based system just allows you to call itself and discard the task without awaiting it
Alternatively, Task.Run for true background tasks exist in case the method is blocking before it would ever switch its context
// This can block the main thread in some cases
_ = FooAsync();
// This never blocks
_ = Task.Run(FooAsync);
{
public static async void FireAndForget(this System.Threading.Tasks.Task task)
{
#if UNITY_EDITOR || UNITY_DEVELOPMENT
try
{
await task;
}
catch (Exception e)
{
Debug.LogError(e);
}
#else
await task;
#endif
}
public static async void FireAndForget(this Awaitable awaitable)
{
#if UNITY_EDITOR || UNITY_DEVELOPMENT
try
{
await awaitable;
}
catch (Exception e)
{
Debug.LogError(e);
}
#else
await awaitable;
#endif
}```
Note that you should always make sure to gracefully handle these methods in a way where you manually try-catch the method to avoid it getting ignored
you can do #if DEBUG (which is true for editor and dev builds)
I don't think it matters as much with Unity, though. The console would show any errors. The issue is that it might break your application
incorrect, unity does not catch threaded errors
yeah async void call and then do awaitable. ah anyway I am probably screwed as glTFast uses Task - seems like an over sight to me that it does so
you mean it doesnt print them in the console
I was specifically talking about them being printed in the console in any way
I didn't say Unity would catch them
.NET has TaskScheduler.UnobservedTaskException, I don't know if you can use it here
I assume Unity would have something similar for this
thats why you wrap your fire and forget in a try catch in debug scenarios
Yeah but your log is not gonna help much in production
or else the errors will go completly silent in the background
But you're right, at least silent exceptions are not the case
no like 40 browsers and 50 devices -> 2000 combos
Does Unity have an event similar to this? #archived-code-general message
Or do Awaitables also hook on this?
I would stay away from task in newer version of Unity. I am unsure how the Unity context and task shecudler works. I dont beleive its default implimentation though
why?
you can do
public static class TaskExtensions
{
/// <summary>
/// Wraps a fire-and-forget task in a try-catch block to prevent unobserved task exceptions. Also silences the
/// related roslyn warning.
/// </summary>
public static void Forget(this Task task)
{
var awaiter = task.GetAwaiter();
if (awaiter.IsCompleted)
{
try
{
awaiter.GetResult();
}
catch (Exception ex)
{
PublishUnobservedTaskException(ex);
}
}
else
{
awaiter.OnCompleted(() =>
{
try
{
awaiter.GetResult();
}
catch (Exception ex)
{
PublishUnobservedTaskException(ex);
}
});
}
}
}
SharedArrayBuffer is not required to do multithreading in JS, that's like saying "C# must have ConcurrentDictionary to do multithreading."
what is this 😅 ...
GetAwaiter/getresult can deadlock
Bit less related but .NET also has AppDomain.UnhandledException for exceptions in general
Again idk if Unity works as good with this and/or if it has an alternative. Would love to know if it does
So what's the reasoning that WebGL still has no actual multi-threaded support? SharedArrayBuffers were suggested but eventually were deprecated years ago and not since have Unity added an alternative.
As it seems, they're more focus with WebGPU at the moment and completely abandoning any threaded support it seems
I guess the move to webgpu?
Which works great^
WebGl is kinda dead
The conversation started on JS multithreading and now seemingly it has moved to WebGL/WebGPU?
The dicussion was about awaitables and unitask not working with WebGL
because at the moment there is no async operations
WebGL is a technology that enables JS to access to GPU in browser, I don't think that's really what you meant. What you meant is probably "why doesn't Unity's web target platform support multithreading" in which case the answer is just, Unity doesn't support it.
UniTask does something similar so id trust it! https://github.com/Cysharp/UniTask/blob/master/src/UniTask/Assets/Plugins/UniTask/Runtime/UniTaskExtensions.cs#L552-L583
I would think there's a bit more to it than just "not support it" considering it was one of the largest focuses with Unity 6.
There's no technological limitation where multithreading cannot be done in web browser, you can literally use it right this moment: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
As for why Unity doesn't support it, that's a question that has to be answered by Unity, maybe it's architectural reasons, maybe it's legacy, maybe it's something else.
I'm just saying. If it was that easy to implement, you'd think Unity's team working with WebGL would be on it
"unitask guy understands more about tasks than anyone in here" is my heursitic
I'm not a web dev, but I've been doing a bunch of webgl games for a decade now
Anyway as it seems, any async operations will be done through compute shader with how the preview went
that's the future for WebGL/GPU with Unity
Related, Godot abandoned multi-threaded support for their web exports
There are quite a few things going on in this conversation, I'm still failing to grasp why multithreading in JS has anything to do with WebGL/WebGPU, but I think I've cleared up the point pretty clearly that web does support multithreading just fine, and it's up to Unity/Godot/Blazor/whatever to make use of that underlying technology.
does unity use webasm or js for user code cus im not really sure?
That doesn't matter because WASM and JS can interop.
WASM cannot even run without a bit of bootstrap JS.
How to implement mountable vehicles and mountable animals
mountable WHAT
ridable?
mountable isnt a bad word
oh wait I just read the last part of the thread name 😆
off to jail you go
nah it definitely gets stuck and other times it works fine, its like random whether it works or not chatgpt said something about burst debug but i think it was tripping because I saw no such option to disable
im looking for AI help to my programming, ive noticed that chatgpt has become very stupid and never gets anything right , is there any good alternative? not looking for full scripts, just help with questions, short thigns and algorithms
good alternative is to actually learn what you're doing
I am having trouble getting my .clicked event to fire. I'm not sure what is wrong? The string name references are correct and my other controller, the MainMenuController has similar code but works just fine.
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
namespace FW
{
public class PauseMenuController : UIController
{
public GameSceneEventChannelSO _GameSceneEventChannelSO;
public Button m_resumeButton;
public Button m_restartButton;
public Button m_exitButton;
private void OnEnable()
{
Time.timeScale = 0;
m_resumeButton = m_ui.Q<Button>("btnResume");
m_resumeButton.clicked += OnResumeButtonClicked;
m_restartButton = m_ui.Q<Button>("btnRestart");
m_restartButton.clicked += OnRestartButtonClicked;
m_exitButton = m_ui.Q<Button>("btnExit");
m_exitButton.clicked += OnExitButtonClicked;
}
private void OnDisable()
{
Time.timeScale = 1;
}
private void OnResumeButtonClicked()
{
gameObject.SetActive(false);
}
private void OnRestartButtonClicked()
{
_GameSceneEventChannelSO.RaiseEventSceneChange(SceneManager.GetActiveScene().name, true);
gameObject.SetActive(false);
}
private void OnExitButtonClicked()
{
_GameSceneEventChannelSO.RaiseEventSceneChange("Main", true);
gameObject.SetActive(false);
}
}
}
you can't shortcut your way through knowledge
there's an #🖱️┃input-system channel
put logs and check if it even clicks
also #🧰┃ui-toolkit
my bad, ill ask there
i dont have 5 years to read into advanced rarity algorithms or take a day to read through 500 stackoverflow and reddit questions just to understand how to properly write an algorithm for my needs :( i dont have the math knowledge for it so stop being condesending, thanks
ah ill ask in #🧰┃ui-toolkit
doubt input system is related to this
where should i put the logs? i know for sure the methods assigned the the event doesnt run at all
hmm its always good to put assumptions aside with proper tests
also not entirely sure if UIToolkit needs the Event System for the new Input Module to work , double check that too
what kind of answer are you looking for then ? Programming takes years of built up knowledge, GPT doesn't work especially when you cannot differentiate between truth or hallucinations
you are being very negative and condescending because you seem to have some hate against gpt, even tho it can be a valuable help, id like to not converse with you any further since you clearly did not understand my question and just got triggered, thanks
it can be a valuable help
it's a tool
it's not a replacement for experience
in particular, you need experience to be able to utilize it effectively, when correctness matters
no problem. I just block and move on 🙂 goodluck friendo..
it does good for sources lookup with web option, but generated prompt is falsy true in most of cases of advanced questions
correct, if youve read my question you can understand that i obviously tried gpt and with my experience and knowledge noticed that its barely any help at all if it is about topics other than basic code fundamentals, thats why im asking if there are more advanced solutions , specifically for programming related questions, in my example i asked gpt for help with a rarity algrithm because my own wasnt good enough, the results ive gotten were worse if not wrong most of the time
you should not rely on AI help in general
consider building up researching skills, for example how to use google search syntax effectively
the internet has a lot of info, just gotta find where it is
thats why im asking if there are more advanced solutions , specifically for programming related questions
with AI? no
a tool is a tool, you shouldnt not rely on X because of Y is really narrowminded
just not really how AI works
If you're looking up algs, always ask for references for where that information was gained if you want more insight and not be too reliant on it
it usually will provide you some direction
you shouldn't rely on tools in general, no? you should be able to work without them. tools make stuff easier if you can use them properly
im more annoyed by the fact that gpt is presenting it as correct, when anyone with 2 braincells can tell that its not, thats why im looking for an alternative to it xd
gpt isn't special; none of the chatbots are special
yeah, stop using unity man, machinecode it is :)
there is no reliable ai
pattern matching is not intelligence
I find it great at finding me documentation I can't find otherwise. It's a glorified search engine and I like it when compared to google nowadays
now this, this is an example of a strawman argument in bad faith
thank you, thats why im asking, that was my question but someone got so triggered by me asking about AI lol, if there isnt, im ok with that, just wanted to know
i dont keep close eyes on gpt development etc
google search is usless nowadays
google has been useless since people started gaming the alg and all those "Top ten" blogs started to spam the top results
if you ask people in this channel they will tell you to not use google search as a tool and get books from the library ;) lmao what a clownshow
pseudointellectuals everywhere you go
huh triggered telling someone to build up knowledge, projection at its max
i don't see anyone getting triggered tbh
but as a rule of thumb, ai is discouraged in many, many places
ai isn't as useful as the marketing would lead you to believe
it's great for pattern matching, so for research and industrial automation that depends on that, and not much else
i noticed, gpt barely provides any valueable info lmao its actually really really dumb
that's LLMs in general
with all the hype and youtube videos i thought that it would be atleast usefull for low level programming questions but it fails at even that
I would strongly recommend people to take a look at how LLMs generate texts, you don't need a ML degree, just a simple overview of how it works and you will immediately understand why they are not reliable: the last step of generating text is literally rolling a dice and picking a token based on probability.
really sad
I don't need correctness from a dice.
it's a "new" technology (at least to the general public), and that's a double edged sword, because people with financial incentives can lie about it and the general public wouldn't know any better
never looked at it that way but youre right yeah, i used to use gpt in the early days as a better way to get the info i would have gotten through google, but since google is barely useable aswell, well here we are
same thing with crypto and blockchain and nfts, see all the scams the past few years where they never actually took off
wouldnt say that, but yes some feel overconfidemt because they sit with one technology for long and thinks that they know everything but its not the case, those people help for free so its very valuable for others so dont see a reason to argue with them
they're useful, but not as useful as they're claimed to be
well then let me ask my question here, im trying to programm rarity, 0 to 100, lower values being more common, how would you do it? i got sth that is fine thanks to gpt for now, but im still lost and not reaaaally happy with it since it has a lot of 1 and isnt as spread around the lower values, as i want it to be
that's hilarious compared to youtube putting suicide help lines on videos that say something tangentially related once lmao
use the rarity as a weight
this is what ive got
public int GetRandomRarity(float rarityWeight = 2.0f)
{
// Step 1: Generate a random value between 0 and 1
float randomValue = Random.value;
// Step 2: Apply the rarity weighting formula
// Lower values are more likely; higher values become rarer
float weightedValue = Mathf.Pow(randomValue, rarityWeight);
// Step 3: Scale the result to the range (1-100)
int rarity = Mathf.CeilToInt(weightedValue * 100);
return Mathf.Clamp(rarity, 1, 100);
}
i guess like, 100 - rarity, as the weight, rather
using a weight of 5 works fine, but the lower values are like i said, not as spread as i want
oh hold on
Depends on how you are using it, if you are using AI to lead you to the source material then sure, if you are just using AI to regurgitate information then that's not a justified use case.
Unlike source materials where the author's reputation is at risk, LLMs are never held accountable no matter how many times it gives you crap. If I keep giving wrong information here in this chat, I will be called out for it, but someone will always make excuses for AI "yeah maybe this time the dice just didn't roll the right way."
what's the input/output?
i thought you meant rarity (0-100) input, and then a yes/no or a selection output
nope
you fish a fish, then roll for weight 0 to 100, but i want it to be more common to get values 1-30ish, and 90+ should be rare enough for it to only be there once or twice in 100 rolls
ah ok
are we talking about ✨ distributions ✨ ?
so are you just kinda, mapping the randomvalue from 0-1 to 0-100 with a bias towards lower numbers?
https://github.com/mackysoft/Choice
I usually do that for weighted items
gotta find a pdf for this then lol
mackysoft always got the goods
a cdf is more useful (:
ah, true
yes
well, an inverse cdf
but a pdf would be more easily mappable to code wouldn't it
An inverse cumulative distribution function lets you sample a uniform random value and then compute a value from the distribution
The simplest system would just be defining a list of all possible outcomes and their weights.
the density function isn't too helpful on its own: you can't use it to sample from the distribution
Yes -- this is a great idea if you don't intend to give a very rigid meaning to each rarity tier
Also, you can get pretty far by doing very basic reshaping of a uniform distribution
yeah i could yanderedev this but i thought about having a fancy rarity function i might use again for sth else
For example:
float BiasedRandom() {
return Mathf.Pow(Random.value, 2);
}
This gives you more small numbers
It's so much simpler to maintain a uniformed distribution and map it to a weight table, than doing some fancy math. It's not about being "YandereDev garbage code," you can have a well written simple system just fine.
Being complex doesn't mean it's automatically better, being simple doesn't mean the code has to be garbage.
sometimes it is most practical to just enumerate every outcome
then i missunderstood, but how would you do that for values 1 to 1000 ?
hard code a weight for each value? thats madness
That mackysoft has a nice overview on the search algs with some graphs for different search algs
do you need 1000 values?
you could just define statically-set ranges, then add random variation to the middle value
yes, maybe even 10000
enuemrate is probably fine
I'm not sure why you would need 1000 values, you only need as many values as the amount of outcomes there are, eg if there are 3 possible types of fish you can fish up then all you need just 3 values (one for each type of fish) and that's it.
wow i have no idea what i'm doing
??? i dont understand what you are saying sorry
this would be a cdf, right? @heady iris
fish have a weight float, which i want to be between 1 and lets say 10000
i could use a simple random.value but thats not what i want
i want higher values to be very rare
lower values to be spread well
You still need to define "very rare"
no, for a few reasons (including because it's decreasing, and because its integral isn't 1)
https://en.wikipedia.org/wiki/Cumulative_distribution_function
wouldn't it be a pdf if the integral was 1
oops, yes, that was backwards.
it should reach 1 (:
ah, of course
10000 is a meaningless number if you don't give it a well defined value, what you are trying to do is that you have some vague definition of rarity (high number = very rare) and trying to find some mathematical algorithm to match that vaguely unspecified rarity number. What does 10000 mean in relation to 10? Does it mean it's 1000x rarer? 3 times (10^3) rarer?
Is there a reason why you are not doing the typical approach to loot table?
i was thinking x being the randomValue input, and y being the weight output
so for the curve i showed, it'd be a 50% chance to get >7, 20% to get >40, etc
does that make sense (asking fen)
oh this is the inverse cdf you mentioned, right?
Perhaps you have the opposite question
because i thought there is some sort of math algorithm for exactly that, you could rewrite my question into simple words like
i want to roll for a number between 1 to 1000 but have the result be weighted towards 1-500 with a variable i can adjust
"How can I turn a weight value into a rarity tier to show to the player?"
It seems a bit weird to be talking about rolling between 1 and 100, or between 1 and 1000
What about the simplest loot table approach that's used by practically every game?
you can choose whatever range you want
how would you make a loot table for weights that go from 1 to 10000 ?
why do you need 10000 different rarity values?
you don't, that's not what they're suggesting
you've gotten obsessed with specific large numbers here
i think you guys are getting confused by weights and weights of the fish as in kg
You are too hyper focused on the arbitrary number of 10000, where you can't even define what "10000" means.
no, we know what's being described
no im changing the number because you are focused on that when it shouldnt matter at all
the upper limit should be whatever number i want whenever
just to make sure we're on the same page here; there's no rarity, is there?
just a weight (physical quantity) that needs to be distributed
if there's not rarity then that would change the problem completely
you catch a fish
code rolls a magic number, this magic number is the weight of the fish
the weight can range from 1 kg to 100kg or whatever i define as the max weight for it, maybe 10000kg its up to me
i want the roll to be weighted towards lower kg results, idk lets say 1 to half of the max kg
and the high kg numbers to be weighted rarer, lets see 70 to 100% of the number
if we stick with 1 to 100 then 1 - 50 should be common, 50-70 should be uncommon and 70-100 should be very rare
is that more understandable
the mass of a fish would be decided by a normal distribution
this would give you very reasonable results (with some clamping required to avoid things like a very rare -10kg fish)
wdym with normal distribution ? i dont understand
are you asking how to turn a uniformly random number into one that belongs to a specific distribution?
In that case, you can pick any kind of curve you want, and the integral of the curve from 0 to x over integral from 0 to max will represent the chance of getting x.
wow, thanks for the embed, wikipedia
yeah, i connected the dots a bit ago though; no need to explain it to me
that brings me back to my original gpt question lmao, how do i do that? im shit at mad at mediocre at c# at best, never really worked with algorithms formulas and math
I've described the process here
You can calculate the integral from 0 to max given the known curve and max, randomize a number between 0 and the result, then reverse the calculation to retreive x.
ty, ill look into normal/gaussian distribution 
The "secret sauce" here is the function that maps from a uniformly random value to the normal distribution.
you aren't going to need algorithms for this; do you know some basics about statistics?
school basics 💀
You don't need a specific curve, literally any differentiable curve will work.
that varies wildly 😭
i would rate myself in Math with an D
ill be fine with keywords i can google and research
but there's so many levels of math that the rating is almost meaningless lmao
use a library. there aren't closed analytics for all of these. if it's important for you to sample with any mean and variance for normal for example. for real stuff you almost always want lognormal.
anyways you'll probably want to figure out how distributions work
don't worry about the math. use a library
im not the one asking
there's plenty of these algs laying around, especially related to games since it's a pretty common problem
ah
I have not carefully inspected the math behind the code linked here, indeed
and I don't have to!
is there a magical place for them or do you guys have a secret to not get shitty google results
iirc it's an approximation of the inverse CDF -- which I believe there is no analytic form for
google search is "unity random distributions library github"
if not shitty, half the results are malicious ads
there are lots of options
here's the secret: https://support.google.com/websearch/answer/2466433?hl=en
There are different ways to filter your Google searches to be more precise or to expand in new directions. Advanced search Google offers pages designed to help you perform specialized web and image
that is exactly what i wanted holy shit
wow that article lists so little
add "Github" or "reddit" to your search
^ I feel like people are too focused on a solution for a specific curve, the general calculation outlined here works for any curve, whether it's Gaussian, normal distribution, f(x) = whatever*math/equation+here.
there is no general calculation for a normal distribution which is why nobody teaches it.
that repository is basically what fen linked
Replace from 0 to max with from min to max and you can expand it to any range including infinity.
there's no analytic inverse cdf for gaussian
this is what i wanted in code form but able to adjust the curve to my liking
this is an exponential distribution. the discrete version (probably what you want) with two parameters is pareto
the thing i linked has exponential
im pretty sure that's not exponential
it wouldn't asymtoted on both axes, no?
so real
Hey guys, I have a quick question about CloudSaveService
I want to do CloudSaveService.Instance.Data.Player.LoadAllAsync, which returns a dictionary<string, Item>
So if I modify this dictionary I later want to save it with CloudSaveService.Instance.Data.Player.SaveAsync
but that takes a dictionary<string, object>..
Is there an easy conversion between these two I have missed?
To anyone that finds this:
I used .GetAsString() and stored all intermediate data as strings...
you said "this is an exponential distribution" though, which, well, is it?
And simply integrate the curve from x = 0 to x = 100 to get the sum (represents area under curve), uniformly randomize between 0 to sum, reverse the integral and you get back the x that's randomized weighted according to that curve.
well that's just a drawing
that's what it is
This process works for literally any curve, given that the curve is differentiable.
but it's much closer to say, 1/x than an exponential function
massive plead emoji
can always just integrate python and use some numpy
try the exponential function from that library. it really depends what you want to do
like im confused what you're trying to say here
what is the gameplay goal?
for pulling stuff out of a bag, that is, most game behaviors, including modeling pity, you want hypergeometric
it really depends on your gameplay goal
this is the gameplay goal
it sounds like you're saying "you want an exponential function", but you said that what they drew was an exponential function
so like, what's your claim here
having high weight(KG) = better
do you want pity?
do you know what that is?
really if there's not catagorizing it's just a curve you throw a dice at
common, uncommon, rare, "legendary" kind of has some player expectations to it. is that important to you?
no
sometimes the best way to model this is to create a deck of 100 fish, and draw from it. this will have pity built in.
otherwise, if it's really totally independent ("harsh" as you say) use exponential.
probably can just use an animation curve honestly
exactly
I've already given the answer here.
I'm having issues with my PropertyDrawers not actually binding the values of a PopupField in the inspector. What's the most appropriate way to share the code I've got so far without flashbanging the channel?
if he draws that curve, no matter which direction, it doesn't solve th eproblem
just use exponential. you have 1 parameter
see if it feels good
"lambda" is the "rate" (higher means bigger values are more rare)
uhh i think you mightve misread what mao said
to turn it into kg, you can do min(1, floor(exponential(some rate)) + 1, 100)
but. @unkempt swallow . you should model this as a deck you draw from. it will be more fun
The solution I've given literally works for any curve, they can change the curve however they like until it feels good.
you can also refill the deck after you draw if you want it to be "harsh"
i think with the lack of confidence in math kinami has, the animation curve would be a viable option 
the curve doesn't mean what you think it means
im checking all solutions offered, rn using the linked github repo and the radnomexpo, but the values are 1.004811 like, nothing above 1
not a distribution curve or a probability curve
okay. what do you want the average value to be?
like most of the time
Is there a more appropriate place to ask this?
randomly chosen between 1-20% of the max value
the one that you should "expect" to get
rate = 1 / expectation
you aren't expressing htis quite right. the expectation is 20kg? 10kg? etc.
so 10kg?
so the rate you want is 1/10.0
no i dont want one specific value , it has to be random like i said, i dont want to define anything solid
if i wanted that i could have hard coded it by now xd
do you know what a mean is
no
okay well
was my picture not good enough 
haha
if you fished 100 times, what should the average be
i think you are learning it's okay
(pretty sure an animation curve would mean exactly what it seems like)
🥺
that isn't in the realm of statistics anymore
side question
https://en.wikipedia.org/wiki/Exponential_distribution are you supposed to learn this in school?
In probability theory and statistics, the exponential distribution or negative exponential distribution is the probability distribution of the distance between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate; the distance parameter could be any meaningful mono-dim...
depends, really