#archived-code-general

1 messages · Page 412 of 1

stark sun
#

isnt that line is the like anchor

#

for the limit

#

didnt think this would matter

still jungle
#

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

stark sun
#

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

full rain
#

!cs

tawny elkBOT
stark sun
still jungle
# stark sun

now it have good angle limits, but you breaking those limits anyway with high force

stark sun
#

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?

still jungle
#

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

placid cairn
#

ignore PhysicalBehaviour

somber nacelle
#

try asking in the game's modding community. modding discussions are not permitted here

placid cairn
#

alr

bleak plank
#

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.

  1. When I move my mouse, you can see the UI has some motion blur, I don’t know why that is

  2. 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

bleak plank
#

Thank you

potent sphinx
#
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.

thin aurora
#

Does it enter the if-statement?

#

Or does it at least increment compsRemoved here?

potent sphinx
#

Yeah it does increment that counter

#

It is confidently logging out "Destroyed 221 Missing Scripts 😎 "

hexed pecan
potent sphinx
hexed pecan
#

What if you mark them dirty with EditorUtility.SetDirty afterwards

potent sphinx
#

I am now trying to deserialise the object and then remove componets mnaully

potent sphinx
hexed pecan
#

Yeah I think it's because you are passing null into DestroyImmediate so it doesn't know what to destroy

potent sphinx
#

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....

hexed pecan
potent sphinx
#

Jeez

hexed pecan
#

Apparently it's been around forever, never heard about it lol

#

Just saw it mentioned in a discussions thread

potent sphinx
#

And it worked

#

😭

#

Thank you so much

#

I had been looking at unity forum posts from 2010

stark sun
still jungle
stark sun
still jungle
lost rivet
#

is there a way to copy a component to another object?

hexed pecan
#

At runtime?

plucky inlet
#

Reflection I guess

lost rivet
leaden solstice
#

What for

hexed pecan
lost rivet
#

i mean, i suppose you could serialize and deserialize it

hexed pecan
#

You'd just need to AddComponent first

lost rivet
plucky inlet
#

Direct way (reflection), performant way (json)

leaden solstice
#

Serializing then deserializing is pretty much direct way

lost rivet
plucky inlet
leaden solstice
#

Don’t do that tho

lost rivet
#

ohh makes sense

#

but i think serialization might be better

leaden solstice
#

You don’t know what fields Unity use internally

#

And what is going to happen when you blindly copy them

lost rivet
leaden solstice
#

Serializing is more robust way since you can control what is serialized

lost rivet
#

also, i dont think they json utility thing works on built in components

hexed pecan
leaden solstice
#

JsonUtility is same serialization as you save to prefab or scene

plucky inlet
#

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.

lost rivet
#

it throws an error when i try to serialize an engine component

#

let me show

plucky inlet
#

There we go already 😄

hexed pecan
#

The doc only mentions MonoBehaviour/ScriptableObject support yeah

plucky inlet
#

Newtonsoft might be more useful in any case too

lost rivet
#

newtonsoft doesnt work either

plucky inlet
#

can you show, what you are trying to serialise?

lost rivet
#

i tried, it cant serialize either because the monobehavior has the gameObject property

#

which causes an endless loop

leaden solstice
#

Don’t use newtonsoft for this

plucky inlet
#

so you not gonna show your class you want to serialise? 😄

lost rivet
#

for example linerender i guess?

leaden solstice
#

In any case, it’s just better to find a way that works with either Instantiate or manual logic

stark sun
lost rivet
#

most of my custom scripts work fine tho

leaden solstice
cold parrot
plucky inlet
hexed pecan
#

UnityEngine.Object

leaden solstice
lost rivet
stark sun
lost rivet
#

anyway this is like a seperate problem entirely

#

i will figuere it out

cold parrot
#

you can use newtonsofts .Populate() API to write a serialized state to an existing instance

plucky inlet
#

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

cold parrot
#

its a good idea to use a memento pattern when serializing monobehaviours

lost rivet
cold parrot
leaden solstice
#

It’s probably the references your class is holding

cold parrot
#

also you should not serialize references anyway, that causes more problems than it solves

leaden solstice
#

Anyhow can’t you just Instantiate the whole game object

#

That’s easist way out

cold parrot
#

its a fundamental feature of any save-system that you come up with a maintainable way for referencing stuff in savegames

lost rivet
leaden solstice
#

What do you mean

lost rivet
#

after instantiated from prefab

leaden solstice
#

You can instantiate that instance

#

Instead of prefab

lost rivet
#

wym o;o

leaden solstice
#

Or use it as prefab, ig

#

Instantiate is essentially copying the game object you pass in

lost rivet
#

oh yeah right, i think we have mixed a couple different problems here

#

anyway, ill figuere out

#

thanks all

thin aurora
leaden solstice
#

JsonUtility shouldn’t be looked as json serializer competing with Newtonsoft, it should be looked as Unity serializer

latent latch
#

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

leaden solstice
#

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

thin aurora
#

Are you saying that JsonUtility is able to deserialize into MonoBehaviour classes whereas Newtonsoft can't do it?

leaden solstice
#

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

thin aurora
#

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

latent latch
#

It's very limited compared to when you can serialize at editor time, not everything usually you can [SerializeField] work with JsonUtility I noticed

thin aurora
#

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)

latent latch
#

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

leaden solstice
#

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

lost rivet
#

what does that even mean

thin aurora
#

I'd love to see an example where JsonUtility is actually a better choice compared to Newtonsoft

lost rivet
#

which is a unity problem, i agree

leaden solstice
thin aurora
leaden solstice
thin aurora
lost rivet
#

even with the package

thin aurora
#

You're not supposed to do that anyway

leaden solstice
hexed pecan
lost rivet
thin aurora
#

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

hexed pecan
#

Without cloning the whole gameobject

thin aurora
#

It's clear that you guys rely way too much on this if you think it should be able to do all this

lost rivet
thin aurora
#

It's a serializer, not a full on object creator

stark sun
#

how can I make this object to look up like this at start?

hexed pecan
#

You are just getting super defensive about newtonsoft for no reason.

latent latch
#

JsonUtility doesnt serialize components, no?

lost rivet
hexed pecan
#

But not with builtin components AFAIK

plucky inlet
#

For my last project, I just build equivalents to builtin components, like a serializablevector3 for example and what not

lost rivet
#

but what happens if you try to serialize an object reference?

lost rivet
#

alsoit should be serializble by default

steady bobcat
#

giving json to you guys was a mistake 😆

thin aurora
leaden solstice
#

Probably object ID

hexed pecan
latent latch
#

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

lost rivet
#

but who is json? 🤔

hexed pecan
#

I'd imagine the behaviour is the same as copy/pasting a component in the editor

plucky inlet
# lost rivet vector3 is not a component...

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

leaden solstice
#

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

hexed pecan
thin aurora
#

Which is not going through hoops with an alternative to get things working?

hexed pecan
#

Not a massive hoop IMO

thin aurora
#

Let's not forget nullable types here. JsonUtility can't use those either

#

Seems like quite a hoop to me

hexed pecan
#

I like how things align with unity's own serialization

#

Because that's literally what it is

leaden solstice
#

You don’t need that if you want to follow Unity serialization

plucky inlet
#

Feels like this discussion ran out of sight from the actual question, didn't it? 😄

hexed pecan
#

Json is always a hot topic :p

warm badger
#

what features do you think should be considered when registering a swipe gesture?

thin aurora
#

The real issue here is Unity like always

plucky inlet
plucky inlet
latent latch
#

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

hexed pecan
#

It is certainly subjective and usecase dependent

#

Saying that X is always better than Y is naive

leaden solstice
#

Whatever is not supported in Editor, like Dictionary, is not necessary for JsonUtility

plucky inlet
leaden solstice
#

Because it’s not JsonUtility to support whatever Unity doesn’t support

lost rivet
#

Unity does support dictionary

plucky inlet
#

you guys wanna throw that discussion in a thread probably?

thin aurora
leaden solstice
thin aurora
#

How to you handle distinct key-value pairing then?

#

I'm so confused

lost rivet
steady bobcat
#

If you want to serialize data properly use something like protobuf or bebop (not sure if its supported in unity but still)

latent latch
#

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

warm badger
leaden solstice
lost rivet
thin aurora
#

This has nothing to do with that

leaden solstice
steady bobcat
plucky inlet
steady bobcat
#

my guy wants the easy way out to json serialize a whole scene

thin aurora
#

Why not just serialize the whole game while we're at it

#

Who needs a binary executable

latent latch
#

I've a load manager specifically for each type of object I serialize

plucky inlet
#

I want a "let it go" frozen emote so bad right now 😄

thin aurora
#

Sorry, I'm just having fun at this point

hexed pecan
#

At least it's somewhat unity related

lost rivet
#

sry to bother lol

#

like do you serialize the prefabs id and then go the manager to get the og prefab?

latent latch
#

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

steady bobcat
#

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.

lost rivet
#

so i want to load in eggs, i pass an egg identifier, which goes to the eggloader?

hexed pecan
#

Eggsactly

#

Sorry i'll go now

latent latch
#

lol, yeah. You can also use interfaces like an ILoadable to implement on each type of object that can be serialized

#

IWritable, ect

azure frost
#

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...

heady iris
split junco
#

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.

plucky inlet
#

What does your ServerLoadManager do on Start?

plucky inlet
calm echo
split junco
# plucky inlet can you show that method. I guess, your quest cant connect to something your edi...

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).

plucky inlet
#

Like two debug.log on your entire start() is not logging tbh. you never check your dataPacket for example. just access its values

plucky inlet
tawny elkBOT
dusty pagoda
#

hello

rigid island
split junco
fiery stratus
split junco
#

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}");
steady bobcat
split junco
# steady bobcat A few things to check. Is get component allowed to get from inactive objects? Is...

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();
leaden ice
#

!collab

tawny elkBOT
#

: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

autumn hull
#

Thank you kind sir

split junco
#

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.

vital salmon
#

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?

split junco
plucky inlet
heady iris
#

If your game depends on a specific order, you must enforce it

steady bobcat
heady iris
#

I wonder if you could scramble the order of objects to help detect that kind of issue

vital salmon
steady bobcat
vital salmon
#

symbols?

heady iris
#

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.

steady bobcat
#

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.

vital salmon
#

ah okay ill have to figure out how to get em

steady bobcat
#

Symbols are output with a build so just upload em, the docs should explain where

#

If using mono it may not I forget

vital salmon
#

I use il2cpp

#

ill chekc it out, thanks!

plush mulch
#

Can someone tell me where in game dev would I need to use dsa intensively?

still ermine
plush mulch
#

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

cold parrot
plush mulch
#

But what type of game would it be most suitable in, tower defense? 🤔

cold parrot
#

Any game

#

it really doesn’t matter, you use all of them in practically all games

plush mulch
#

Alright I'll just pick one and look into it then

cold parrot
#

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.

plush mulch
#

Okayy thankyou

cold parrot
#

Any list is also a stack, queue is useful for message/command/action ordering

plush mulch
#

Got it, thankyou for your help

split junco
heady iris
#

you can have one object call a "setup" method on a second object, rather than using Awake or Start on both of them

split junco
# heady iris you can have one object call a "setup" method on a second object, rather than us...

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.
    }
}
fallow quartz
#

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

leaden ice
#

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

fallow quartz
kind nymph
#

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

https://paste.mod.gg/mmbknjcyfzjd

leaden ice
#

why is there a for loop here at all?

kind nymph
# leaden ice why is there a for loop here at all?

i think the way i planned for it to work is

  1. loop through the list until the current projectile name matches the index's projectile name
  2. 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

leaden ice
#

(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

kind nymph
#

the definition is public List<PlayerProjectile> projectiles = new List<PlayerProjectile>();

soft nymph
#
    {
        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

leaden ice
#

you're setting it on the SpriteRenderer component

soft nymph
#

yah I mistyped

#

thats intentional

#

I want to disable the sprite renderer

leaden ice
#

Well you're using GameObject.Find so that's a red flag immediately

soft nymph
#

oh?

leaden ice
#
  1. Is the code actually running? Use Debug.Log to find out
#
  1. Any errors in console?
soft nymph
#

yes and no

leaden ice
#

How did you verify 1

soft nymph
#

I am calling another function right above it in the same block and thats running fine

leaden ice
#

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

kind nymph
soft nymph
#

if it didnt run, wouldnt the dashing bool of animator not be false?

leaden ice
#

you are making assumptions

soft nymph
#

I did its running

leaden ice
#

and that's what leads to bugs

simple void
leaden ice
#

SOmethiung else is probably disabling the renderer

#

or you're enabling the renderer of the wrong object

kind nymph
leaden ice
#

There's only one FireEffect in the whole scene?

soft nymph
#

yes, and this is the only code the accesses it

simple void
#

Also you could write
index = ((index + step) % listcount + listcount) % listcount

leaden ice
#

How do you know there's only one

soft nymph
#

and there is only one

leaden ice
#

Search the scene at runtime

soft nymph
#

i dont think you understand

#

this whole project has 6 files

leaden ice
#

I understand completely

soft nymph
#

yep, only one fire effect

#

what did you mean by "Find" is a red flag though, is it some unity anti-pattern

leaden ice
#

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?

soft nymph
#

how so

pallid barn
simple void
#

It’s not efficient

#

You could find them in advance and cache it

soft nymph
leaden ice
# soft nymph how so

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
leaden ice
#

Is this part of the same object hierarchy this script is on?

#

Sorry thought it was GameObject.Find

#

That's a different story

soft nymph
#

yes

leaden ice
#

Can you show some screenshots of the hierarchy and which components are on which objects?

soft nymph
#

i hope im not using a global find

leaden ice
soft nymph
kind nymph
soft nymph
#

what do you want the player for? there is a lot there

pallid barn
# soft nymph

Oh wait so the sprite renderer is stating as disabled? Are you then enabling it somewhere else??

soft nymph
#

correct

#

is there another way to make sprites invisible / visible?

pallid barn
#

Where is it that you're enabling it? That could be working against you trying to disable it in your dash code

leaden ice
#

And can you show the full script

soft nymph
#

I already checked its order in layer is above all else

soft nymph
#

how else do people make sprites invisible if not disabling

leaden ice
#

something is wrong here because that works

soft nymph
#

huh

leaden ice
#

enabling and disabling is fine and works

#

so something else is going on here

soft nymph
#

im new to unity as an engine so prob some small setting

leaden ice
#

I'm still not totally convinced the code is actually running

soft nymph
#

it is.

leaden ice
#

having not seen the Debug.Log and the console

soft nymph
#

I can add it back again

#

im not sure why you dont take me at my word though

vestal arch
#

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

soft nymph
#

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

vestal arch
#

that would generally be preferable, yes

leaden ice
#

it's not a personal attack

soft nymph
vestal arch
#

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".

soft nymph
#

Ah ok found the bug

past elk
#

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

leaden ice
leaden ice
#

Can you share images/screenshots or an example of what you mean?

past elk
#

yep

#

The player is now in a tile, i want he moves to the next tile that is in front of him

fallow quartz
past elk
#

there is a tile empty gameobject to detect the tile in each tile

past elk
#

with the tag "Tile"

leaden ice
# past elk

but how do you define how they are connected?

fallow quartz
#

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

past elk
#

i dont define any connection

leaden ice
fallow quartz
#

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

plucky inlet
sturdy stump
#

Hey, is anyone able to help me with a small issue that i have?

soft shard
mild goblet
#

guys why does my GameObject spawn at its pivot point rather than its centre point

somber nacelle
#

because the pivot point is where it's transform.position is

leaden ice
mild goblet
#

okay following question. why is the pivot positioned at the bottom of my object.

leaden ice
#

is it a MeshRenderer?
A SpriteRenderer?

mild goblet
#

mesh renderer

#

i made my own mesh

leaden ice
#

Because that's where the origin/pivot of your 3D model is

mild goblet
#

okay how does one implement the origin of my mesh

#

is it the first vertex?

leaden ice
#

How do you change it you mean?

mild goblet
#

change yeah

leaden ice
leaden ice
#

but.. just google, e.g. "Change mesh origin in blender"

mild goblet
#

oooh. i made a mesh in unity. 0,0,0 was at the bottom of my mesh

leaden ice
#

You mean ProBuilder?

mild goblet
#

nah just in code

leaden ice
#

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.

mild goblet
#

thank you i'll have a play around with the vertices

spare dragon
#

does anyone know where I could find the resources to develop a multiplayer DOTS game?

fleet gorge
#

if you're familiar with unity's netcode then this will help

spare dragon
#

thanks!

spare dragon
fleet gorge
#

honestly i dont really understand how dots multiplayer would play out, it seems like a lot of data to sync

west lotus
prime lintel
#

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?

stoic orbit
#

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??

prime lintel
unborn elm
#

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

somber nacelle
somber nacelle
#

i mean, okay, but i did just answer your question so i don't see why you would need to repost it

unborn elm
#

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"

somber nacelle
#

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

unborn elm
#

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.

unborn elm
#

Was that clear? @somber nacelle

soft shard
#

I want to implement a game where I will

lost rivet
#

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

hexed pecan
#

Show the actual code

#

Or at least the class and method signatures

lost rivet
#

only the names are different though, signatures are the same (its a simple script)

hexed pecan
#

Did you add the override modifier to the method in the child class?

lost rivet
#

yes

#

is this not supposed to happen? i was wondering if it was a c# thing

hexed pecan
#

This should call the overridden method, so you are doing something wrong

lost rivet
#

wait

#

when i call it inside a for loop it doesnt work, but in a foreach one it does huhhhh?

hexed pecan
#

Nobody can help without code

still jungle
thin aurora
#

One reason whyt his might happen is when you use the new keyword in a method signature. You should not be using this.

rustic ember
#
            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?
rustic ember
#

GetPointAlongToolAxis() returns Vector3.negativeInfinity;

leaden ice
#

If you assign an object's position to infinity, that will be a problem.

rustic ember
#

In the If statement

plucky inlet
vestal arch
hexed pecan
plucky inlet
vestal arch
#

not really, no

plucky inlet
#

Another conversation not really related to this I guess 😄

vestal arch
#

but definitely not helpful to the situation

hexed pecan
#

@rustic ember Ah nvm just saw you logging it before you use those

leaden ice
hexed pecan
#

Unity overrides Vector3 == operator, not sure if it works with infinity values

rustic ember
#

Hmm... 🤔

leaden ice
#

nvm just saw that lol

rustic ember
#

Ahah

vestal arch
#
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;
}
hexed pecan
vestal arch
#

im pretty sure that results in a bunch of NaN

#

so yes the comparison would not work

leaden ice
#

Yeah here's the problem

#

return sqrmag < kEpsilon * kEpsilon;

#

is not going to work properly for infinity

hexed pecan
#

Equals probably works

vestal arch
#

any difference of infinities would result in NaN

hexed pecan
#

It just compares x y and z with ==

vestal arch
#

oh, so that's what the difference between those 2 are

rustic ember
#

"// Returns false in the presence of NaN values." Is infinity a NaN value? Or just a really high value?

plucky inlet
#

you could compare your values to mathf.infinity tho and then clamp them to 0 for example

hexed pecan
vestal arch
#

@rustic ember are you aware with floating-point values as a concept?

rustic ember
#

What if it was positive infinity instead?

plucky inlet
vestal arch
leaden ice
rustic ember
plucky inlet
#

Infinity is not defined, so no value to substract from the "no value" infinity

vestal arch
plucky inlet
rustic ember
#

But I could use Vector3.one * 1000000?

leaden ice
rustic ember
#

B-but... But math?

leaden ice
vestal arch
# rustic ember That makes no sense to me. It should be 0 right?

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

leaden ice
#

It's not 0 even if you had perfect floating points

vestal arch
#

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

rustic ember
leaden ice
#

use a magic value to represent something?

#

Why don't you use Vector3? (nullable)

vestal arch
hexed pecan
#

Both ways are valid IMO

vestal arch
#

this isn't math

#

this is an approximation of math for computers to use

#

see IEEE 754

rustic ember
#

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
rustic ember
vestal arch
leaden ice
rustic ember
#

I could just return null

plucky inlet
#

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

vestal arch
plucky inlet
#

So thats what you could do to check if its infinity

vestal arch
leaden ice
# rustic ember Right!
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^

plucky inlet
vestal arch
prime lintel
#

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.

plucky inlet
vestal arch
prime lintel
# plucky inlet Where do you set the instance? And why are you setting booleans of another class...

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);
    }
}
prime lintel
#

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?

plucky inlet
prime lintel
plucky inlet
#

your InstanceManager is instantiated?

prime lintel
prime lintel
plucky inlet
#

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.

prime lintel
#

Okay, I'll try that. Thank you

prime lintel
plucky inlet
#

You rather have some kind of UI Manager reacting to for example gamemanager states or user inputs and what not

prime quarry
#

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?

placid summit
#

async tasks in Unity continue after play mode has stopped... notlikethis

#

I think I need UniTask...?! Which avoids such things by default?

placid summit
tired elk
placid summit
#

Do async tasks end on closing a .Net app, is this some unity issue? What would be a reason to allow tasks to continue?

chilly surge
#

Your editor isn't closed when you exit play mode.

placid summit
craggy veldt
#

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

chilly surge
thin aurora
craggy veldt
#

it doesnt, thats why they give us MonoBehaviour.destroyCancellationToken

thin aurora
#

So if you combine your cancellation tokens with this (assuming you use them), you can cancel running Task instances

#

@placid summit ☝️

chilly surge
#

I will continue to recommend UniTask 😄

thin aurora
#

What does UniTask have to do with cancelling the Task? Does it do it automatically?

craggy veldt
#

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

leaden solstice
#

Is PlayerLoop still undocumented

thin aurora
#

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

placid summit
#

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

cold parrot
craggy veldt
thin aurora
#

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

cold parrot
#

if you do anything with tasks, unitask is not overkill, regular tasks in unity have so many gotchas you need to know about

leaden solstice
#

Awaitable is meh

thin aurora
#

Ah, I wasn't aware of that.

#

It seemed pretty well thought out

cold parrot
#

it (UniTask) is one of those packages made by someone with extensive experience with real world problems they wanted solved

craggy veldt
#

not sure what that means, but Awaitable is quite lacking of useful methods like what regular Tasks has

#

Unitask covers most of those

placid summit
#

Awaitable does exit at end of play mode?!

cold parrot
#

its best to not rely on it and always pass a onDestroyCancellationToken that every component has

placid summit
cold parrot
#

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

steady bobcat
#

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)

craggy veldt
steady bobcat
#

you cant leak program owned memory when the process terminates...

latent latch
#

So everyone still using Unitask? Havent looked into awaitables yet

#

not that any of this stuff works for webgl :(

steady bobcat
#

must be a webasm limitation and well js "threads" are a joke

chilly surge
#

JS is fully capable of multi threading.

latent latch
#

but hey, I'm blowing up peoples GPUs overhere

chilly surge
thin aurora
#

It's the main way to stop asynchronous Tasks from running gracefully

#

Or not gracefully, that's also possible 😄

latent latch
placid summit
#

awaitable does not have Forget() so... seems annoying. How should an Awaitable be triggered from a synchronous function to avoid warning?

wheat spruce
#

There are that many browsers?

vestal arch
#

and devices
probably multiplying the 2

craggy veldt
wheat spruce
#

1998 devices
Firefox,
Chrome

thin aurora
#

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);
calm echo
# placid summit awaitable does not have Forget() so... seems annoying. How should an Awaitable b...
    {
        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
        }```
thin aurora
#

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

steady bobcat
#

you can do #if DEBUG (which is true for editor and dev builds)

thin aurora
#

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

calm echo
placid summit
#

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

steady bobcat
#

you mean it doesnt print them in the console

thin aurora
#

I was specifically talking about them being printed in the console in any way

#

I didn't say Unity would catch them

calm echo
#

yeah i mean they are silent

#

they wont be in the consle

thin aurora
#

I assume Unity would have something similar for this

calm echo
#

thats why you wrap your fire and forget in a try catch in debug scenarios

thin aurora
#

Yeah but your log is not gonna help much in production

calm echo
#

or else the errors will go completly silent in the background

thin aurora
#

But you're right, at least silent exceptions are not the case

vestal arch
thin aurora
#

Or do Awaitables also hook on this?

calm echo
#

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

cold parrot
#

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);
                }
            });
        }
    }
}
chilly surge
craggy veldt
thin aurora
#

Again idk if Unity works as good with this and/or if it has an alternative. Would love to know if it does

latent latch
#

As it seems, they're more focus with WebGPU at the moment and completely abandoning any threaded support it seems

latent latch
#

Which works great^

calm echo
#

WebGl is kinda dead

chilly surge
#

The conversation started on JS multithreading and now seemingly it has moved to WebGL/WebGPU?

latent latch
#

The dicussion was about awaitables and unitask not working with WebGL

#

because at the moment there is no async operations

chilly surge
#

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.

latent latch
chilly surge
#

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.

latent latch
#

I'm just saying. If it was that easy to implement, you'd think Unity's team working with WebGL would be on it

cold parrot
latent latch
#

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

chilly surge
#

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.

steady bobcat
#

does unity use webasm or js for user code cus im not really sure?

chilly surge
#

That doesn't matter because WASM and JS can interop.

#

WASM cannot even run without a bit of bootstrap JS.

cyan mortar
#

How to implement mountable vehicles and mountable animals

steady bobcat
#

mountable WHAT

placid summit
#

ridable?

cyan mortar
#

yeah, ridable

#

poor choice of words?

wheat spruce
#

mountable isnt a bad word

#

oh wait I just read the last part of the thread name 😆

#

off to jail you go

prime quarry
unkempt swallow
#

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

rigid island
prime lintel
#

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);
        }
    }
}
rigid island
#

you can't shortcut your way through knowledge

rigid island
prime lintel
unkempt swallow
prime lintel
rigid island
#

doubt input system is related to this

prime lintel
rigid island
#

also not entirely sure if UIToolkit needs the Event System for the new Input Module to work , double check that too

rigid island
unkempt swallow
#

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

vestal arch
#

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

rigid island
still jungle
#

it does good for sources lookup with web option, but generated prompt is falsy true in most of cases of advanced questions

unkempt swallow
# vestal arch it's not a replacement for experience

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

vestal arch
#

thats why im asking if there are more advanced solutions , specifically for programming related questions
with AI? no

unkempt swallow
vestal arch
#

just not really how AI works

latent latch
#

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

vestal arch
unkempt swallow
vestal arch
#

gpt isn't special; none of the chatbots are special

unkempt swallow
vestal arch
#

there is no reliable ai

rigid island
#

pattern matching is not intelligence

latent latch
#

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

vestal arch
unkempt swallow
# vestal arch there is no reliable ai

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 ThumbsUp i dont keep close eyes on gpt development etc

still jungle
#

google search is usless nowadays

latent latch
#

google has been useless since people started gaming the alg and all those "Top ten" blogs started to spam the top results

unkempt swallow
#

pseudointellectuals everywhere you go

rigid island
#

huh triggered telling someone to build up knowledge, projection at its max

vestal arch
#

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

unkempt swallow
vestal arch
#

that's LLMs in general

unkempt swallow
#

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

chilly surge
#

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.

unkempt swallow
#

really sad

chilly surge
#

I don't need correctness from a dice.

latent latch
vestal arch
unkempt swallow
# chilly surge I don't need correctness from a dice.

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

vestal arch
#

same thing with crypto and blockchain and nfts, see all the scams the past few years where they never actually took off

still jungle
vestal arch
unkempt swallow
#

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

vestal arch
# latent latch

that's hilarious compared to youtube putting suicide help lines on videos that say something tangentially related once lmao

unkempt swallow
#

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);
    }
vestal arch
#

i guess like, 100 - rarity, as the weight, rather

unkempt swallow
#

using a weight of 5 works fine, but the lower values are like i said, not as spread as i want

vestal arch
#

oh hold on

chilly surge
# unkempt swallow never looked at it that way but youre right yeah, i used to use gpt in the early...

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."

vestal arch
#

what's the input/output?

#

i thought you meant rarity (0-100) input, and then a yes/no or a selection output

unkempt swallow
#

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

vestal arch
#

ah ok

heady iris
#

are we talking about ✨ distributions ✨ ?

vestal arch
#

so are you just kinda, mapping the randomvalue from 0-1 to 0-100 with a bias towards lower numbers?

latent latch
vestal arch
#

gotta find a pdf for this then lol

latent latch
#

mackysoft always got the goods

heady iris
vestal arch
#

ah, true

heady iris
#

well, an inverse cdf

vestal arch
#

but a pdf would be more easily mappable to code wouldn't it

heady iris
#

An inverse cumulative distribution function lets you sample a uniform random value and then compute a value from the distribution

chilly surge
#

The simplest system would just be defining a list of all possible outcomes and their weights.

heady iris
heady iris
#

Also, you can get pretty far by doing very basic reshaping of a uniform distribution

unkempt swallow
#

yeah i could yanderedev this but i thought about having a fancy rarity function i might use again for sth else

heady iris
#

For example:

float BiasedRandom() {
  return Mathf.Pow(Random.value, 2);
}
#

This gives you more small numbers

chilly surge
#

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.

heady iris
#

sometimes it is most practical to just enumerate every outcome

unkempt swallow
#

then i missunderstood, but how would you do that for values 1 to 1000 ?

#

hard code a weight for each value? thats madness

latent latch
#

That mackysoft has a nice overview on the search algs with some graphs for different search algs

heady iris
#

do you need 1000 values?

vestal arch
unkempt swallow
latent latch
#

enuemrate is probably fine

chilly surge
#

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.

vestal arch
#

wow i have no idea what i'm doing

unkempt swallow
vestal arch
#

this would be a cdf, right? @heady iris

unkempt swallow
#

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

chilly surge
#

You still need to define "very rare"

heady iris
vestal arch
#

wouldn't it be a pdf if the integral was 1

heady iris
#

it should reach 1 (:

vestal arch
#

ah, of course

latent latch
chilly surge
# unkempt swallow fish have a weight float, which i want to be between 1 and lets say 10000

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?

vestal arch
#

does that make sense (asking fen)

#

oh this is the inverse cdf you mentioned, right?

heady iris
#

Perhaps you have the opposite question

unkempt swallow
heady iris
#

"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

chilly surge
heady iris
#

you can choose whatever range you want

unkempt swallow
heady iris
#

why do you need 10000 different rarity values?

vestal arch
heady iris
#

you've gotten obsessed with specific large numbers here

unkempt swallow
#

i think you guys are getting confused by weights and weights of the fish as in kg

chilly surge
#

You are too hyper focused on the arbitrary number of 10000, where you can't even define what "10000" means.

heady iris
#

no, we know what's being described

unkempt swallow
#

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

vestal arch
#

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

latent latch
#

if there's not rarity then that would change the problem completely

unkempt swallow
#

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

heady iris
#

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)

unkempt swallow
#

wdym with normal distribution ? i dont understand

polar marten
vestal arch
chilly surge
vestal arch
#

wow, thanks for the embed, wikipedia

vestal arch
unkempt swallow
#

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

heady iris
chilly surge
unkempt swallow
heady iris
#

The "secret sauce" here is the function that maps from a uniformly random value to the normal distribution.

vestal arch
chilly surge
#

You don't need a specific curve, literally any differentiable curve will work.

vestal arch
unkempt swallow
#

i would rate myself in Math with an D

#

ill be fine with keywords i can google and research

vestal arch
#

but there's so many levels of math that the rating is almost meaningless lmao

polar marten
vestal arch
#

anyways you'll probably want to figure out how distributions work

polar marten
#

don't worry about the math. use a library

latent latch
#

there's plenty of these algs laying around, especially related to games since it's a pretty common problem

polar marten
#

ah

heady iris
#

and I don't have to!

polar marten
unkempt swallow
#

is there a magical place for them or do you guys have a secret to not get shitty google results

heady iris
#

iirc it's an approximation of the inverse CDF -- which I believe there is no analytic form for

polar marten
#

google search is "unity random distributions library github"

unkempt swallow
#

if not shitty, half the results are malicious ads

polar marten
#

there are lots of options

vestal arch
unkempt swallow
vestal arch
#

wow that article lists so little

polar marten
chilly surge
polar marten
#

there is no general calculation for a normal distribution which is why nobody teaches it.

latent latch
#

that repository is basically what fen linked

chilly surge
#

Replace from 0 to max with from min to max and you can expand it to any range including infinity.

polar marten
#

there's no analytic inverse cdf for gaussian

polar marten
#

in games you never want gaussian

#

you want lognormal, bernoulli, and hypergeometric

unkempt swallow
#

this is what i wanted in code form but able to adjust the curve to my liking

polar marten
#

the thing i linked has exponential

vestal arch
#

im pretty sure that's not exponential

polar marten
#

🥺

#

i know a lot about this guys

vestal arch
#

it wouldn't asymtoted on both axes, no?

polar marten
#

he doesn't know what he wants

#

i'm trying to give him the answer in light of that

unkempt swallow
magic tusk
#

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...

vestal arch
chilly surge
polar marten
#

that's what it is

chilly surge
vestal arch
polar marten
#

massive plead emoji

latent latch
#

can always just integrate python and use some numpy

polar marten
vestal arch
#

like im confused what you're trying to say here

polar marten
#

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

vestal arch
#

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

unkempt swallow
#

having high weight(KG) = better

polar marten
#

do you know what that is?

unkempt swallow
#

no pity

#

just harsh randomness (weighted)

latent latch
#

really if there's not catagorizing it's just a curve you throw a dice at

polar marten
#

common, uncommon, rare, "legendary" kind of has some player expectations to it. is that important to you?

unkempt swallow
#

no

polar marten
#

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.

latent latch
#

probably can just use an animation curve honestly

heady iris
#

that's a pretty good idea, actually

#

just make a curve that looks good

polar marten
#

no guys

#

it doesn't work that way

chilly surge
small linden
#

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?

polar marten
#

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)

vestal arch
#

uhh i think you mightve misread what mao said

polar marten
#

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

chilly surge
#

The solution I've given literally works for any curve, they can change the curve however they like until it feels good.

polar marten
#

you can also refill the deck after you draw if you want it to be "harsh"

vestal arch
#

i think with the lack of confidence in math kinami has, the animation curve would be a viable option shrugsinjapanese

polar marten
#

the curve doesn't mean what you think it means

unkempt swallow
#

im checking all solutions offered, rn using the linked github repo and the radnomexpo, but the values are 1.004811 like, nothing above 1

vestal arch
polar marten
#

like most of the time

small linden
unkempt swallow
polar marten
#

the one that you should "expect" to get
rate = 1 / expectation

polar marten
#

so 10kg?

#

so the rate you want is 1/10.0

unkempt swallow
#

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

vestal arch
#

do you know what a mean is

unkempt swallow
#

no

unkempt swallow
polar marten
#

haha

vestal arch
#

if you fished 100 times, what should the average be

polar marten
#

i think you are learning it's okay

vestal arch
polar marten
#

🥺

vestal arch
#

that isn't in the realm of statistics anymore

unkempt swallow
#

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...

vestal arch
#

depends, really