#archived-code-advanced

1 messages · Page 116 of 1

tough stream
#

see i know i can secure the endpoint (not how though, docs are very unclear)

#

but everything has to be done through unity authentication service which is done on the client

compact ingot
tough stream
#

can i have multiple keys with different permissions?

#

i was under the impression that being authenticated was your "key"

compact ingot
#

Most certainly

#

Keys are per player, org, game whatever, you can set permissions what a key can access

#

It would be the most pointless API ever without that

tough stream
#

yeah i just dont see any sort of key management dashboard

#

service accounts look promising

#

ohh wait

#

ahhhh i see

#

so the server instance would authenticate as a service account

#

to give the player currency

#

wait no

compact ingot
#

all these APIs (incl. playfab) use such a pattern. Server runs on a privileged account/key, players on a personal account/key

tough stream
#

service accounts are for changing settings programatically

#

yeah nvm im back to being confused

#

i cant find anything to control what the player can an cant do

compact ingot
#

Usually account management is a whole separate service

bleak citrus
#

The Economy service allows the game client to retrieve and modify a player's economy resources in the cloud.

the docs do imply the player should be allowed to modify their own resources 😂

tough stream
#

yup

#

but it seems like theres no dashboard for this, just a bare api

compact ingot
#

i think in this context "game" is the entire live service, and each instance of your unity client is a "client" including the server

tough stream
#

and definitely no key systme

#

its more like an all or nothing "is this available yes or no"

compact ingot
#

you gotta set up those policies yourself

#

there is a Economy admin API, which is a resource you can restrict in a policy

tough stream
#

i could definitely keep using multiplay and just self host an sql database or something for player data

#

seems a lot less convoluted than this

#

my biggest concern is fucking something up since theres no dashboard to manage this

scenic forge
#

Never used something like this, but if there's no server, what stops a malicious client just take its own key and give itself infinite currency?

compact ingot
#

there is a role called "Economy Resource Editor"

scenic forge
#

I take that as you can limit what a key can and cannot do, in which case what stops a malicious client that spams something its key can do?

bleak citrus
#

presumably the game client would only be allowed to read currency values, and anything involving writing them would be done by the game server

compact ingot
#

it would be ridiculous if that werent possible, the core of any managed cloud services is the account/premission management

scenic forge
#

But isn't the whole point that there is no need for a game server, or am I mistaken?

compact ingot
#

there always is a server, the point is that the runtime server for matches is not the same as the backend that stores persistent player data

scenic forge
#

Ah, so it's basically selling you a storage solution with permissions and what not, you still have to build your own server side logic.

compact ingot
#

no

#

the account management service gives you an API to set permission, per user/role on resources (other service APIs) that are offered

#

these other services implement features like advertising, matchmaking, provisioning of runtime servers and in this case, microtransactions and persistent player inventory

#

at the very least these services have a "view" and a "admin" permission set.

#

usually, on the client, you make a request to a public API, /set/money/USER-ID/10000000?auth=MYTOKEN

#

and if that token doesn't have permission, the money wont be set

#

its usually more complicated than than, not through a sniffable token, but in essence thats what happens

scenic forge
#

Sure, then how would you implement something like "player passes a level and should be rewarded some currency"?

compact ingot
#

the runtime server has a priviledged token that can give the currecny to the player

#

that server obviously has to be 'trusted'

bleak citrus
#

the Economy API is basically just a counter (for currency) and a list (for items)

compact ingot
#

+permission on who can change what counter

#

all these backends are supremely trivial in what they do for a game

scenic forge
#

Where do you write the code for the runtime server, is it a separate Unity project?

compact ingot
#

which leads many to DIY these things, until they figure out that the permissions, security, availability, scaling bit is not so trivial and boring AF

bleak citrus
compact ingot
scenic forge
#

Interesting architecture.

compact ingot
#

thats basically how all live services work

#

i think its one of those 'aha' things to realize that your unity-server-app is just one component in the context of an entire multiplayer/online/live-service game

bleak citrus
#

I guess you can think of it as different levels of trust and persistence

#

The game client is very non-persistent. I can shoot my computer with a gun whenever I want to (or turn it off, I guess)

#

It's also very non-trusted

#

Servers that run game instances are trusted, but not very persistent

#

And then you have a backend that's trusted and persistent

#

Unity is providing that backend here

scenic forge
#

Not the front and backend distinction, but that if I was to build something like that I wouldn't go "oh yeah my backend is also a Unity project" I'd just have it a regular web backend or whatever.

bleak citrus
#

oh yeah

#

I've thought about that (slightly)

scenic forge
#

I suppose for cases where the backend does need to have more context about the game, it would enable logic sharing.

compact ingot
#

ofc your persistence is just a http API there is no point in making that a unity app

bleak citrus
#

Make sure you're distinguishing the game servers from the rest of your infrastructure here

#

The game servers are much more likely to be an actual Unity application :p

#

(but they don't have to be -- you can do all of your server logic however you want, and then present the results to the player in a Unity game)

compact ingot
#

you can make your game server in node, and die a slow painful death of realization

#

nothing is as glorious as doing a competitive multiplayer game with json messages over HTTP

bleak citrus
#

putting the lag in lag compensation

compact ingot
#

it also murders your bandwidth

#

thats the next realization, its not O(N), its O(N*N+1) for each message

bleak citrus
#

presumably you would use something less obviously unfitting, like WebSockets

scenic forge
#

I mean, it's not like Node.js is incapable of doing anything other than JSON over HTTP, but I digress.

compact ingot
#

the one who picks node for this problem likely is not aware of that

#

i find node usually gets picked because the team isn't comfortable with any other server tech.

#

usually there is also a lack of awareness what it even means to do realtime networking

scenic forge
#

Presumably you are not locked to using Unity Netcode for your server to talk to Unity Services, right?

compact ingot
#

i think you mostly are~

#

you at least need to use unity transport if you want to use the relay service

#

don't think there is anything else to unity netcode that would be required

scenic forge
#

Yeah looking at the Unity Services docs, seems like things are documented and have OpenAPI specs so you can just plug that into whatever.

tough stream
#

this is what i mean by it feels half assed btw

#

u cant even pass a player id to any of the economy methods

#

u have to bang rocks together with raw api requests

bleak citrus
#

Increments the balance of the specified currency for the currently logged in user.

Man this really does feel like they want to let the game client directly set currency values

tough stream
#

yup

long ivy
#

that's more like the pattern I'd expect to see: client code calls cloud functions, cloud functions do the currency stuff

bleak citrus
#

ah, and I wonder if the cloud code gets the "context" of the client that caused it to run

tough stream
bleak citrus
#

how so?

#

(thought: how "how so?" is just a posh version of "wdym")

compact ingot
#

The more the API does on its own the less you can use it to your own ends. Economy is not supposed to do anything. It’s just a database of raw values that you assign meaning to in your game

bleak citrus
#

yeah, it's conceptually just:

  • some counters
  • a list
#

that's it, really

compact ingot
#

What it provides is reliability

#

So people trust your game, and items bought for real money or by spending time in the game don’t get lost because you thought you can DIY it all.

compact ingot
bleak citrus
#

my game is about a list of things

#

some of the things remove other things from the list

compact ingot
#

Yeah

bleak citrus
#

and they're all called "entities"

#

how vague!

compact ingot
#

I call them props (like props in a play)

bleak citrus
#

my props are entities

#

they just don't do much thinking

#

unlike the player entity, that thinks a lot

tough stream
#

so, it really seems like theres nothing stopping someone from spoofing their player id to play as someone else

#

the unity staff on the forums just say "send the player id to the server"

#

after authenticating

plush hare
#

look into steamworks.

#

If you wanted to manage your own system, you'd have to keep track of purchases & user accounts, and somehow have the client send a short-lived web-server-generated token when he wants to connect to a game server.

#

If the game servers are 3rd party hosted, they'll have to contact your backend master authentication server and verify that short-lived token. It needs to be short-lived to prevent other players pretending to be other players, if the token ever got leaked somehow.

#

also don't ever send usernames/emails & passwords to game servers as authentication. bad idea. always use a token.

tough stream
#

i use steamworks

#

and what i said still applied

#

but i was wrong on the approach

#

the correct way to do it is to send both the player id and the auth token

#

and use the get player api endpoint to verify that they match

#

on the server

#

i just send the player id and auth token via an rpc and encrypt with rsa just in case bc i dont know the specifics of how rpcs are secured and such

#

and once this is done, the server has the player's id

#

and i authenticate the server as a service account

#

so i can interact with things like the economy api

#

achieving what i was originally trying to do (server authoritative player data management)

#

now to waste my time writing an abstraction layer on this since unity couldnt be bothered to

regal olive
#

Can i use steamwork api if the app isn't installed from steam?

#

I wonder if i can use steamwork api for android version of the app

stuck plinth
untold moth
regal olive
regal olive
untold moth
regal olive
#

That doesnt sound like something that is legal

untold moth
regal olive
untold moth
regal olive
untold moth
#

Anyone can read that. It's in English. And it's better than asking random strangers online about issues that can potentially get you into legal troubles.

stuck plinth
# regal olive I need the matchmaking system so that player can play multiplayer with steam

steam matchmaking requires the players to be playing on steam accounts which you obviously can't do without steam, you can implement cross multiplayer by other means (there's better options but valve even offers their networking code as a cross platform library) but the matchmaking part will need to be a platform-independent service if you want it cross platform

shadow nebula
#

I have a list of scriptable objects in an Authoring script and I want that to bake a similar list with entities in my component. My Component has public Entity[] EnemyPrefabsToSpawn; and the authoring has:

       AddComponent(enemySpawnerEntity, new EnemySpawnerComponent
       {
           EnemyPrefabsToSpawn = ConvertToEntities(authoring.Enemies),
/// ....
       });
    }

    private Entity[] ConvertToEntities(Enemy_SO[] prefabs)
    {
        Entity[] entities = new Entity[prefabs.Length];
        for (int i = 0; i < prefabs.Length; ++i)
        {
            entities[i] = GetEntity(prefabs[i].prefab, TransformUsageFlags.None);
        }
        return entities;
    }

But I get "The type 'EnemySpawnerComponent' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent<T>(Entity, in T)'CS8377"

bleak citrus
#

and what is EnemySpawnerComponent?

shadow nebula
#

I holds my enemy spwan wave information: ```cs
public struct EnemySpawnerComponent : IComponentData
{
public Entity[] EnemyPrefabsToSpawn;
public int NumOfEnemiesToSpawnPerSecond;
public int NumOfEnemiesToSpawnIncrementAmount;
public int MaxNumOfEnemiesToSpawnPerSecond;
public float EnemySpawnRadius;
public float MinimumDistanceFromPlayer;

public float TimeBeforeNextSpawn;
public float CurrentTimeBeforeNextSpawn;

}

#

Would it be more idiomatic to have multiple monsterInfo components in the spawner, that I iterate through with the monster info and prefabs?

bleak citrus
#

Entity[] is not a non-nullable value type

#

That is why you're having problems here

#

I believe you need to create a "blob" here

#

It's been a hot minute since I worked on Entities

#

But I had a somewhat similar situation -- I was creating spawner data and needed to encode a variable number of "rules" for each of my tiles (I was doing wave function collapse)

#

If you have a Foo[] in your authoring data, you'll create a BlobBuilderArray<Foo> with a size equal to the length of that array

shadow nebula
#

Okay, thanks. I'll look into blobs. Have not done anything with blobs yet, so that's a new thing

bleak citrus
#

The idea is that a blob has an exact size for everything

#

exactly 17 things to spawn, for example

crisp meteor
#

Hello, I have a save-load system. It is possible to save and load object information as well as animation data for objects with animations (such as layers, parameters, current state, clip time, and clip name). However, after the scene is loaded, the current animation state starts playing again, which causes animation events to be triggered and executed.

How can I prevent the animation from playing upon scene load? My current system does not save the duration of completed animations, so I cannot adjust the animation's timing. I would greatly appreciate your help.

slow jay
sly grove
#

Have you considered running it through ILSpy or something similar?

maiden zodiac
#

Hi i am stuck in the code can anyone help me ?

The task is to move the car and avoid any obstacles and follow the path

misty glade
swift spear
#

Is there any way to load scene additively with no spike?

bleak citrus
#

profile your game to see what's taking up the time -- but it's always going to take at least a moment to create all of the objects, even when loading the scene asynchronously

fallow echo
# swift spear Is there any way to load scene additively with no spike?

We're currently trying to do something about that at work! The plan is to have a custom Awake method on pretty much everything, then execute that manually over multiple frames following execution order rules, and only then activating the scene, which should be better as there would be no Awakes.

sly grove
bleak citrus
#

My main problem has actually been scene unloading

#

It causes a very long GC pause

sage radish
proud pumice
#

Does anyone know a tutorial to a good wave spawner system?

raven bolt
#

Question on file saving and serialization. Currently my solution is text based, but I am having some mental block organizing classes. As it stands I have 2: a Serializer that just writes and reads from disk and a DataHandler that parses the data and converts it to more strongly typed internal datatypes.

Should these classes be static (the Serializer currently isnt) and am I way overthinking this?

fallow echo
#

Are you using an existing serializer like JsonSerializer? If not - why not?

sly grove
# raven bolt Question on file saving and serialization. Currently my solution is text based, ...

You want:

  1. Some kind of manager for handling save files and/or profiles (if your game has them)
  2. An internal strongly typed data model for representing the game state
  3. A serializer that can serialize and deserialize the data model in #2

The save manager should be responsible for (when saving the game):

  • invoking the serializer to serialize the current game state into text
  • Saving the text to a save file
    And when loading the game:
  • Reading the save data text from a file
  • Invoking the deserializer to convert the text to your internal model
  • Rebuilding the scene based on that model.
#

You can and should use an off-the-shelf serializer rather than writing your own from scratch usually

raven bolt
sly grove
# raven bolt I already wrote mine, but im more concerned with whether the two branches (deali...

B is really vague as to be almost meaningless. Should what be static?

A. Should what be split into separate classes? Are you asking if you should have a separate DTO for saving vs the class you use in the actual game? I would avoid that if at all possible because it's generally unecessary complexity and maintenance. If you can use the same class for storage and at runtime, that's ideal. There's usually a pre-save and/or post-load pass you can/should do to the data if you need to set up certain runtime references.

raven bolt
sly grove
#

Almost nothing in this process should be static generally except perhaps a static singleton reference variable for the data manager.

raven bolt
raven bolt
sly grove
#

Static variables are generally bad because you are forced to manually manage their entire lifecycle

#

If you return to the main menu in your game, you have to remember to reset your static variables, for erxample

sly grove
upbeat path
#

why would you use statics in a save/load system. one they are allocated they are there for the life of the domain so why have a Load system which exists for the entire runtime?

sly grove
#

Generally serializer entry points are static

raven bolt
# sly grove What's your reason for using static?

the class needs no reference other than its helper functions, can be accessed by other classes in my codebases core namespace and persist across the entire runtime of the application and will only ever exist once.

THe design of my game calls for a single scene with no reloading. Data is loaded and objects are created/discarded rather than scenes

sly grove
#

such as JsonUtility.ToJson

icy field
#

is there any way to have a render texture that renders a cameras view but only with 1 material? i want to have a hologram of the map with everything having a hologram material (urp)

raven bolt
raven bolt
sly grove
icy field
fallow echo
icy field
raven bolt
sly grove
#

but if you ever add another scene you'll have some refactoring to do

#

The only thing you're gaining really is not having to add a singleton to the scene

#

If it's totally stateless, just use a static class, sure

raven bolt
#

gotcha thanks. I guess i did overthink it. Most of my projects are procedurally/dynamically loaded so i have fallen into a single scene design

viral edge
#

Anyone familiar with the Item Services portion of Steamworks? Currently working on items, have the json def file setup, have code to GenerateItems for developer accounts but cannot for the life of me get the TriggerItemDrop function to return anything other than a zero item success even though I'm using the correct playtimegenerator item and bundles. Doesn't seem to be any info out there.

vital fossil
#

Respected Seniors, I have some confusion about the Google Play Services in the Unity game.
Please guide me when it will be easily possible for you.

1- Does authentication to Google Play Services occur only once per session, or does it persist throughout the game until the user removes the game from the background or quits the game?

2- For read/write operations (e.g., saving data to Google Play Games), is one-time initialization sufficient until the user removes the game from the background or quits the game?

3- If the user's internet is off, can data be saved locally and synced later automatically? Does Google Play Services handle this process on its own?

4- When enabling Google Play Services in the game, will users receive a notification about it on their device to successfully connect to Play Services, or is there any other way they are informed?

5- If I want to integrate Google Play Services, is a Google Developer Console account sufficient, or do I also need an account on Unity or any other platform? Could you kindly clarify this process for me?

6- Or any important tip for me to implement it.
Thank you

slow jay
#

does the profiler by default only show Unity's methods like Camera.Render and Transform.SetParent, instead of the game's methods?

icy field
#

thank you

#

gonna try it out later

little solar
somber swift
little solar
#

@somber swift how do i make sure its public?

little solar
#

i have a parkour game but my character keeps flying into the celing

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f; // Speed of player movement
public float jumpForce = 5f; // Force applied when jumping

private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
    rb.useGravity = true; // Ensure Unity's gravity is applied
}

void Update()
{
    Move();

    if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
    {
        Jump();
    }
}

void Move()
{
    float moveX = Input.GetAxis("Horizontal");
    float moveZ = Input.GetAxis("Vertical");

    Vector3 moveDirection = new Vector3(moveX, 0, moveZ).normalized;

    Vector3 moveVelocity = moveDirection * moveSpeed;
    rb.linearVelocity = new Vector3(moveVelocity.x, rb.linearVelocity.y, moveVelocity.z);
}

void Jump()
{
    rb.linearVelocity = new Vector3(rb.linearVelocity.x, jumpForce, rb.linearVelocity.z);
}

bool IsGrounded()
{
    // Check for grounding to prevent floating or upward dragging
    return Physics.Raycast(transform.position, Vector3.down, 1.1f);
}

void FixedUpdate()
{
    // Extra safeguard to force Rigidbody's velocity in case of erratic behavior
    if (rb.linearVelocity.y > 0 && !Input.GetKey(KeyCode.Space))
    {
        rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
    }
}

}

devout hare
little solar
#

srry

slow jay
#

if I run my game on meta quest 3, the process has 14gb virtual memory. Does that mean that my game can use 14gb of memory before it crashes?

sly grove
#

that means it's using 14gb of memory now

#

but part of it may have been written to disk and offloaded from RAM

#

virtual memory is basically when the OS writes part of the memory of the program to your SSD or HDD instead of leaving it in RAM to save on RAM, at the cost of having to read/write it to and from disk at some point.

slow jay
#

like this output from top command:

Tasks: 1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
  Mem:  7944432K total,  7679704K used,   264728K free,     1784K buffers
 Swap:  4718584K total,   748108K used,  3970476K free,   869144K cached
600%cpu   5%user   1%nice   6%sys 585%idle   0%iow   2%irq   0%sirq   0%host
  PID USER         PR  NI VIRT  RES  SHR S[%CPU] %MEM     TIME+ ARGS
14018 u0_a81       20   0  16G 3.8G 185M S  1.0  50.2   2:37.51 com.Icosa.OpenBrushPR795

VIRT is 16G

slow jay
#

but in the above, is 16G the max virtual memory we can use or what we're using right now?

sly grove
#

RES is the resident memory aka how much RAM it's using right now

#

but the process thinks it's using 16GB

#

and has 16GB worth of addressable data in memory according to itself

#

some 12GB have been swapped onto disk

#

16gb is the amount of virtual memory it's using right now

slow jay
#

ok thanksfor the clarification

#

when you get memory errors like "out of memory", is that mainly done by the OS or the unity engine? I guess the OS will kill the process if there's no memory anymore, but does the Unity engine also try to prevent the player from asking too much memory?

dusty wigeon
wary thistle
#

(I am also using it to train an AI to drive with ML-Agents. That is what a lot of the original functions are.)

lament salmon
whole mountain
#

Does anyone know how to make only the tiles from a tileset turn transparent when the player is behind them? I want to ensure that only the specific walls obstructing the player's view become transparent, not the entire tileset.

slow jay
#

if I await something in Unity, is it handled by the UnitySynchronizationContext? ie it'll put the task on the queue and periodically run it

#

and Coroutines aren't handled by UnitySynchronizationContext?

sly grove
slow jay
#

im wondering if UnitySynchronizationContext will make sure that LongTask() gets executed periodically

bleak citrus
#

Not at all.

#

well...

#

okay, you didn't await Main2()

#

tbh I'd just try it and see. I have a bit of a weak grasp on the intricacies here

slow jay
#

sry i forgot the await

bleak citrus
#

In that case, Main() would park itself there until Main2() completed

slow jay
#

sry nvm

#

there wasn't supposed to be await

#

yeah so Main() starts, then Main2() starts, and the await in Main2() will make execution return to Main()?

bleak citrus
#

My understanding is that running an async method without awaiting it means that the method executes until it hits an await

#

at which point control returns to the caller

wary thistle
untold moth
wary thistle
untold moth
wary thistle
untold moth
#

If it's really vsync, then you could try disabling vsync. Optimizing your script is not gonna help at this point.

wary thistle
untold moth
wary thistle
#

is this enough?

#

@untold moth

untold moth
# wary thistle is this enough?

This is not the hierarchy mode.

But what I can see from here, it is indeed vsync. You should try profiling a build and seeing if your GPU forces a vsync on the app.

Also, 4.6ms is really fast anyways.

wary thistle
wary thistle
untold moth
#

Or, if you don't need graphics/visuals at all, you could build it as a server build and disable rendering

bleak citrus
wary thistle
wary thistle
untold moth
wary thistle
wary thistle
untold moth
# wary thistle

The 0.8ms is basically waiting for the GPU. It could be due to vsync still or simply the GPU rendering stuff.
There's probably not much you can do here without disabling rendering.

untold moth
# wary thistle

You could have several environments. One for debugging with actual rendering and one without for the training runs. It's not like you're gonna see all the stuff rendered during the training runs anyway. If you were to record it all, it's probably gonna be gigabytes and hours of video.

If you really need some debugging data, you could record crucial data, like positions, rotations and such and save them to a file in organized way. Then you could reconstruct what happened in each run from that data.

night geyser
#

im trying to figure out circular audio buffers (trying to make voice chat)
where im struggling is figuring out where (in my clip) to write the audio data to (because if there was no data recently then we should write to the current point in the playback, and if there is data we should write onto the end of it)

here's what i have currently, any thoughts or suggestions are appreciated

public void OnNetworkDataReceived(object o) { //called when network data is received (should be every ~0.5s)
        if (o is NetVoiceData) {
            NetVoiceData voiceData = (NetVoiceData)o;
            //should only happen once
            if(voiceData.sampleRate != playbackSampleRate) { RegeneratePlaybackClip(voiceData.sampleRate); }
            float[] receivedData = voiceData.audioData;
            //setup the write index
            int samplesToWrite = receivedData.Length; 
            int currentSampleIDx = voicePlayback.timeSamples;
            int writeIdx = currentSampleIDx;
            if(Time.time < safeHeadWriteTime) {
                writeIdx = lastPlaybackSampleIDx;
            }else{
                writeIdx += voiceData.sampleRate; //add a small buffer of 1 second
                safeHeadWriteTime = Time.time + 1f;
                //clear the buffer (it is a 5s buffer)
                float[] clearData = new float[voiceData.sampleRate * 5];
                playbackClip.SetData(clearData, 0);
            }
            playbackClip.SetData(receivedData, writeIdx);
            lastPlaybackSampleIDx += samplesToWrite;
            if (lastPlaybackSampleIDx >= playbackClip.samples) {
                lastPlaybackSampleIDx -= playbackClip.samples;
            }
            Debug.Log($"Received {samplesToWrite} samples, writing to {writeIdx}");
            safeHeadWriteTime += 0.5f;
        }
    }
regal olive
#

How would I check if something is grounded no matter what surface its on?

night geyser
hard lily
#

Regardless, for detecting flat surfaces and angled ones the best approach is to use raycasts. Have a minimum ray size for flat surfaces and consider longer sizes for increasing angles (this avoids having the characters "hovering" on otherwise flat surfaces or soft angles.

#

If you are using collision layers for "surfaces" such as metal, wood and etc I strongly recommend you consolidate them all to a single layer and instead use monobehaviours to define surfaces

#

Like if you need a metal surface, you just attach a surface script or scriptable object, select it to be metal and you are done

sudden lantern
#

How to make inputs transparent to the character? What I mean is that so I can control it with physical devices, AI controller, network controller, etc?
Right now I have in my Character component:

    public InputActionReference Move;
    public InputActionReference Action1;

Then in my code I read the Move and subscribe to Action1:

Vector2 CharacterVelocity = CharacterComponent.Move.action.ReadValue<Vector2>();
CharacterComponent.Action1.action.started += Action1_started;

And do things based on those action inputs. This is supposed to be decoupled from the player inputs, but how to control this from code?

#

I am thinking of making a clone of the built-in InputAction class with the same interface of what I'm using:
ReadValue function and the started event, and then create a CharacterInput component.
And then set those actions from a physical device or an AI controller.

#

So the character can be controlled using the same interface

#

I thought this InputActionReference and InputAction were the classes that are supposed to separate the actions that can be performed from physical inputs by the player.

sly grove
# sudden lantern How to make inputs transparent to the character? What I mean is that so I can co...

The typical approach is make something like an "InputPacket":

struct InputPacket {
  bool pressedJump;
  bool pressedInteract;

  Vector2 movementInput;
}```

Then you have your input processing code create these and feed them to your movement code:
```cs
void Update() {
  InputPacket ip;
  if (playerControlled) {

      ip = new();
      ip.pressedJump = jumpActionReference.action.WasPressedThisFrame();
      ip.movementInput = moveActionReference.action.ReadValue<Vector2>();
  }
  else {
      ip = AiGenerateInput();
  }

  Move(ip);
}```

Then you can have your AI code or network controller simply create an InputPacket each frame
#

The InputPacket struct can also be used for e.g. client prediction in a networking setup where you move your character locally with the InputPacket and also send it to the server in an RPC. The server then uses it to process inputs on the server side and you do rollback/reconciliation when the results don't match up.

sudden lantern
#

Thank you

thin mesa
robust stone
#

Ho right

#

I thought it was about muse and such

thin mesa
#

It's about all of the AI tools, including the behavior package (which also happened to previously be called Muse Behavior)

robust stone
#

Ok nice i get it

#

Thx

green meadow
#

a question, is using Time.deltaTime this much gonna cause lag

sly grove
#

It looks like you have a lot of repeated calculations there

#

For all performance concerns, you should use the profiler to check if it's a problem.

#

There's no way to know if something is a problem based on an isolated code snippet like that

sly grove
#

Things that are not a problem when called once per frame suddenly become a problem when you call them 10000 times in a frame

green meadow
#

since it's every frame

sly grove
#

What you are doing here is not "using multiple timers"

#

but that's also not a meaningful statement in terms of performance

#

Performance has to do with how many operations you are doing, and how much GC you are allocating.

#

"using a lot of timers" is a totally different abstraction

#

usually you will run into performance issues when there are loops or recursion involved, not just by having many manually written lines of code (assuming each line is itself not expensive)

green meadow
sly grove
#

If you had 1,000,000 objects each doing one operation, that's when you have an issue

green meadow
#

i just wanted to make sure

sly grove
green meadow
#

I did, I'm running at a solid 60fps

sly grove
#

Then there's no problem.

green meadow
#

but i wanna optimize the game for low end computers

#

i'll have to run a virtual machine for that

sly grove
bleak citrus
sly grove
bleak citrus
#

Each operation is incredibly fast

scenic forge
#

"60 FPS" is not the same as using the profiler, in case you are not aware.

green meadow
#

seems fine i guess

sly grove
#

Looks like you have some spikes you might want to look at - but i would guess it's the typical editor overhead spikes

green meadow
#

and the 20 chrome tabs i have open

#

but yeah

#

thank you

raven ruin
# green meadow most of the timers are in if statements, so i don't think it's gonna lag as much

Doing it in a poorly written way will be slower than doing the same thing in a better way, but you also need to consider that you could be talking about a difference of 8 nanoseconds.

For the vast majority of cases, especially for a typical indie game, it being 8ns slower really doesn't matter whatsoever. An optimisation there would only be important if you happened to call that 8ns code 100000 times in a row.

#

Hell, even 800,000ns is still only 0.0008 seconds

minor garden
#

Hello everyone, I have a question.
I want to divide a 2D top-down map into chunks. When a monster enters the area of a chunk, it should be added to that chunk's monster list.
The goal is to implement a tab-targeting feature like in MMORPGs, where the system only needs to scan monsters within chunks around the player.

The question is: how can I efficiently move monsters between chunks without consuming too many resources since positions need to be checked continuously?
Are there any documents or alternative approaches for this?

fallow summit
#

I'm trying to create a grid to allign my cards onto.
The grid takes in a prefab and generates a grid made out of those prefabs.
Problem at hand:
The grid is being generated at -1876.85 if the z value for the grid's vector3 is 0 and is moved according to the following function if the z variable of said vector is changed.
f(x) = x*20.854-1876.85
To get the desired z value of 0 I would have to input "89.9995204756881" which is not storable using a float.
That number does get close to the z value of 90 my canvas, which is set to "Screen-Space Camera", has.
Attached you find:

  1. Screenshots of the prefab
  2. Screenshots of my camera and canvas settings
  3. the scripts attached to those GameObjects
    I'm open for anny suggestions and solutions,
    kind regards, Emily.
sly grove
#

It's also unclear why you care about the z position and aren't just making it 0.

#

You could also just be using GridLayoutGroup here.

fallow summit
sly grove
#

Again why not just use GridLayoutGroup anyway?

fallow summit
#

because I do not know what that is tbh "._. it also kinda fixed itself after i deactivated, reactivated and added it back to the canvas

#

it changed the offset to a fixed -90

#

instead of that weird function

modest sinew
#

Hey so quick question. If i load 2 scenes with async, and one scene is priority 1 and the other 0. Will the scene with priority 0 not load until scene 1 has been enabled?

Because from what i can tell this is the case. Scene 0 is at 0 progress until i enable the first scene and then both finish loading

modest sinew
#

this doesnt mention anything about the operation having to be 100% progress before it allows anything else to happen on any operations with lower priority

sly grove
modest sinew
#

i suppose it makes sense for it to function like this, its just annoying that it doesnt fully explain what it actually does as i wasnt expecting it to act like that. i was hoping it would prioritize the loading to finish it first, not to prevent other async operations

raven flicker
#

Howdy folks. So as best I can tell (from my own testing and reviewing bug reports from other users) Software Cursors are not supported by Unity's New Input System. I would greatly like to use a Software Cursor, because Auto/Hardware remove control of the cursor size from my control and push it back on the OS which breaks what I am using it for. Is there any other way perhaps to get the desired effect I want?

sly grove
raven flicker
#

Yeah I posted there last night but got no hits, so I'm trying a different tactic of how else could I do cursors. Since cursors and the input system seem like a tangentially related issue anyways.

#

I've been using SW cursors for over a year on Unity 2022.3 and have had relatively few issues. Upgrading to the New Input System however, it makes the cursor freeze in the first location it is rendered.

#

There seems to be many other people experiencing this as well, with no solutions other than to go back or use both systems.

bleak citrus
#

i'll give this a try in my game

#

Seems fine for me. The cursor is visible and moving around after doing this duiring game startup

#

Cursor.SetCursor(cursorTex, Vector3.one, CursorMode.ForceSoftware);

#

(it's a very big texture oh no)

raven flicker
#

It works if I call it once. It does not work if called from Update.

#

Which I need, because the cursor changes based on what it is hovering over?

bleak citrus
#

I'll try doing it in Update

raven flicker
#

I suspect each call to set cursor is resetting something. Also, what version of Unity are you on?

#

It may be this was eventually fixed and my version is too old or something.

bleak citrus
#

hmm, still seems fine.

I'm running 6000.0.24f1 on macOS

#

It could be platform-dependent

raven flicker
#

Heh. Wonderful. Blegh.

#

I can't upgrade this to U6.

bleak citrus
#

It's more likely that ForceSoftware behaves differently on this platform

#

Notably, I can't tell if it's actually doing anything

raven flicker
#

Oh. Well, yes that may be true as wel.

bleak citrus
#

The results are identical if I use Auto

raven flicker
#

Yeah I have a matrix of 50-something cursors in 3 sizes.

bleak citrus
#

now this is a good cursor

raven flicker
#

You'd need to be resizing the cursor to see if its actually resizing it. But I doubt that would work since Auto generally forces it back on the OS.

#

Anyways, I did hunt and found other people having the same issue.

#

Thank you for testing with the setup you were able to.

#

@sly grove did you have any other thoughts on the matter?

fallen osprey
#

This is a problem pink

drifting solstice
#

not a code issue

bleak citrus
#

on Auto, the cursor is not changing size, but it also disappears when it gets locked

raven flicker
#

:nod:

#

Yes, I had some other issues with Auto that were undesirable.

bleak citrus
#

It wasn't disappearing when locked when I used a size of Vector3.one

raven flicker
#

Performance issues limit my using both systems.

bleak citrus
#

ForceSoftware doesn't disappear when locked in this case. But it's also not respecting the size either

#

note that I'm also setting the lock state immediately before calling SetCursor

#

i'll see if that matters

raven flicker
#

Warping also doesn't seem pertinent to what I need?

#

nm, I think I get it. Heh, worth I a shot I guess but damn what a hack if this is needed.

sly grove
bleak citrus
#

oh, i just realized that the vector3 argument is a position offset, not a size, haha

raven flicker
#

Oh, yeah the size is the size of the image.

#

The vector3 offsets the cursor "tip" point.

#

Its all really nice and works well until it doesn't

bleak citrus
#

hm, it still doesn't do anything! It might just not work at all on macOS

bleak citrus
#

...ah, i was using a constant for the offset

#

I'm currently setting the cursor right after my game decides to switch the cursor lock mode. When using Auto, the cursor vanishes when it gets locked, but only if the offset gets changed from the value it had when I was using ForceSoftware.

Very weird.

raven flicker
#

Yeah I mean vanishing is the same thing. It basically gets moved offscreen and never comes back while the actual mouse and clicks and everything is processed normally. The two threads discussing it go through all the steps and thoughts I had pretty well.

#

for now I'll just keep using the legacy input system. I only made this leap as a result of pressure from members here haha...

bleak citrus
#

Okay, so here's a really funny idea

#

what if you set the hotspot offset to a small random value every frame

#

Does the cursor show up?

raven flicker
#

I'll have to give that a try and see.

bleak citrus
#

but it's interesting that changing the offset has any effect at all

plain abyss
#

I have an array of XY points, here represented by spheres. This is a 2D cross-section of a radially symmetrical object. What would be the best way to turn a bunch of points defining a 2D shape into a 3D object?

austere jewel
#

if that's what you mean by 3d object

plain abyss
# austere jewel if that's what you mean by 3d object

Yeah, basically, just take the object about its center (you can see the origin selected there, the y axis goes right through it, it's centered at 0) and just like, radially extrude it into a mesh so it forms a sort of mushroom shape

austere jewel
#

Ah, if the center isn't inside the object then my first suggestion won't work, you'll have to try something more complicated

plain abyss
#

Searching "Radial Extrusion" isn't quite what I wanted but this sort of demonstrates it:

#

Like, spin the flat object 360 degrees about its center and make the resulting mesh

austere jewel
#

So you want to revolve these points and create an actual 3d shape with volume

plain abyss
#

Yeah, this is a cross-section of a 3D shape I've gotten from a bunch of math and I need to rebuild the 3D shape from that

#

Just spin it about the Y axis into a sort of deflated sphere

austere jewel
#

do you have these points in a sensible order already? Like, tracing the border of this object?

heavy phoenix
#

hey all,

I've been having issues with Unity's Transparency Sort Mode custom sort via y axis. I've tried using both Built in and URP. Neither do the job the transparency sort mode claims to.

doing everything right so far as I can tell:

  • pivot sort axis
  • same layer & sorting layer
  • same order in layer

if anything it gets weirder bc the player was sorting with a background layer that wasnt anywhere CLOSE to being on the same layer. and it wasnt even happening on the y axis, it was on the x axis. this is resolved now by changing the material or something to default sprite or something haha but yeah, would love to have this sort function work visually

plain abyss
#

I at least have that going for me

austere jewel
#

If so, then surely it's as simple as just revolving and creating triangles at the poles and quads everywhere else, bridging between two steps

heavy phoenix
austere jewel
heavy phoenix
#

where should it go?

#

I'll paste it elsewhere and then put another issue im having here

austere jewel
plain abyss
#

So, get the array of points as A1, and then some offset. Rotate all the points about the Y axis by that offset into A2, then do quads with points of A1[i], A1[i+1], A2[i], A2[i+1]? With special handling for i==0 and i==A1.Count?

austere jewel
#

Yep

plain abyss
#

Now I just need to figure out how to do that rotation, which is almost certainly going to require quaternion multiplication so I'm going to have to just bash my face against the math until it's the right shape

austere jewel
#

If the vertices are already centered around y then it's just
vertexAtRot = Quaternion.Euler(0, rot, 0) * vertex

heavy phoenix
#

New Issue:

So im trying to create a dialogue system. this issue has 2 parts. happy to only focus on part 1 for now if thats ok.

  1. the first page of dialogue is fine, but then DialogueBaseManager.finished = true and the next dialogueLine runs, and for some reason it seems to be called twice... as in, the text IEnumerator would say like "HHelloo wwoorrlldd". This continues for the rest of the dialogue lines, but not the first one.

  2. Atm my dialogue system only allows for cycling through the children of one object DialogueManager. for a game with the potential for thousands of dialogue lines, this wont work. I'd need a totally separate system. Any ideas of how i might e.g. store dialogue info in a file and get that on certain triggers from a dialogueBaseManager? or idek just set different dialogues for different game objects, and have those change over time with different bools unlocked so to speak

#

i can paste code if that helps:

#

DialogueBaseClass:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace DialogueSystem
{
    public class DialogueBaseClass : MonoBehaviour
    {
        public bool finished { get; set; }

        protected IEnumerator WriteText(string input, TMP_Text textHolder, Color textColour, TMP_FontAsset textFont, float textDelay, AudioClip sound)
        {
            textHolder.color = textColour;
            textHolder.font = textFont;

            for (int i = 0; i < input.Length; i++)
            {
                textHolder.text += input[i];
                SoundManager.instance.PlaySound(sound);
                yield return new WaitForSeconds(textDelay);
            }

            yield return new WaitUntil(() => Input.GetKeyDown("z"));
            Debug.Log("Finished = true");
            finished = true;
        }
    }
}
#

DialogueLine:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace DialogueSystem
{
    public class DialogueLine : DialogueBaseClass
    {
        private TMP_Text textHolder;

        public DialogueManager dialogue;

        //public bool hasStartedDialogue = false;

        [SerializeField] private PlayerControl player;

        [Header ("Text Options")]
        [SerializeField] private string input;
        [SerializeField] private Color textColour;
        [SerializeField] private TMP_FontAsset textFont;

        [Header("Time Parameters")]
        [SerializeField] private float textDelay;

        [Header("Sound")]
        [SerializeField] private AudioClip sound;

        private void OnEnable()
        {
            if (dialogue.dialogueIsOpen == true)
            {
                //StartCoroutine(DialogueRun());
                DialogueRun();
            }
            else
            {
                ResetDialogue();
            }
        }

        private void OnDisable()
        {
            ResetDialogue();
        }

        /*public IEnumerator DialogueRun()
        {
            for (int i = 0; i < transform.childCount; i++)
            {
                textHolder = GetComponent<TMP_Text>();
                StartCoroutine(WriteText(input, textHolder, textColour, textFont, textDelay, sound));
                yield return new WaitUntil(() => this.gameObject.GetComponent<DialogueBaseClass>().finished);
            }
        }*/

        public void DialogueRun()
        {

            textHolder = GetComponent<TMP_Text>();
            StartCoroutine(WriteText(input, textHolder, textColour, textFont, textDelay, sound));
        }

        public void ResetDialogue()
        {
            textHolder.text = "";
            finished = false;
        }
    }
}
untold moth
austere jewel
heavy phoenix
wise barn
#
public class DATABASE : MonoBehaviour
{
    public Sprite[] savePortraits;
}
public class SAVEDATA : MonoBehaviour
{
    //Updated by main menu to select which save indexing to read and write from save file
    public int index;

    // I.E. savePortrait = DATA.savePortrait[SAVE.file[SAVE.index].savePortrait];
    public SaveFile[] file;
}
[Serializable]
public class SaveFile
{
    public int savePortrait;
}
public class CALLEREXAMPLE : MonoBehaviour
{
    [SerializeField] SAVEDATA SAVE;
    [SerializeField] DATABASE DATA;

    [SerializeField] Sprite sprite;

    public void Start()
    {
        sprite = DATA.savePortraits[SAVE.file[SAVE.index].savePortrait];
    }
}

is there any disadvantages to doing save files in this manner?

bleak citrus
#

I don't see why the "database" or the "savedata" classes are monobehaviours

#

they're just bags of data

wise barn
#

im not super experience din programming and this is easier for me to do atm. for DATABASE, it will also hold stuff like Prefabs and such

#

im wide open to feedback

heavy phoenix
#

i think the best way would be to make it from scratch, even if it does take like years

midnight violet
wise barn
#

its saved as json i jsut left it out.
i ended up talking somewhere else about this, but the reason i put it in advanced with that question is i wasnt aware if there was a disadvantage of havign a database script holding all prefabs, and other refferences in a single script being called by most other scripts

gusty berry
#

hi there, im looking for a way to access external webcam cameras on ios through unity on ios (ipad). i have no problem getting camera feed from the onboard cameras, but i dont seem to be able to access a usb camera. any help would be appreciated!

fiery dome
dusty wigeon
# wise barn its saved as json i jsut left it out. i ended up talking somewhere else about t...

Yes there is.

Whenever you load your database, you would also need to load every prefab which means all the texture, meshes and audio clip. Those types of assets are heavy and will mostly not be needed in every situation. Instead, you should use weak reference to hold unto your prefab and only load them whenever you need them.

If you do not do this, you will mostly see a really long initial loading time with little to no room to manage memory. Obviously, if your project is simple, none of that will be apparent.

bleak citrus
#

the next time I bump into that, I think I'm going to have a singleton that takes item definitions and gives you a game object (possibly loading assets in the process)

dusty wigeon
bleak citrus
#

Yeah, I was already halfway there with item definitions. They just had direct references.

dusty wigeon
#

Weak reference is a concept, not really a feature.

#

You can use a string to have a "weak reference".

#

Also, I believe you are speaking of something else entirely.

#

Which would be weak reference through code memory.

bleak citrus
#

I initially thought of a literal WeakReference

#

Which is much closer to what you're describing here

#

That lets you store a reference that doesn't prevent a C# object from being garbage-collected.

sage radish
stuck plinth
#

i think unreal also has soft references which are something like an AssetReference?

#

i'm no unreal expert lol

regal lava
#

What's the difference from you know, not dereferencing it completely?

bleak citrus
regal lava
#

sounds like a memleak waiting to happen

bleak citrus
#

But the weak reference won't stop the GC from eating the object

bleak citrus
regal lava
#

Ah, reading on them they sound like a neat way to just kinda clean up references but at the bottom of the page it's like:
Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.

modest slate
#

Something weird. If I have a rigidbody, and I want it to stick somewhere after hitting it with collider or trigger, I then change it to Kinematic for the physics to stop change it's position. Then I can specificaly set it's position in transform.position.
The strange thing is... if there is interpolation, it would end up in a different position.
I have to turn interpolation into None, before I can set it's sticking position.

Is this a known issue?

bleak citrus
#

Yes, this is how interpolation works

#

The rigidbody sets the transform's position every frame, which clobbers whatever values you put in

#

When interpolation is off, this does not happen

#

Set the position property of the rigidbody.

#

You may be able to just set it and the transform position at the same time. That'll let you leave interpolation on.

frail hemlock
#

this question might be impossible, but i wanna import my house into unity, like a model of my house (on a side note how can i get said model) (also on a related note how do i make a portal gun in vr) i wont see the responces until uh around 2pm on gmt-5.

sly grove
#

It doesn't matter if it's a donut, your house, or the mars rover.

#

on a side note how can i get said model
You would have to make it.

frail hemlock
#

also before i go, can u recommend a guide on how i could go about making a portal gun

sly grove
#

No I don't have one of those sitting around. Search on youtube or google

frail hemlock
#

ok, thank you for this good advice, i will tommorow :)

real basin
#

I've got a issue on how to approach a problem. I'm making a card game roguelike. I've got the board and movement around the board set up(its a 2d arr). the problem comes down to when it moves, i want to call a script. I have a parent class, called minion, with this function

public class Minion : MonoBehaviour
{
public virtual void onMove(int dir, int row, int col)
{
  Debug.Log("a");
}
}

then i have a child of the class, snake

public class SnakeMinion : Minion
{
  public override void onMove(int dir, int row, int col)
  {
      Debug.Log("b");
      //whatever the snake does
  }
}

ive got both of these on the same object, and whenever this card moves, it calls onMove(minion script). i want it to call the snake card instead when it calls onMove. there will be more cards than the snake, so i cant just have a check on the minion script just looking for the snake class.
im not exaclty sure how classes work in c#, im more used to java classes. any help would be appreciated

drifting solstice
#

(in any case, this is not an advanced problem)

prime kindle
real basin
#

Well thats the thing, it does not do it

midnight violet
real basin
real basin
prime kindle
#

so you have the game object with BOTH the minion and snake scripts attached to it?

tall ferry
tall ferry
real basin
tall ferry
#

it sounds really odd that you'd have a Minion and SnakeMinion on the same object, while specifically only wanting to get the snake minion

upbeat path
real basin
real basin
upbeat path
hallow flax
#

I would like to inquire whether the ONNX file in the unity ML agent contains all types of learning or if it only retains the best results, Additionally, how can we filter it out if needed?

abstract hill
#

Hi everyone, I am working on some high performance required code in which I am trying to check if specific chunks in a procedurally generated game are within the render frustum, right now this is my current speeds.

This is my current testing order, (I have moved them around to make sure the speed is as fast as can be with the current code). I am going to be looking into quad-trees too but I was wondering if their are ways to speed these things up even more. For example, are their faster substitutes for bounds checks. (I am loosing 0.72ms just from copying a vector to the bounds.centre).

The hash set is also something I was hoping someone could potentially mention for a faster way of doing this, right now all I am doing is assigning chunks to this set when they are considered render able, however this is still unbelievably slow.

This is a bit more of a board question, as I am wondering if their is a way to access private fields (like the centre variable of the bounds) to change them directly without needing to create new strucks or objects and such.

sage radish
abstract hill
#

Ill look into jobs, good shout. Mainly just concerned with the amount of objects needing to be made, from my understanding of jobs you need to create an objects the pass it to the job system to be executed. Since slow down is happening on creating small structs like Vectors, I am worried that creating the jobs itself will also take up way more time then it could solve.

I was also wondering actually, are their any maths libraries that can be called through C#, to my understanding most of the maths stuff (though this may be wrong) is written nativly in C#, are their any super optimised ones written in C# or assembly in which I could call instead. (again this is a broader question for me potentially replacing alot more things down the line)

fallow echo
#

+1 for looking into job systems... also you can burst-compile specific methods, I hear, and call those and those would be performant...

#

unless you can do something smarter, that's just a lot of operations, and if you can do them in parallel and whatnot - it's gonna be order of magnitude better... otherwise if you share more code and whatnot we can perhaps optimize something, but it wouldn't be WOW

abstract hill
#

I can send the main function, I'm rewound it to before I made changes (though I will be going back to try the job system), is it fine to paste a block in chat or should I use a link? Like pastebin?

#

So to explain, the code is being used to queue up chunks for rendering, not to render them. I need to know if the chunks are already in the last frames render queue as I am uploading and disposing of data from the GPU only when it is no longer needed. So this is the actively observed chunks, which are then compared to the previous frames where it is split into 3 lists, common, new and old. (New gets uploaded to the GPU, old gets disposed of).

abstract hill
#

Does Unity not have a TestPlanesAABB test for planes jobs?

abstract hill
#

Ah brilliant, thank you. Just surprised me is all, I would have though the AABB collision detection would be a pretty contained function, given you are providing it with the planes and bounds to check.

fallow echo
#

not sure how ChunkCoordinate works, but perhaps the implementation can be better when it comes to hashcode and stuff

sage radish
#

For example:

#

Where the data comes in already packed for SIMD

#

Burst will attempt to auto vectorize and make use of SIMD for you, even if you don't do it explicitly, but the slightest changes in how your code is structured can make that automatic process fail.

abstract hill
#

Thank you, I will have a look!

abstract hill
#

I'm not finished looking into things yet but I wanted to check with everyone about something, I did a quick test with things transitioned to jobs and its actually working out slower. The problem seems to be the reading and writing to native arrays being really heavy on compute time. I have tried to minimise this by caching the data I need on the job so I'm only calling getItem and setItem, when absolutly necisary, but this is still way to slow.

Reading further into the call stacks shows that a large portion of time is speant doing something called "AtomicSafetyHandle", given I know that the indeces arn't overlapping is their a way to turn this off on the NativeArrays?

real basin
timber kernel
bleak citrus
#

It's been a hot minute and I'm not terribly experienced with the intricacies

abstract hill
#

Damn, so their isn't really a way to get passed this then with NativeArrays? Do jobs support different types of data then? I read online that ConccurentBags and such don't work with burst, but is their alternatives?

#

Alls good! I appreciate the help, I will give this a look into anyway. I'm pretty new to trying to get everything as optimised as this so just trying to get as much info as I can xD

untold moth
chilly moon
#

Turn off safety checks, usually the issue (on by default). Also looking at your previous code, seems brute force checking for x for y for z, surely you could try and figure out the edges and assume outside/inside. Also its useful to predict the size of buffers you need. If using a buffer/dictionary/hashset, give it a max possible or predicted size. Also as mentioned work with float4 amd the 'math' library. You can work with xyz(w) math in one formula. I love Tuples but can be hard for the compiler to optimise especially on Burst. Storing (int,int,int) is large for an index. Depending how many coords, you could use a byte4, but ideally you have a single index ie. Int that refers to a table that refers to a chunk with coord data (possibly)., therefore storing only whether chunk index should be in the queue. Could also go the entity route which is about separating objects and data.

chilly moon
scenic forge
# abstract hill I'm not finished looking into things yet but I wanted to check with everyone abo...

Safety checks are off during runtime, they are (IIRC) on by default in editor to help prevent errors, so those costs won't actually be there.
I cannot see your code to know what's going on, but if you have two copies of the data (one using regular managed C# array, one using native array) and you are treating the managed one as source of truth, while you are constantly copying to the native one, running the job, then copying the result back.
The ideal way is to just have the native array as the only source of truth and everything operates on it, so there's no back and forth moving data around.

abstract hill
abstract hill
abstract hill
stuck plinth
#

iirc you can more easily convert NativeArray/NativeSlice to C# Spans these days and off the top of my head using the copy methods on spans seemed faster too but i don't think i profiled it much

tired fog
#

Hellou, I'm using jobs for a node system that includes many job scheduling. Right now i have a big array that jobs read and write to it in parallel in a nice ordered manner (no overlapping, no errors).

The problem with this system is that i need to precalculate the array size before starting and select the different places each job can write and readfrom. It's not a big problem because it's what i have.

But I wanted to improve readibility and instead of one big array have many small ones that get passed around as pointers. That way each node can create it's arrays, add or write and pass the pointer down the line for others to read.

Is there any major performance impact in a change like this? Or anything that I should know before that can help me judge if it's worth it or not before doing all the changes it requires?

compact ingot
tired fog
#

By this you mean moving from one big array to pointers?

compact ingot
#

yes

tired fog
#

so better the one big array

compact ingot
#

yes

tired fog
#

alright, thanks!

compact ingot
#

but not a big array of big structs

tired fog
#

nono, its a big array of floats

#

my idea of pointers was to get the pointers when scheduling the jobs only for the specific case where there are N arrays that have to be combined

compact ingot
#

also you should not jump around in the array

tired fog
#

nope, always accessing 1 index at a time, but starting at diferent offsets

compact ingot
#

if you don't use jobs, and implement your parallelization with low level sync primitives, you can design a system that is fast without the constraints that jobs put on you

#

but that is extremely difficult

tired fog
#

Yeah, the good thing with Jobs is that it's quite accessible to anyone and it's something I would like to keep

compact ingot
#

not in the sense that the code is difficult, just making it perform well requires a lot of insight

compact ingot
#

and it coaches you into the right approach that is fast and manageable

minor ruin
#

Is anyone good with Photon?

#

because im having a problem where ascript cannot acsess CustomProperties

#

scratch that when i set the custom properties it doesnt

#

for more info

minor ruin
#

please @ me or dm me for help cuz im going bed

regal olive
#

i have all my animations ready but i need to script them to perform combos and stuff in my game but i tried all AI's and provided them with maximum information but they are still not working as expected i need help pls if someone can i have most of the code so if anyone can help me fix anything from it i will be glad i need it to work as quick as possible so please help me if u can

drifting solstice
#

have you tried googling for it at all

#

"unity combo attack animation"

regal olive
#

yea

tired fog
#

Hi!
1- Doesn't sound like code-advance, probably better fit for #💻┃code-beginner
2- Can you say exactly which features are we talking about? and how deep do they go? For example healt bar ui can go from simply adding a texture that gets squishy to having to create a world canvas, the required scripts to update health, placement of those ui bars that follow or not the enemy, etc...
3- Depending of 2, 15 dollars seem way to low. If it's so simple that 15 dollars are enough, you can probably do it with ChatGPT and learn along the way, otherwise i don't think so

weak mica
#

Yea it is quite low

#

thanks will take the advice

drifting solstice
#

and please don't crosspost.

weak mica
#

of course

bronze glen
#

I've encountered a strange problem with changing materials of an object in build. If it has a baked lightmap (being static is not required), everytime I change material in build it just changes to pink and makes the game very laggy when I look at it. I checked if there was something wrong with shader or material with Debug.Log(), but everything seems to be fine. Interestingly, it appears only in build, everything works fine in editor. So, does anyone know what is happening?

bleak citrus
#

I wonder if the new material has a different shader that wasn't compiled with the lightmap keywords

bronze glen
#

both the original material and the new one are just the same with same shader (URP Lit) but different texture

bleak citrus
#

it's possible that you wound up with a combination of shader keywords like

#

USES_FOO
USES_FOO LIGHTMAP
USES_BAR

#

But if materials literally only differ in albedo texture, then I wouldn't expect this

#

(I'd also expect unity to spend 5 hours compiling every single possible combination of keywords)

bronze glen
bleak citrus
#

Unity should also try to fall back to a shader variant that's "pretty close"

#

unless you turned on strict shader variant matching

bronze glen
#

nah, it is turned on 😦

#

or this is the issue?

#

I mean, materials are really the same, so there shouldn't be any shader variant differences

bleak citrus
#

If it's turned on, any mismatch in keywords will cause an error shader

#

Importantly, if the second material is not used in a scene, it won't have gotten the lightmap keyword

#

at least, that'd be consistent with the problem

bronze glen
#

💀

#

I think this is the case...

bleak citrus
#

Turning off strict matching would prevent the error shader from appearing, but I'd expect the material to still be lightmapped wrongly

#

(or, well, it won't be lightmapped at all)

#

You can test this by sticking the material on something in your scene that gets lightmapped

bronze glen
#

Yeah, sure, I will be expirementing with this

bronze glen
lavish plume
#

I'm creating a floating capsule type of movement system similar to half life and I'm having an issue where for some reason the Y position on the player's rigidbody is slowly reaching the target instead of instantly snapping to it. I've attached the code in the pastebin alongside a video to show the unwanted smooth effect (if you cant visually see it just look at the transform)

https://pastebin.com/zvec5SQj

lavish plume
#

Solution was to divide the distance between the target height and the player by fixeddeltatime

slow jay
#

if i have an array in a job that is run on multiple threads, and I know that any given Execute() isn't going to write to the same indices as another Execute(), is that still going to be undefined behavior?

untold moth
regal olive
# slow jay if i have an array in a job that is run on multiple threads, and I know that any...

In most cases, if each thread is guaranteed to write to distinct, non-overlapping indices of an array, it should not result in undefined behavior. However, it's crucial to ensure that there are no concurrent write operations to the same indices, as this could cause data races and undefined behavior.

Here are a few key points to keep in mind:

No Concurrent Writes: Ensure that no two threads are writing to the same array index simultaneously.

Thread Synchronization: While not strictly necessary if there are no overlapping writes, you might still want to consider synchronization mechanisms to manage access to shared resources.

Array Bounds: Ensure all threads respect array bounds and do not access indices out of range.

If you ensure each thread is working on separate indices, and your array bounds are respected, you should be in good shape. It’s always good practice to review your concurrency logic and test thoroughly to catch any potential issues. 😊

untold moth
regal olive
untold moth
#

It did sound like something chat gpt would generate. These are general advises in multithreading context, but they don't touch at all om the jobs nuances. Unity might be imposing extra restrictions in the jobs.

regal olive
regal olive
long ivy
#

being accused of an AI response isn't a compliment. It stands out because your key points are all worthless given the context of Unity jobs and the question, so it looks exactly like you regurgitated an AI response without knowing what you're talking about

regal olive
#

I don't understand your logic here

regal olive
#

or falsely accused

untold moth
#

I mean, it's fine. Even if it was an ai generated response. Was just curious.

humble leaf
#

Move on, don't turn this into a thing, thanks.

regal olive
mellow sail
#

hey guys, I have a question. Let's say i have a server url and wanted to fetch data from a databasein my unity windows game. Is there a way that the player could know my API for fetching data? or could see my server URL?

devout hare
#

Yes, it's trivially easy to find the URL. And no, you can't hide it

drifting solstice
#

your computer needs to know the url/ip in order to actually make the request. and if your computer knows, then the user can know too

mellow sail
#

what would be the best practice to avoid player from cheating if thats the case, like there's a chance the player uses it to send (via rest API configuration that I had in a script) manipulative score?

drifting solstice
#

cheating what exactly? there's no one-size-fits-all solution here

mellow sail
#

like lets say sending score to save via database

devout hare
#

You can prevent people doing it casually by adding a checksum into the payload, that can still be manipulated but it would require decompling the game which most people wouldn't bother with. The only way to prevent it (almost) completely would be to have the server validate the entire playthrough

#

It's not an actual problem for most games. If someone cares enough to mess with the highscores you can take that as a good sign

mellow sail
#

rather than just PUT a plain score to the server

#

the thing is, the score kinda important since its for buying things in the game

drifting solstice
devout hare
#

It makes no difference. The game must include the encryption key for it to be able to encrypt the score

drifting solstice
simple tartan
#

Hello! One quick question: I need to send a .txt file created by my Unity app to one folder in other PC via Local Network (there is no internet connection)

Whats the simplest way to do that?

mellow sail
drifting solstice
drifting solstice
#

if you're not sending it via the internet, then not having an internet connection doesn't really matter
if you have that local network you can use that to communicate between devices

simple tartan
#

@drifting solstice thanks! i want to do It from Unity, whats the library I need to use?

#

Or just copy it / save it to a folder?

drifting solstice
#

any ftp or http solution would work

mellow sail
#

okay thanks guys

simple tartan
#

@drifting solstice ok So I need just to find FTP tutorial for Unity to send the file isn't it?

drifting solstice
#

sure

simple tartan
#

Thanks a lot!

gloomy flume
#

Hello! Could you please help me with serialization in editor?

I have interface IScoreView and two different views - TMPScoreView and DefaultTextScoreView implementing it.
I have class ScoreManager that is monobehaviour. I want to assign those two views on my ScoreManager, but I want ScoreManager to work with Interface and not implementation.

Unity [SerializeField] or [SerializeReference] not working (one not showing in editor, another giving errors) for IScoreView, only with TMPScoreView or DefaultTextScoreView .
I've tried with Odin, but not sure how to properly do it with it (can't find it in docs). Could you help me with it?

robust nexus
#

Backend Score Validation

compact ingot
# gloomy flume Hello! Could you please help me with serialization in editor? I have interface ...

there is no reliable way to reference interfaces in the editor, you can find some serializers on github that promise to do it, in practice it breaks down very easily under refactoring/git-use/prefabs. You can also try OdinSerializer which is at least a well supported solution for many serialization issues that come up with unity. Generally its best to not get fancy with serialization in unity. Its decision to keep it simple is more helpful than inconvenient in practice.

long sky
#

i was trying to make a module for character controller. Used MVP pattern. Ended up with this (see picture). I don't like the long chain of events invokation (lines) from input reader to presenter to model to spell caster. Can someone help me loose the coupling?

#

All starts when player gives input and then the logic goes according to diagram

gloomy flume
#

You can expose your spellcaster as public as one of options and subscribe this way.
not sure it's best approach though.

fallow echo
# gloomy flume Hello! Could you please help me with serialization in editor? I have interface ...

I hope it's not in any way inappropriate mentioning my own packages... but I have one that includes a tool for selecting what implementation to use when doing SerializedReference + interface / abstract class: https://github.com/pulni4kiya/unity-editor-tools
What you'd do is [SerializedReference, TypePicker] private IMyInterface field; and it just works.
You could indeed mess it up a bit if you start renaming serialized classes and whatnot (solutions for some of it exist), but still, I'd say it's well worth the freedom that you get. I use it in all my projects, and we also use it at work all the time. 🤷‍♂️

tired fog
#

Im creating a Texture2DArray in a scene, without saving it to the disk, but it's a private field. However, when I save the scene this one gets saved with it. It shouldn't be because it's regenerated so i don't understand why its being saved?

#

And if it will be saved no matter what, is there any way to detect a save event to destroy it?

upbeat path
sly grove
sly grove
#

Are you just running the game again without a domain reload and without reloading the scene or something

tired fog
#

Just to be clear, im creating the texture2d array in editor mode

sly grove
#

sure, and the domain reload question is still relevant

tired fog
#

okay, then no, im never running the game.

sly grove
#

Loading a different scene?

#

Restarting Unity?

#

the field is basically going to be retained until a domain reload happens

tired fog
#

But when I press on my keyboard ctrl+s at least with other private fields, they never get saved

sly grove
#

Can you answer the clarifying questions?

tired fog
#

I just don't understand exactly what you mean by some XD. but I can explain the last one. By saved i mean that I right click on my .unity scene object and check the contents on it. And i see my Texture2DArrays there

#

Im trying to build a small script that can replicate it. Managed to do it for meshes, but it might help me understand why is being saved. By default Texture2darray doesn't seem to be saved

#

Solved

regal olive
#

For large dialogue/story systems is it smart to use coroutines for a bunch of callbacks? I have a node system at the moment and some nodes have options to ensure they are completed before continuing.

fallow echo
regal olive
#

im hoping to migrate to Unity 6 due to it having an actual node system in the behavior package

#

because the old unity node graph system has been "experimental" for years now and it really shows

#

(i tried to employ a save/revert setup with scriptable objects and i ended up reverting it after months of trying)

regal olive
lucid crane
regal olive
compact ingot
regal olive
#

yeah i essentially use Unitask right now for a bunch of it

#

i have to make sure everything works together though

compact ingot
#

ink, btw, has a very coroutine-ish execution model.

regal olive
#

and stops when i need it to

#

i thought of potentially having a main task

#

for everything to branch off of

compact ingot
#

its really not complicated, and depending on your other tooling, you can reinvent ink, in a way more suitable to your use case, yourself. Ink has an editor however that can simulate dialogue flow, this is something that can be very helpful

regal olive
#

yeah its a complicated system especially as we are working with videos

#

unavoidably

#

(1080p frame by frame animations)

scenic forge
#

(As a side note, if you are already using async/await then you shouldn't mix it with coroutines. It's much better to use exclusively one or the other, rather than mixing the two)

regal olive
#

yeah i just use them to prototype

#

worked with them longer

compact ingot
#

if you have a commandline interface (like in a text adventure) you can do everything with coroutines with very little overhead and issues

lucid crane
regal olive
#

i have node processors for each node type

#

they handle the actual execution of the nodes

#

and are in charge of stalling if it needs to wait for something

compact ingot
lucid crane
#

You likely have messed up the styling properties.

regal olive
#

ngl hardest part of this system is working with videos

#

(especially when crossplatform support will be needed for mobile at some point)

lucid crane
#

Stuff like your flex side, growth, margin, etc

regal olive
# lucid crane Wdym?

because its using unitasks when a node that needs to wait is processed it tells it to delay

#

the dialogue system runs in its own task

compact ingot
#

this is not a code issue

lucid crane
#

Oh you’re using the old ui system?

distant tiger
#

how to design complicated inventory system and crafting system like Dayz ?

untold moth
distant tiger
untold moth
distant tiger
#

no i am thing it right now like i have 100 items and each item has its uniq perpose and each item can intrect diffrentl with other item . so i have to use swithc stement to check where this item is intrect with other item and if i make a new entry i again need to adjuct my switch stement. is thr any bttr apporch to make such huge inventory system like dayz,rust

untold moth
terse inlet
compact ingot
# terse inlet To add to this, you can also use async/await with Unity's Awaitable class now. w...

that is true, and probably recommended when dealing purely with async. UniTask has some convenience methods that offer lightweight Reactive-style primitives that can be very useful when dealing with dialogue. Iz also makes it very easy to convert between all these async patterns via UniTask which comes in very handy when using 3rd party libraties that use other APIs. So its worth considering.

scenic forge
#

Haven't looked into Unity's Awaitable, but UniTask also has stuffs like SwitchToThreadPool/SwitchToMainThread.

#

In the past, UniTask is a stable of doing async/await in Unity because it provides things like NextFrame/WaitUntil/etc, so it covers everything coroutine can do so you never need to mix the two. I assume Awaitable probably has most of these as well so the gap is probably pretty close.

scenic forge
#

Oh nice

#

Kind of surprised it has BackgroundThreadAsync/MainThreadAsync but not WaitUntil.

compact ingot
#

doesn't support cancellation tokens (you cancel the awaitable) and its a pooled class, so beware of that

#

it don't think it really replaces UniTask in a meaningful way

#

suppose Awaitable is just a way to unify all these async handle objects that unity has

scenic forge
#

Well not having cancellation token support does seem less than ideal.

compact ingot
#

well, its pooled, so the token pattern would not work

#

idk why its a pooled class an not a struct like in UniTask

scenic forge
#

Yeah, well tasks being structs do have some issues, but the tradeoff is imo worth it.

terse inlet
slow jay
#

what could cause Unity Editor writing 20mb/s to disk during a domain reload?

drifting solstice
#

cache/build files

slow jay
#

it's the scene file being super large: 1.2gb!

#

so it happens when I enter play mode because it writes a backup to Temp/Backupscenes

#

same happens when I just save the scene

#

is that really a large scene file? or can it be expected depending on the project?

stuck plinth
#

that seems gigantic, is it an extremely complicated scene?

lament salmon
#

In any case that is massive

slow jay
# lament salmon I saw you were working with meshes, are you saving mesh data into the scene perh...

I have an editor script that splits a mesh into multiple smaller meshes. It creates a new gameobject for each new mesh. The way it works right now is that the only difference between a new mesh and the original is mesh.triangles. Could the problem be that for the new mesh, we set newMesh.vertices = originalMesh.vertices? (even though it doesn't have all the vertices)

For example, I have a dragon mesh that has 60k vertices, and it's split to 150 smaller meshes using this GetMeshSubset() method:

  public static Mesh GetMeshSubset(Mesh OriginalMesh, int[] Triangles) {
    Mesh newMesh = new Mesh();
    newMesh.name = OriginalMesh.name;
    newMesh.vertices = OriginalMesh.vertices;
    newMesh.triangles = Triangles;
    newMesh.uv = OriginalMesh.uv;
    newMesh.uv2 = OriginalMesh.uv2;
    newMesh.uv3 = OriginalMesh.uv3;
    newMesh.colors = OriginalMesh.colors;
    newMesh.subMeshCount = OriginalMesh.subMeshCount;
    newMesh.normals = OriginalMesh.normals;
    return newMesh;
  }
#

it shouldn't be the issue though because isn't newMesh.vertices just a reference to OriginalMesh.vertices? it's not going to make a copy of 60k vertices right

lament salmon
#

.vertices creates a copy array, so no, the new mesh doesnt share the vertices with the source mesh

#

Same with uvs, triangles, colors, normals etc.

#

In other words, all meshes have unique data, not shared data

slow jay
#

so that's probably the problem then

#

ok yeah it's definitely the problem

bleak citrus
#

Yeah -- all of the mesh data lives somewhere in Native Code Land

#

This is the case for quite a few unity objects

dapper pumice
#

is it somehow possible to get the source code for the line renderer

#

i am really wondering how they handle the corners.

sly grove
dapper pumice
#

because i am using it for my city builder game and it works but i wanted to make my own procedurally generated road instead, i managed to get it working but the corners look ugly, that is why i asked.

dapper pumice
#

i have not but i will do that rn, thanks

compact ingot
# dapper pumice i have not but i will do that rn, thanks

the spline library has a line-extruder component, have a look at that, it doesn't do corners well (at all) but its a template you can use for making any kind of shape extruder. Its capable of being really fast too. You can find resources for how to do various types of corners (rounded, bevel, miter) on the net.

olive prairie
#

Has anyone had any experience writing a custom node for a visual scripting ?

reef void
#

anyone able to help with figuring out how to get my current movement script to work with Sebastian Lagues Spherical Gravity implementation?
https://hatebin.com/bvpdpsbkkd
https://www.youtube.com/watch?v=TicipSVT-T8&t=192s

Hi there, welcome to this tutorial on creating a simple first person controller that will function on spherical planets.

Updated source code for Unity5: https://github.com/SebLague/Spherical-Gravity
Original source code: http://pastebin.com/YBbFGZzD

Download the world model package by @danielsound here: https://www.dropbox.com/s/ul53h1g3nb5b9e...

▶ Play video
reef void
# reef void anyone able to help with figuring out how to get my current movement script to w...

i tried to just make my moveDirection be
moveDirection = transform.forward * verticalInput + transform.right * horizontal input;
to make it work in the local space but it comepletely ignores my camera so sometimes my W key wont actually move me the way im currently looking in the local space
I also have a bit of a problem with how jumping works, it doesn't seem to detect if my player is grounded or not once it reaches a certain point on the side of the planet

#

Also my camera gets all messed up too as i dont think it rotates with it and is clamped currently so i cant infinitely look up and go in a circle

#

This is also my current setup in the hierarchy for my player and camera objects

#

not sure if this helps too but i have a dashing script also on my player that handles some of the stuff with my player dashing which im pretty sure also uses the world direction to launch itself forward

#

Any help on how to get this working would be greatly appreciated!

stiff jacinth
#

what object is 'transform' referring to? the player?

reef void
#

here's another screenshot that shows more of the components on my player and what part its on

stiff jacinth
#

haven't looked at the scripts but does the player rotate (with camera)?

reef void
#

uhh i dont think so, i have all the freeze rotation constraints turned on

#

so i think it just moved in the direction of the world space that my camera was facing or something

stiff jacinth
#

you can still rotate the player even with the rigidbody constraints (in code). if you're using the player's transform.forward but don't rotate the player, then 'forward' will always be forward on the Z axis.

#

on a side note, your ground check's raycast is using Vector3.down. your screenshot show the player in a 'planet', which looks like a sphere. the raycast won't find any ground unless the player is on 'top' of the sphere.

reef void
#

the rigidbody should be rotating with the planet gravity in the code i added from sebastian lagues guide

stiff jacinth
#

no, Vector3.down is a constant

reef void
#

oh alr

stiff jacinth
#

looks like there is a 'gravity body' script (from your screenshot). you'll need to get what 'down' is from that (i'm guessing)

#

i'm also guessing that gravity script turn off Rigidbody.useGravity or modifies Physics.gravity ... otherwise you'd fall off the planet.

reef void
reef void
#

and then in fixed update it calls the attract method from the gravityattractor script that is on the planet

#

I gotta get off for the night, but any chance u can help out again sometime tomorrow?

#

thanks for the help so far

stiff jacinth
#

i can try. i'm in UTC+10 timezone, if that helps.

#

so it's 4pm for me right now

reef void
#

its 1am for me XD

stiff jacinth
# reef void ooh alright sheesh lol

any reason you chose to use that controller? a physics-based controller with custom gravity is advanced stuff. as an alternative, there's a free asset you can use: https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131

it's more of a framework than a plug-and-play solution - programming is required but there are lots of examples included. supports custom gravity (i.e. walk around planets) and moving platforms.

Get the Kinematic Character Controller package from Philippe St-Amand and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

ashen yoke
short blade
abstract hill
#

Hi everyone, I've been looking into converting a large portion of my codebase to work with burst and jobs. My game is currently storing chunk data (a procedural grid) in within a Chunk class, however this means that for large actions where I am going to want process chunk logic I cannot use it with jobs (since its a class, unless i'm mistaken on this).

I've been trying to convert this class and its surrounding code to work as a struct. However this means that anytime I am trying to access it (from the dictionary where the chunks are stored) they are copied instead of modified. I can't seem to figure out a clean way of being able to pass in the Chunk data as a struct while also having the changes be kept only on the original object.

I have been looking into GCHandle and IntPtr to store a pointer reference to the chunks, though this seems like a terrible solution, and I'm not even sure this is going to work.

The only other though I had on this was to just pass in the values of the class version of Chunk independenly to the job, however this seems very convoluted to me, any suggestions on how I should be going about doing this kind of thing would be appreciated.
(Though if this is the intended way of using the Job System then I will go with this, I just want to check with people more experienced with optimisation code)

compact ingot
# abstract hill Hi everyone, I've been looking into converting a large portion of my codebase to...

you have to discard the idea of having objects when you want to use jobs efficiently. Your architecture should revolve around small groups of values that change together, put these into structs, these small structs into lists, and iterate those list. Treat the output of these updates as input for subsequent updates. If you need to keep this stuff accessible via regular objects you can create Query/access functions that index into these optimized structures.

abstract hill
#

Would copying the data between the structs and the creation of new objects not cause additional slowdown?

compact ingot
#

objects are just not compatible with the optimization philosophy behind jobs

#

naturally you can use jobs just to implement a complex calculation and reduce the output to simple states that get copied into your objects, but copying the entire data (say all vertices of a mesh transformation) back and forth through the OO API is wasteful.

scenic forge
#

Also keep in mind when you shove things into a native container like NativeArray<T>, that container is a pointer, so if you have a struct containing a native array of 10,000 elements and you copy that struct, you are not copying all 10,000 elements, only the pointer.

abstract hill
#

Right, so if I understand you correctly then, with the Chunk class itself I should instead of looking for ways to pass the whole thing and then inside the job access the parts I need, I should instead just be sending in the data itself. For example within my chunk I have a native array of CellData, instead of passing in the chunk to access this, I just pass in the celldata array?

#

Or do you mean to create a temp struct (say ChunkJobData), that I copy the native array to (like you said it wont copy all data just the pointer)?

scenic forge
#

What is it that you are trying to prevent?

#

I feel like there might be some disconnect in our communication, or understanding with how things like structs and native containers work.

abstract hill
#

Sorry, my fault for this as I am multitasking atm with things though finished now so can properly ask, The main thing I am trying to do is convert the architecture of my game to flow better with the job system, right now in a general example of things I need to do this:
-> Generate Chunk Column (contains data on biome and surface height)
-> Generate Chunk (contains data on individual cells within the chunk)
-> Process Neighbour Chunks
-> Generate Cells with Chunk
-> Generate Cell Meshes
And a few other things, but this is the main jyst.

The architecture at the moment has all chunks exist in a dictionary, where they are accessed based on a int3 coordinate or int2 coordiante (for chunk and chunkColumn data respectively).
What I am trying to do now is convert most of the process described above into Unity Jobs with Burst. However given that the chunks are classes I cannot directly transfer them to the job for execution.
My question mainly comes down to, how should I go about passing in data like this to a job? Should I try and force the classes, like Chunk and ChunkColumn into structs; should I create a new temp struct, pass in a copy / references to the data in the chunk and then send that to the job, or should I pass in each property of the class seperatly.

Does that make more sense for what I'm trying to accomplish?

scenic forge
# abstract hill Sorry, my fault for this as I am multitasking atm with things though finished no...

If the goal is performance, then you would want only one copy of the data, eg use structs and native containers for the entirety of your project. Otherwise if you have two copies where one is the source of truth, eg you have data in C# managed land, then whenever you need to process them in jobs you make a copy to pass to jobs then after the jobs are done, copy the results back, that would positively kill your performance.

abstract hill
#

How should the struct exist outside of the job system then? Given accessing structs in dictionaries creates a copy of the data, storing it in the managed part of the code becomes a bit of a mess.

scenic forge
#

Your struct can contain native containers, which are just pointers.

abstract hill
#

Ah right, so let the struct be copy-able but the data inside wont be, thank makes more sense

#

Thanks

scenic forge
#

Correct, native containers are like keys to a warehouse, the actual data is over in the warehouse and you are only copying the key around.

#

That alone should be performant enough, but large struct copying still has costs, which you can optimize with ref/in. However I would not recommend jumping straight to that unless you positively identified struct copying is a performance bottleneck and you understand the nuisances with passing by ref/in.

reef void
#

Are there any big things I won’t be able to achieve by not using a rigid body character?

compact ingot
# reef void Are there any big things I won’t be able to achieve by not using a rigid body ch...

if you want anything else besides a phyiscially pseudo-correct force simulation the force simulated approach (what you call rigidbody) will be exceedingly complicated and annyoing to handle. A kinematic controller starts with the assumption that you want fully custom physics and then adds in the expected features you want, like ground and obstacle collisions. But it also assumes that things like snappy jumping, flying, movable platforms, stairs, corners and platform edges are all handled by you exactly to your project's needs (and not based on what would be realistic). Usually these concepts are difficult to implement with force simulation.

reef void
reef void
#

Like if I wanted to implement my own custom crouch/slide/dash/wall jump I would be able to?

sly grove
#

Of course

stiff jacinth
bleak citrus
#

I found the KCC to be pretty nice

#

Notably, I could swap out the motor as needed to switch locomotion modes

#

I enjoy the "visitor pattern", where third-party code calls your code

stiff jacinth
stiff jacinth
# reef void Ooh I’ll look into that, I got recommended to use that asset by someone a bit ag...

if this is still a bit too difficult for you, then maybe a more 'play-n-play' solution would be better - e.g. Game Creator 2. it breaks up the player controller into modules. each module is backed by an interface so you can write your own modules if you want. it is very 'visual coding' based though. you can write your own stuff for that too. it's not free but you can buy more of their modules to add onto it (e.g. quests, inventory) if needed, so you don't have to do it yourself. https://docs.gamecreator.io/gamecreator/

pure berry
#

Hello, I'm trying to simulate a balance effect with the SpringJoint component as the Youtuber Dave shows in this video :
https://www.youtube.com/watch?v=HPjuTK91MA8&t=151s
What I'm trying to achieve is clearly visible at 3:32 of the video.

Although I followed this tutorial and used exactly the same values as in the YouTube video, I can't get a good balance effect. You can see in my video I've attached that, instead, I slow down a lot.
The video is short because otherwise I'd exceed the file size limit that can be uploaded to Discord, but if I continued to stay tied, you'd see that the character swing extremely slowly until he's below the SpringJoint attachment point represented by the blue cube.
I've tried changing the parameters joint.spring, joint.damper and jointG.massScale but it doesn't change anything.

Here is my code (temporary) :
StateMachine.cs : https://codefile.io/f/vEqUEoohSS
SwingingState.cs : https://codefile.io/f/Jrpa22yemn

Also attached is a screenshot of my SpringJoint configuration for the video shown (Ignore SwingSpeed, it's not used).

Can anyone help me please?
Thanks to anyone who took the time to read this!

ADVANCED SWINGING in 9 MINUTES - Unity Tutorial

In this tutorial I'm going to show you everything you need to know to code an advanced (omni-directional) swinging ability in Unity. I'll also show you how to combine this swinging ability with the grappling ability from last tutorial and how to implement proper aim prediction.

If this tutorial h...

▶ Play video
lucid crane
# pure berry Hello, I'm trying to simulate a balance effect with the SpringJoint component as...

My assumption is that your rigid bodies mass is larger than the values in the video. Physics has a lot of moving values so it may just be that some numbers are set wrong. I personally think it would just be better to write your own physics system if you want better game feel, as it is far easier to tweak. Unity’s default physics are good for simulations, but I wouldn’t use them if you wanted to make your own spider-man style game.

#

By the way, why did you encapsulate your variables if you made them public?

pure berry
pure berry
lucid crane
pure berry
lucid crane
pure berry
#

Thank you very much for the tip, I'll look into it

reef void
stiff jacinth
reef void
#

its on kinematic currently lemme try simulated dynamic

reef void
#

that screenshot is from mid being pushed by a moving platform

reef void
# stiff jacinth on the KinematicCharacterMotor script, what is "Rigidbody Interaction Type" set ...

Im also having this error get constantly printed out in the console while its running:
Rotation quaternions must be unit length.
UnityEngine.Rigidbody:set_rotation (UnityEngine.Quaternion)
KinematicCharacterController.KinematicCharacterSystem:PreSimulationInterpolationUpdate (single) (at Assets/KinematicCharacterController/Core/KinematicCharacterSystem.cs:176)
KinematicCharacterController.KinematicCharacterSystem:FixedUpdate () (at Assets/KinematicCharacterController/Core/KinematicCharacterSystem.cs:131)

stiff jacinth
#

is there a gap in in the demo scenes?

reef void
reef void
#

lemme check again to make sure

stiff jacinth
#

which version of Unity r u using?

reef void
#

this is the vid and it shows it at 1:31 https://www.youtube.com/watch?v=SDgwexgeZb0

Download link - https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?aid=1100lNXT&pubref=KinematicCharacterController-CF-YT-20Sep19

What is Kinematic Character Controller?
Kinematic Character Controller a relatively low-level character controller solution that is not tied to any specific game genre and is mad...

▶ Play video
reef void
reef void
# stiff jacinth which version of Unity r u using?

i just updated my project from unity 2022 with my old rigid body controller to unity 6 and everything imported well except for the ambient lighting, but i did have to hit a button to make changed to the scripts because of API changes

#

it also gave me a prompt to make changes to a script in the asset pack due to API changes

#

so i just hit to make changes to this script and all future ones it finds

stiff jacinth
#

the script changes are to change Rigidbody.velocity to Rigidbody.linearVelocity - that's all

reef void
#

oh alright cool

stiff jacinth
#

what's "Capsule Radius" set to?

reef void
stiff jacinth
#

what's the scale of the capsule gameobject? i.e. on the player

reef void
stiff jacinth
#

i'm using it in a project now and i have a small gap as well. the yellow ring is showing the radius + 0.1

stiff jacinth
#

check the demo and see if the character model (capsule) scale is different. other than that all i can suggest is to copy what's in the demo scene and modify it one bit at a time to get what you want, making sure it works after each change

pure berry
dapper cave
#

11 seconds hiccup shortly after play on assetdbv2 out of date asset processing. What causes that?

untold moth
#

It also seems to be partially triggered by profiling itself I think. Is that with deep profiling on?

#

You can see the EditorPerformanceTracker call in the middle of the stack.

dapper cave
#

I'm thinking HotReload is the cause

untold moth
#

I'd guess it's either marking some assets(shaders?) as dirty every time or something like that.

untold moth
#

Yeah. The real question is why does it need to run it every time.

dapper cave
#

ASE is old crummy code, I pinged the devs

untold moth
#

It's either a bug/inefficiency in the plugin or simply by design.

dapper cave
#

hotreload used to have a major problem forgetting many small changes and they probably bruteforced it in the last release

untold moth
#

Perhaps

burnt epoch
#

I forget exactly what it’s called

#

But if you look in physics tab of projects settings you can change it

#

Default contact offset

#

Its 0.01 units by default which is definitely not unnoticeable

#

Especially if you have small colliders in your game it can be a big margin

reef void
abstract hill
#

Hi everyone, I was wondering. Does ParallelWriter not work with NativeHashSets? I keep getting mixed info online but I can't seem to replicate this on myside, only NativeLists seem to work with them (this is with Unity 6 with the 2.4.3 colletions package)

bleak citrus
#

There is a separate NativeParallelHashSet class

abstract hill
#

Ah! Excellent thank you

#

This works with Burst jobs yeah?

bleak citrus
#

I'd expect so

#

I don't recall if I've ever used that one before

abstract hill
#

Awesome! Thanks, I'll give it a go ^-^

sly grove
pastel finch
#

I'm generating large meshes at runtime which are bigger than the vertex limit. Does anyone have a good blog or advice about how to split this properly into a submesh?

bleak citrus
#

the 32-bit vertex limit, not the 16-bit vertex limit?

#

4 billion vertices would be a lot of vertices!

pastel finch
#

Ah I'm on 16.... but I feel for collision, I will probably want smaller colliders anyway

sly grove
#

well - for convex colliders

somber swift
#

*triangles I believe

bleak citrus
#

I wish you could tell it to just...idk, do its best

#

decimate the model some more

hallow flax
#

I would like to inquire whether the ONNX file in the unity ML agent contains all types of learning or if it only retains the best results, Additionally, how can we filter it out if needed?

shadow hound
wet sail
#

hello, is it possible to have a script automatically get added to any scene when playing ?

#

i.e don't have to manually add it to an existing gameobject

bleak citrus
#

Yes, you can respond to a "scene loaded" event

#

Of course, you'll need to subscribe to that event first

bleak citrus
#

jinx!

echo coral
#

Snap

bleak citrus
#

my entire game starts with

#
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        private static void OnLoad()
        {
            Instance.Initialize();
        }
#

on my game controller singleton (which loads itself from Resources)

lavish plume
#

With BeforeSceneLoad is it called once or for every scene loaded?

wet sail
#

so why do i need scenemanager if i can do RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)

lavish plume
#

Might be a handy replacement for the global singleton I have so I can just play at any scene instead of loading into the menu

wet sail
echo coral
#

Reading docs is hard

bleak citrus
#

The load type just determines exactly when in the startup process the code is run

bleak citrus
wet sail
#

so if you reload scene, it doesnt fire again?

bleak citrus
#

No, because RuntimeInitializeOnLoadMethod is used to run a method as the game is starting

#

BeforeSceneLoad just means that the code executes right before Unity starts loading the first scene

wet sail
#

not sure whats the best way

bleak citrus
#

then just use RuntimeInitializeOnLoadMethod

lavish plume
pearl mortar
#

I'm going to have multiple menu's in my game that all need to stop the character from looking around with mouse look and unhide the mouse cursor. This is going to be shared code between all of these UI's that needs references to a bunch of different objects, what's the best way to structure that?

pearl mortar
#

I guess something has gone really really wrong if I have multiple UI controllers. Alright. I can do that.

#

Thanks @sly grove

bleak citrus
#

Consider a "counter" if many menus can be open at once

#

Each menu increments the counter when opening and decrements it when closing

#

Just don't mess up 😉

pearl mortar
#

That's a good idea. I haven't thought about what would happen if a player opened the escape menu ontop of something like the inventory.

lucid crane
bleak citrus
#

eh, you'd have a stack of menus if you had to close the menus in the reverse order that you opened them in

#

this doesn't imply a stack -- it's just "how many menus are open?"

pearl mortar
#

It does make some sense to store a collection of objects that are locking mouse look/keeping the mouse visible though.

#

It makes it easier to keep track of which UI is keeping mouse rotation locked and is a little more resilient against accidentally calling the lock mouse method twice or something.

#

I agree that a stack isn't nescessairly the right choice though. I can't picture a case where you would open up a new menu and close the menu behind it before closing the new menu but I could imagine it happening.

bleak citrus
#

oh yeah, a set is a decent idea

#

it also means that, when you mess up, you can figure out who's locking the damn screen!

bleak citrus
#

My game has a strictly stack-based menu controller system (and only one menu controller is allowed to be active at a time)

#

I do have other UI elements that also need to unlock the cursor, but they're handled separately

compact ingot
# pearl mortar It does make some sense to store a collection of objects that are locking mouse ...

you can do something like this (see code). The notion of a stack is irrelevant to releasing a resource, a stack is only useful if you want to pass control back in the same order as you handed it off, all you care about when it comes to things like cursor-unlock etc. is whether something blocks/claims it. A collection of claimants is irrelevant if you don't use it for anything besides counting them: https://nombin.dev/90d6951mljg0gpph4kswn9wr

humble loom
# bleak citrus my entire game starts with

sheesh that makes me feel icky lol. why would you do this rather than say like, having a bootstrap scene that additively loads your landing scene post-initialization?

bleak citrus
#

I don't see a huge conceptual difference between "there's a special scene that starts everything" and "there's a special prefab that starts everything"

#

It can't be turtles all the way down 😉

humble loom
#

true. separation of responsibilities i suppose, you can get some parallelism a little more easily but i suppose you're right. maybe i'm just conditioned to play nice with unity lol

#

i don't tend to have centralized controllers so it's less of a necessity for me. the singletons I do have usually have static event registration so i just need a little prewarm so i don't get dry fires on script execution order

pliant cypress
#

I'm trying to get a source generator working, but for some reason its failing to include the namespace it needs. The generated code looks like this:

using OwlTree; // namespace proxy factory is from
using System;

public class ProjectProxyFactory : ProxyFactory
{
    ...
}

I'm getting the error:

OwlTree.Generator\OwlTree.Generator.OwlTreeGenerator\ProjectProxyFactory.g.cs(1,7): error CS0246: The type or namespace name 'OwlTree' could not be found (are you missing a using directive or an assembly reference?)

The cs files that contain everything in the OwlTree namespace are in my Assets folder. It works just fine if I use it in a script myself.

This is what my generator dll looks like in the editor:

thin mesa
#

are you using assembly definitions in your project? and if yes, is your generator dll within the same assembly definition path as the namespace definition?

pliant cypress
#

no assembly definitions yet

#

they're all in the base assembly

pliant cypress
#

I still haven't fixed this. I found some resources on how to properly set up the csproj for the generator. I was doing it wrong, so I fixed that, but that still didn't fix the errors. I can also see that the generator is working correctly in the language server in vscode. So it's only when unity compiles is it an issue.

timber flame
#

I would like to format my codes before commiting

#

For example, it should format a class like below
First serialized field, then props, readonly fields, fields, abstract methods, unity event functions, etc.

compact ingot
timber flame
compact ingot
#

If you find the cleanup/layout settings you should find the option do automatically apply it too

#

I don’t think you can trigger it by a commit but you can run it on any folder recursively on other triggers, like save/pre-build.

halcyon flower
#

hey guys, i don't know if this falls under advanced but there were other people asking questions in the other channels and i didn't wanna post over them, if it's a problem, tell me and i'll move the request.
I'm trying to setup a "gravity switching system" but i'm having some problems with switches from -y and +y axis to -x, +z and -z axis, while for some reason +x works fine.
The problem is that my player comes out rotated in wrong direction, the objective should be to keep the player facing always the same direction after the switch but as said for the 6 out of 24 cases i highlighted above this thing doesn't work.
I know it might sound confusing so i also have a video of the problem in case that's helpful, here's my code so far:

#

i should also mention that i use controller.move to move the player: