#archived-code-advanced

1 messages · Page 24 of 1

undone coral
#

reactive property and subject are both IObserver i.e. they define OnNext

#

if you want to be pedantic you can protect your health from outside stuff mucking with it using IReadOnlyReactiveProperty

#

that way only the private things can OnNext onto it

#

the deathrattle example i'm showing you so that you can implement things like the character falling over and dying

obtuse flume
#

So when accessing ReactiveProperty does it store all of the past values too?

undone coral
#

no

#

but there are things that do that

#

in unirx

#

behaviorsubject is one of them

#

and can be used for weird stuff, or to deal with "Bugs" like "do i have to worry about what order this stuff happens in"

#

for example, a thing might have already died before you started listening for it to die

#

very tricky

obtuse flume
#

What does killedBy: source, amount: amount do?

undone coral
#

that was just naming the parameters

#

this way you could have it wait until it plays its tombstone and death animation

#

before spawning some critters

#

which is Good Game Feel

#

so you would have a bunch of IDeathrattle components and they would execute in order

#

maybe you want to NOT wait for some of them. use a bool dontAwait

#

and check it. if it's true, Async().Forget() instead of await Async

obtuse flume
#

Ok so you are just playing a death animation before you destroy, and this way you don't have to have some convoluted way to track when every single deathrattle has finished their animations?

undone coral
#

yes

#

yes!!

#

yas gaga yas

zenith ginkgo
#

You forgot your meds again

undone coral
#

lol

undone coral
#

it took only a few hours and there's already all this awesome stuff happening so i'm pretty happy

obtuse flume
#

this is exactly what i was looking for by posting here

undone coral
#

yeah, and the game looks nice

#

anyway i think this is really good ground covered and it is coming quickly

obtuse flume
#

we shouldve made a thread

undone coral
#

i like that Actor is like "my utility belt for all sorts of things i can do in the world" and you have different scripts that use those items on the utility belt

#

it's the right mix of coupled and decoupled that helps you solve problems expressively and without clutter

#

we have also so far avoided virtual which is great

#

there is a time and place for that

#

but you can solve like 99% of problems without virtual

west scarab
#

You can solve 99% of problems without anything fancy 😅

#

Everything is just a tool at the end

undone coral
#

yeah

#

i don't really mean to get too fancy

#

the point of all this really is to make your code look like an english language description of how the thing works.

west scarab
#

I'd argue reactive programming is already "fancy"

#

there's a lot of stuff going on

undone coral
#

we can stick to async

#

i agree reactive can be weird if you don't do the web development thing also

misty glade
undone coral
#

lol

west scarab
#

I don't think it's necessarily weird, it's just a style of programming that some people like and others don't

#

Maybe weird when first getting into it I guess?

misty glade
#

I saw an @ but wasn't around and lost the thread.. in and out for the evening - what was I supposed to comment on DrP? 🙂

obtuse flume
zenith ginkgo
#

Death to UniRx

#

Sorry, my bad habits flaring up again

undone coral
#

lol

west scarab
undone coral
#

@obtuse flume well keep us posted on how things go and make sure to GIF & document some gameplay 🙂

obtuse flume
misty glade
#

sync'd drum track overlaid on main track after the login button is clicked - I'm currently just playing these at the same time and turning the volume up to 100% on the second track - should I chain these to each other? and if so, thoughts on how?

#

(they aren't two separate tracks- they're a naked drum track and a background track)

#

It sounds fine "on my machine" but I worry that maybe there's a way these can get desync'd?

rapid flume
thorny lion
#

is zenject popular?

compact ingot
#

It’s fun if a non-trivial message gets through. Makes it all worth it.

compact ingot
thorny lion
#

zenject seems to be super advanced tool that I am to early to put my hands on

#

just look at the import files. What is it all for? The documentation of zenject is longer than a thousand lines

#

what is the purpose of dependency injection in unity then?

#

unless FindObjectOfType<x>() does the stuff?

compact ingot
#

there are many ways to do this, the simples one is to manually do it when instancing a class., the unity scene hierarchy and object references are also dependency injection and sort of a framework for that

#

a framework like zenject just adds a bunch more options and flexibility to it at the cost of more boilerplate code and potentially a very complex dependency resolution config that defeats all the benefits you gain from the decoupling

#

you need to figure out if your project and workflow and team organization benefits from using a dependency injection FRAMEWORK (hint: most game projects don't)

#

all code generally benefits from dependency injection (with or without a framework) that is done as part of implementing the inversion of control principle

thorny lion
#

my brain is going to hurt from all of that (omg)

#

anyways thank you

#

now I realise I do not need zenject because it is overloaded

compact ingot
#

yes, if you don't have a perceivable problem regarding coupling/decoupling and modularity of your code, you don't need it

thorny lion
#

hm you seem to be concerned a lot about it, can I ask you? My game has the only scene and a mono script called Themes.cs that handles themeing. I used to believe zenject would help me denote Themes.cs as a Singleton and easily refer to it in other scripts (instead of FindObjectOfType<Themes>().someField)

#

I know the rule of objects existence in which unique objects (just like Sun, Moon, the Earth) are not limited to be so and speaking so can become numerous

#

even you as a human can have a copy (purely identical instance) though the chance for it is 0.00000000000001%

#

such a rule dusts the concept of singletons in games, such as "there can be only one player at once". No. There can be many, but in our game it does not occur

#

respectively in my game I have a Themes.cs and I wish I could refer to its only instance from any script

#

Static? No. I need it to be a Mono

#

Singleton pattern? I hate it

#

FindObjectOfType<>()? Works perfectly but I hate doing it all the time

modest vale
#

What is the syntax for setting a variable to either <a> or <b> with faster if statement

compact ingot
thorny lion
#

do you know what a single mono per scene is?

#

like a god object but it handles events only within its scope

#

in the case of my Themes.cs there are only theme-related events and methods it performs

#

I don't need 2 of Themes.cs Monos in my scene or otherwise it will break the game

#

I want to assure my game I only have 1 mono and to have access to this mono without FindObjectOfType or inspector variable assigning

shadow seal
#

You can do that with a singleton

#

A singleton doesn't need FindObjectblah like you keep putting in

#

You have a static field which gives you a reference, the first instance fills in that reference, any other instances that appear should see that it's already filled and destroy themselves

quaint swan
#

how can i make that the wheels turn in the way the car is going

lavish sail
quaint swan
lavish sail
zenith ginkgo
# quaint swan

Assign Input.Axis * speed; to one variable. then assign that variable to all wheels

#

calculating it 4 times, is poor form

quaint swan
#

no seriously ?

#

just read the other messages plz

quaint swan
#

but there is a problem

#

like for my speedometer the speed is always positive

#

so idk

zenith ginkgo
#

you have two ways to find out if you're going backwards or not

#

this. if its < 0, you're going backwards, or the cars velocity

quaint swan
#

i don't really understand

#

what would be < 0 ?

zenith ginkgo
#

the return value of your input

thorny lion
shadow seal
#

I have no idea why, I don't use them often but I think a lot of it is down to people's opinions

livid kraken
quaint swan
livid kraken
#

Singletons are perfectly fine if used correctly

quaint swan
#

formula x -1

quaint swan
zenith ginkgo
#

you should know what a return value is

thorny lion
quaint swan
#

but what i wrote can work no ?

zenith ginkgo
#

what

quaint swan
#

so its good if i write this like if(Inupt.....(Vertical) < 0):

#

formula x -1

zenith ginkgo
#

theres more to it than that...

#
float movementDirection = Input.GetAxis("Vert");
bool isMovingForward = movementDirection > 0;
A.torque = movementDirection * speed;
B.torque = movementDirection * speed;
C.torque = movementDirection * speed;
D.torque = movementDirection * speed;```
#

thats all im going to give you

shadow seal
thorny lion
#

hm fine that's a saying

zenith ginkgo
quaint swan
#

ok thanks you man

autumn topaz
#

I changed the mesh of my rig and now its not working. its saying: System.InvalidOperationException: The TransformStreamHandle is invalid. Please use proper function to create the handle.

obtuse flume
#

Async stuff

urban sequoia
autumn topaz
#

I fixed it now, you just have to rebuild the rig but originally I just removed the model

rugged radish
#

I have a multipass compute shader which can run with a dynamic number of passes that is unknown on the CPU side in advance
current implementation has to readback the output after each pass and check if the task was completed on the CPU
are there any cheaper ways to accomplish this ?
currently I plan to add a 1-element buffer which tells the CPU that the task is done, but this still means requesting a readback after each pass and I doubt it'll save that much time

modest vale
#
aspectRatio.x = Mathf.Cos(dir) * vector.x - Mathf.Sin(dir) * vector.y;
aspectRatio.y = Mathf.Sin(dir) * vector.x + Mathf.Cos(dir) * vector.y;

what is wrong about this rotation matrix

somber swift
modest vale
#

yes indeed

#

it doesn t work for me

#

I hate rotation matrix

somber swift
versed warren
#

hacing trouble understanding what this error log means

#

Invalid allocation label passed to UnsafeUtility::Free
UnityEngine.StackTraceUtility:ExtractStackTrace ()

#

I'm using a networking script to look for servers on a local network

#

whenever I send data to the found server this error is logged

somber swift
#

@modest vale are you sure you are not confusing radians and degrees? Btw wdid you know that represents counter clockwise rotation, not clockwise. Otherwise that should work

modest vale
#

I think it works now, the problem is in the function that I wrote I *= instead of = the rotated position

tame thistle
#

When using the FromToRotate function, how do I preserve my other axis?

sly grove
tame thistle
sly grove
tame thistle
#

Whenever I set my transform.up to the normal of another surface, the y axis is reset

#

i want to rotate the transform.up to the normal, without it turning my object to the same direction

#

should i word it better

sly grove
scenic forge
#

For people that are looking to use additional files in source generators, I took a stab at it and got it working:

  • Add -additionalfile:path/to/file to additional compiler arguments.
  • Implement OnGeneratedCSProject in an editor script and append <AdditionalFiles Include="path/to/file" /> so it works in your IDE too.
  • It doesn't seem like Unity can pick up changes to additional files, you can optionally make an editor script that whenever additional files change, generates a stub .cs with a line of random comment inside to force Unity to recompile and thus rerun SG.
#

Some unresolved problems I have:

  • I could not get generation time dependencies to work with SG, which is really unfortunate because parsing YAML/JSON and generating code based on result is a pretty common pattern.
  • Not sure if it's specific to VS Code, it cannot pick up changes to additional files even with source changes. It seems like I have to restart O#.
#

I'll say what everyone says when they work with SG: "this sucks and could be so much better, but it was still worth migrating to it"

urban warren
#

Is it possible to use an interface as the type for a generic with the struct constraint?

public class Example<T> where T : struct { }

public interface IInterface { }

// Is this possible in some way???
new Example<IInterface>();
undone coral
#

do you mean public class Example<T> where T : IInterface, struct

urban warren
undone coral
undone coral
#

okay

#

you can always cast it to the interface

#

you can use a struct that implements your interface

#

then give it to native array

#

what am i missing here?

#

what is the specific code you want to have

urban warren
# undone coral what is the specific code you want to have

This is a bit changed as it is part of a larger system, but basically what I am doing

struct CustomJob : IJobFor, IGenerator
{
  public NativeArray<IGenerator> Generators;

  public void Execute(int jobIndex)
  {
    for(i Generators)
      for (j Generators[i].Length)
        Generators[i].Execute(j);
  }
}

interface IGenerator : IJobFor { }
undone coral
#

i see

#

why would it be a native array though

#

what is the advantage here? what am i missing

urban warren
undone coral
#

why would this have to be a burst job, isn't it delegating to other jobs? potentially themselves burst?

#

hmm

#

i see why you are wanting to use IJobFor

#

i guess this is a little confusing to me, you can declare a static method elsewhere

#

and use it in your custom job

#

for the generators

#

a method and an interface with a single method are duals

#

jobIndex - where is this used?

urban warren
undone coral
#

oaky

#

if it's essential to schedule things this way

#

you can have a native array for each type of input data for the generators (so only structs)

#

or 1 native array of 1 struct type that is sufficient for all your generators

#

you would have an enum in that struct that corresponds to which static method you want to execute (i.e., instead of having a generator be a class, it's a single static method)

#

does that make sense?

urban warren
#

Yeah, I guess that would work. But boy does that feel real ugly

undone coral
#

i think you can also call the jobs directly

#

instead of via na rray like this

#

in code

#

because you're not the only person who wants to run a ton of different jobs all at the "same time"

urban warren
undone coral
#

can't you just schedule each generator

#

and it will work the same way as what you are doing now, which is trying to schedule 1 job that then calls all the generators via the index

#

it will work out the same

urban warren
#

How many jobs 'can' you schedule at a time?

undone coral
#
class GeneratorPass : MonoBehaviour {
  List<IGenerator> generators = new();
  JobHandle previousFrameJobs;
  JobHandle nextFrameJobs;
  void Update() {
   previousFrameJobs = nextFrameJobs;
   var handles = generators
        .Select(generator => generator.Schedule())
        .ToArray();

   nextFrameJobs = JobHandle.CombineDependencies(handles)
   // wait for the jobs you scheduled previous frame to complete
   previousFrameJobs.Complete();
   JobHandle.ScheduleBatchedJobs();
  }
}

interface IGenerator : IJob { ... }

@urban warren

#

you can then all.Complete() in the right place

#

wherever you want

#

wherever you need to wait for all the generators to finish

#

if you have 8 cores, you'll have 8 workers, and they'll start chewing through all the scheduled jobs

urban warren
#

I will explain exactly what my scenario is @undone coral.
I am working on a mesh manipulation thing. I have a stack of modifiers (I called them Generators in my example earlier)
They can be something like "Bend", or they could be "Scatter"

This is where it is getting tricky. "Scatter" creates multiple instances of the mesh, however parameters can be randomized so each instance needs to be generated on its own, not just copied.

So if a "Scatter" modifier creates 10 instances, then all the modifiers above the "Scatter" modifier needs to be executed for each instance.
It gets more tricky because you can have multiple "Scatter" modifiers.
So another one after the first that creates 10 instances of those 10 instances. So 100 instances, and each need to have every modifier run on it.

undone coral
#

jobs are scheduled and batched onto a queue

#

you can look at hdrp, it schedules hundreds of jobs sometimes

#

every frame

#

the number of jobs isn't super important

#

you prob want each generator to be an IJobFor of its particular work items

austere jewel
undone coral
#

rather than have 1 IJobFor that is your poor man's scheduler

urban warren
urban warren
undone coral
#

so i don't see lots of unusual performance issues

#

it works how i expect it to, which is "if it's burstable it's fast, otherwise it's a work queue for multithreading"

urban warren
cerulean sky
#

Hello!

#

I have an issue in my game where UdpClient after some time stops receiving any sort of data at all, and I don't know why

#

The hosting player has a UdpClient receiving in a loop and and that loops is not broken, it doesn't exceipt, and I can see with wireshark that packets are still coming forth. Yet the .Receive still blocks until timeout and does not catch any data

#

netstat -ano still shows Unity.exe listening on the correct UDP port, so there's no reason to believe packets are not being transmitted to it

#

I've spent a few hours yersteday night trying to understand where the problem could be and I can't find it. I get the issue after a few hundreds of packets or so, quite randomly, and once the host is in that state of "not receiving anything" nothing solves it except exiting play mode and playing again. Not even destroying/recreating the udpclient/socket fixes it

#

Here is my receiving code - which I believe should be catching anything?

            protected async Task Listen()
            {
                try {
                    while (!stopListening) {
                        try {
                            var data = Receive();
                            if (!data.HasValue) continue;
                            [...]
                        }
                        catch (SocketException e) {
                            if (!Game.i.Network.IsMaster) {
                                LowDebug.LogWarning($"Remote killed connection:\n{e}");
                                break;
                            }
                        }
                    }

                    Destroy();
                    LowDebug.LogWarning("Network closed gracefully");
                }
                catch (ObjectDisposedException) {
                    Destroy();
                    LowDebug.LogWarning("Network killed brutally");
                }
                catch (Exception e) {
                    LowDebug.LogError("Error while trying to listen:\n" + e);
                }

                LowDebug.Log($"Broke out of listening loop for {this}!");
            }

            private NetworkMessage? Receive()
            {
                var timeToWait = TimeSpan.FromSeconds(5);
                byte[] data = new byte[0];
                IPEndPoint remoteEP = null;

                var asyncResult = client.BeginReceive(null, null);
                asyncResult.AsyncWaitHandle.WaitOne(timeToWait);
                if (asyncResult.IsCompleted && client != null) {
                    try {
                        data = client.EndReceive(asyncResult, ref remoteEP);
                        // EndReceive worked and we have received data and remote endpoint
                    }
                    catch (Exception ex) {
                        LowDebug.LogWarning($"Endreceive: {ex}");
                        // EndReceive failed and we ended up here
                    }
                }
                else {
                    // The operation wasn't completed before the timeout and we're off the hook
                }

                if (data.Length <= 0) {
                    if (Game.i.Network.TraceNetworkCommunication) {
                        LowDebug.Log($"[network] Receive timeout - nothing was received");
                    }

                    return null;
                }

                [...] // Lots of code to process the data and return it
            }
#

What happens is that the Receive() call keeps timing out after 5 seconds (as it should when no data is received at all) and returns null. Exactly as if no packets were received. The thing is wireshark indicates there are packets coming in, to the correct port and address, and so they should be caught by Receive (they way they do for a while before it abruptly stops working)

#

Firewalls on both machines are down so it's not that

#

If anybody has an idea of what it could be (maybe a unityeditor bug where it eats the packet under some precise circumstance?) i'm all ears UnityChanSleepy

cerulean sky
#

The easiest way I repro it is :

  • Both computers (host and client) run the game on unity editor
  • Client joins the game, everything works normally
  • Client exits play mode (by clicking the ▶ button on unity)
  • Hosts sees client stops responding and kicks it out of the party
  • Client enters play mode ( ▶ )
  • Client tries to join, sends party join packets, but the host is not receiving a single one of them
  • Wireshark shows the packets are received by the host machine
  • Netstat shows the host machine has Unity.exe listening on the correct port
  • Logging on the host machine indicates the UdpClient is up and timing out regularly without any exception, error, or otherwise weird thing
upbeat path
cerulean sky
#

Yes, having written UDP/RUDP network games for the past three years I do know that, but since the packets are actually received on the machine (as Wireshark sees them) I'm figuring out a 100% loss rate between the network driver and the UdpClient is not normal even for UDP and is more likely to come from either my code, a .NET bug, or a unity bug

upbeat path
#

tbh I would break up your Receive method so your while loop knows immediately if that has been received or not and then process that data separately

cerulean sky
#

The behaviour you're describing is the current behaviour of the code I provided

upbeat path
#

Does not look like it from

 [...] // Lots of code to process the data and return it
cerulean sky
#

I'm sorry but the answer "tbh i would break out the code that is not provided and that i imagine being wrong" is not being very helpful to me

fresh salmon
#

Oh

cerulean sky
#

Here is the full receive function but I doubt the part I omitted was relevant to the problem I describe

            private NetworkMessage? Receive()
            {
                var timeToWait = TimeSpan.FromSeconds(5);
                byte[] data = new byte[0];
                IPEndPoint remoteEP = null;

                var asyncResult = client.BeginReceive(null, null);
                asyncResult.AsyncWaitHandle.WaitOne(timeToWait);
                if (asyncResult.IsCompleted && client != null) {
                    try {
                        data = client.EndReceive(asyncResult, ref remoteEP);
                        // EndReceive worked and we have received data and remote endpoint
                    }
                    catch (Exception ex) {
                        LowDebug.LogWarning($"Endreceive: {ex}");
                        // EndReceive failed and we ended up here
                    }
                }
                else {
                    // The operation wasn't completed before the timeout and we're off the hook
                }

                if (data.Length <= 0) {
                    if (Game.i.Network.TraceNetworkCommunication) {
                        LowDebug.Log($"[network] Receive timeout - nothing was received");
                    }

                    return null;
                }

                var buff = new Queue<byte>(data);
                if (Game.i.Network.TraceNetworkCommunication) LowDebug.Log("[network] =>>> Received " + buff.ToArray().Length + " bytes from " + remoteEP.Address.ToString() + " <<<=");

                return new NetworkMessage(
                    dequeued: buff.Dequeue(),
                    identifier: BitConverter.ToUInt16(new byte[] { buff.Dequeue(), buff.Dequeue() }, 0),
                    data: buff.ToArray(),
                    sender: remoteEP.Address
                );
            }
upbeat path
#

you want your while loop to be as fast as possible. So when you get data in you process that data in a seperate thread if you can rather than blocking this thread which could prevent new packets being received

cerulean sky
#
  1. Blocking the network thread does not prevent new packets to be received, the packets are queued in a buffer in the socket stream and no data would be lost if that were to ever happen
  2. The issue you point out is irrelevant to the problem that I'm having & describing
cerulean sky
#

Okay I got rid of UdpClient and used C# Sockets instead, still the same issue occurs! With the exact same repro steps

#

Packets stop coming through

proven venture
#

is there a way to access the raw audio buffer of an audio source? i have a native library that writes little/big endian samples to buffer that i'd love to be able to use with unity's audio mixing (instead of it just writing to the process's audio buffer)

#

in case you're wondering, i'm using fluidsynth to play back a midi, it's working fine but i'd like it if spacial audio works

winter yacht
proven venture
#

ok, AudioClip.Create with stream=true and the PCMReaderCallback set to

fixed (float* dataPtr = data)
{
  fluid_synth_write_float(_synth, data.Length / 2, dataPtr, 0, 2, dataPtr, 1, 2);
}

it's now working

cerulean sky
#

But I'm definitely feeling like the socket is being turned into some garbage state that prevents it from receiving data, the problem is I can't find how or why and i'm not getting any exception or error

#

It happens brutally for no reason, and since i'm doing RUDP whenever the host stops "receiving" data it also drops every client because to its point of view no packets get confirmed anymore, so it's very noticeable whenever it happens - and it happens randomly

calm ocean
#

What's the difference between UniTask and UniRx?

#

I could be wrong but it looks like UniTask has all the reactive programming like UniRx

lunar raft
flint sage
#

You gotta add a refernce to your game assembly

autumn topaz
#

how do you get all the agents currently on a navmesh from its navmeshsurface?

lunar raft
# flint sage You gotta add a refernce to your game assembly

yeah, I got that impression and there's even an example where one sets up a "GameAssembly" Assembly definition (which the Unity Test Framework docs seems to leave out).

But what I don't know is how the Assembly Definition is associated with the code that I've written. Is it the location of the file? Is it something else? It doesn't seem to be any of the properties in the Inspector values.

flint sage
#

No, you create your own asmdef for the game code

sly grove
lunar raft
sly grove
#

the file grabs all source code within the directory it's in (and subdirectories) and puts them in an assembly

lunar raft
flint sage
#

Yes

#

You also shouldn't be shipping tests with your game hence the distinction

lunar raft
#

The Unity documentation is kind of light on these details. I'm gonna go make the suggestion that they update them.

undone coral
#

it's one of those things where i look at the source and it would be easier to rewrite this little part to do the thing you want, instead of trying to understand how what you've written might have this weird bug

lunar raft
#

@sly grove @flint sage Thank you. 🙂

last acorn
#

Hello. My first msg here 🙂 i'm wondering if anyone went through the process of migrating their project from built-in assemblies to asmdef?
Specifically i'd like to know about compatibility with existing asset bundles (i assume that this transition breaks their compatibility with the built player).

undone coral
#

asyncResult.AsyncWaitHandle.WaitOne(timeToWait); why are you doing this? @cerulean sky

undone coral
tame thistle
#

Sorry if wrong chat, but if i am trying to make a character controller using raycasts so that the character can walk up walls + walk around a 3d cube, what would the best setup of raycasts + method to determine the normal?

last acorn
undone coral
last acorn
#

i thought maybe someone went down that road before

undone coral
# last acorn i thought maybe someone went down that road before

i think you would have to contact a unity support person to get a definitive answer. here is a thread illustrating the confusion on the matter: https://forum.unity.com/threads/asset-bundle-cannot-find-scripts-from-assembly-definition-files.531804/

#

they're going to tell you to test

#

good luck out there 🙂

#

i see the GUIDs are stripped, so it will still be buggy imo

#

imo, don't use asset bundles across versions @last acorn

dapper cave
#

CC

old swallow
#

Hey, anyone have any clue how to reset prefab variables?

Resetting added / removed GameObjects and Components was supper easy with "PrefabUtility.GetAddedGameObjects()", "PrefabUtility.GetAddedComponents()" and "PrefabUtility.GetRemovedComponents()".

But there is nothing like that for component variables! There is "PrefabUtility.GetPropertyModifications()" but it returns "PropertyModification" witch has no "Revert()" function and the "RevertPropertyOverride()" accepts only "SerializedProperty"!!!!!

I have been trying to do this like 2h now and the Unity documentation is literally useless with all of these functions?!?!?!?
Here is the code: https://pastebin.com/eFQZRG8e

jolly token
old swallow
#

i tried to use the "PropertyModification.target"

#

but something was wrong with it

jolly token
#

new SerializedObject(target) ig

#

Then find with path

old swallow
# jolly token Then find with path

This just trows a bunch of errors:

foreach (var item in UnityEditor.PrefabUtility.GetPropertyModifications(RootObject))
{
     var serializedobject = new UnityEditor.SerializedObject(item.target);
     var serializedProperty = serializedobject.FindProperty(item.propertyPath);

     UnityEditor.PrefabUtility.RevertPropertyOverride(serializedProperty, UnityEditor.InteractionMode.AutomatedAction);
}

"ArgumentException: Calling apply or revert methods on an object which is not part of a Prefab instance is not supported."
but i have an idea how to fix it

old swallow
jolly token
old swallow
#

for each changed field

jolly token
old swallow
#

yes and no

#

before I just looped through every object and reset changes but it had a side effect of making the icons in the hierarchy disappear and not allowing me to rename the objects in hierarchy

#

this function is run every frame

#

so resetting changes made hierarchy refresh a lot

#

thus the side effects

#

now im thinking about finding the changes and only if they exist resetting them

#

i might be overthinking it again like usual lol

jolly token
old swallow
#

"What is RootObject here, is it prefab instance?" yes

jolly token
cerulean sky
# undone coral it's one of those things where i look at the source and it would be easier to re...

what do you mean? where is it not doing the thing I want ? 😮
I rewrote it in the meantime to use sockets anyway

            private NetworkMessage? Receive()
            {
                byte[] buffer = new byte[2048];
                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort);

                int bytesReceived = socket.ReceiveFrom(buffer, ref remoteEP);
                if (bytesReceived <= 0) {
                    if (Game.i.Network.TraceNetworkCommunication) {
                        LowDebug.Log($"[network] Receive timeout - nothing was received");
                    }

                    return null;
                }

                // Truncate
                byte[] data = new byte[bytesReceived];
                Array.Copy(buffer, data, bytesReceived);

                return new NetworkMessage(...);
            }
            protected async Task Listen()
            {
                try {
                    while (!stopListening) {
                        try {
                            var data = Receive();
                            if (!data.HasValue) continue;
                            if (Game.i.SimulateBadNetwork && new Random().NextDouble() < 0.3f) continue;

                            [...]

                            _ = Task.Run(()=> onReceiveData?.Invoke(data.Value));
                        }
                        catch (Exception e) {
                            LowDebug.LogError("Error while trying to listen:\n" + e);
                        }
                    }

                    Destroy();
                    LowDebug.LogWarning("Network closed gracefully");
                }
                catch (ObjectDisposedException) {
                    Destroy();
                    LowDebug.LogWarning("Network killed brutally");
                }

                LowDebug.Log(...);
            }

problem is still exactly the same! The socket stops "hearing" data even though it's still listening, after some random while

old swallow
#

the point of the script is to make sure an object never has overrides

#

ever

#

and i also hide the children using "hideFlags"

jolly token
old swallow
jolly token
#

OnValidate can cover some cases but "to make it never has override ever" sounds tough
I wish there was built in feature like that lol.

#

'Lock' instance except some property or such

old swallow
#

Here is the full code:
Runtime script: https://pastebin.com/RaHnRw6i
Editor script: https://pastebin.com/bvJLH5jk

old swallow
#

the prefab script runs every time gizmos get drawn and every frame if the component is at least once not collapsed

jolly token
old swallow
#

probably not bacause i disabled hideflags while testing

#

with hideflags i cant even make the overrides

#

but just in case i still want to reset them

#

@jolly token bruh...
"GetObjectOverrides" that function works just like the other 3 that were easy but works with variables

#

dumb unity

#

no

#

no no no

#

dumb me

#

well...

#

thx for the help anyways

#
        private void RevertChanges(GameObject RootObject)
        {
            foreach (var item in UnityEditor.PrefabUtility.GetAddedGameObjects(RootObject))
            {
                item.Revert();
            }

            /*foreach (var item in UnityEditor.PrefabUtility.GetRemovedGameObjects(RootObject))
            {
                item.Revert(); // You can't remove GameObjects from prefabs anyways
            }*/

            foreach (var item in UnityEditor.PrefabUtility.GetAddedComponents(RootObject))
            {
                item.Revert();
            }

            foreach (var item in UnityEditor.PrefabUtility.GetRemovedComponents(RootObject))
            {
                item.Revert();
            }

            foreach (var item in UnityEditor.PrefabUtility.GetObjectOverrides(RootObject))
            {
                item.Revert();
            }
        }
#

this workd perfectly

jolly token
old swallow
#

hahaha

#

I guess so

calm ocean
#

In UniRx, if I subscribe to a reactive property, am I also responsible for disposing? For example

        private void OnEnable()
        {
            _virusReactivePropertyDisposable = _virusReactiveProperty.Subscribe(_playerVirusMeterUI.SetVirusPercentage);
        }

        private void OnDisable()
        {
            _virusReactivePropertyDisposable.Dispose();
        }

Is the on disable here necessary?

#

For context, this is inside a MonoBehaviour

jolly token
#

If the reactive property itself is disposed or GC'd, then you don't have to dispose subscriptions.

#

For UI update I prefer using CompositeDisposable so I can clear related subscriptions at once before resubscribing

calm ocean
shut owl
#

Hi, so I am trying to create ai and it was going fine but now I have problem after adding some stuff that allows for the enemy to move towards the player when the player enters their FOV. The code also includes stuff that allows for the enemy to go to specific locations. the problem now occurs when the enemy can see the player and I cant find a solution. The console reads that the operation caused a stack overflow. if you think you can help me, please dm me. Its easier that way for me.

pliant crest
#

stack overflow is when you recursively call a method too deep

shut owl
#

@pliant crest Thank you for the reply. Thank you for telling me what a stack overflow is. I found the problem because of that and now everything is working the way I need it too

mint sleet
#

Is it possible to make a newer commit to the initial commit of the repo?

#

I do not want to see others than the marked version. (I know that creating a new repo and pushing it into it is a solution, but I want to learn if it is possible)

long ivy
#

squash the commits using interactive rebase. As long as nobody else has the history (it sounds like they don't), you can rewrite history this way

lofty quail
#

Hi,
I remember a website with a huge checklist to improve performance. I didn't remember the name, do you have any idea ?

lofty quail
#

But now that isn't free anymore

turbid tinsel
#

Hi, is there a way to write something similar to
using Random = UnityEngine.Random;
but for 1 method only? Instead of an entire class?
I want it specifically for

using SizeOf = System.Runtime.InteropServices.Marshal.SizeOf;```
#

which is a method

#

I need it because I have no clue how to name System.Runtime.InteropServices.Marshal...

orchid marsh
#

Why not Marshal?

austere jewel
#

What do you mean? Is there a reason to not just using System.Runtime.InteropServices;?
And do Marshal.SizeOf?

#

You can call using static System.Runtime.InteropServices.Marshal; to import all the members of that class, but it can muddy the water and sacrifice clarity

winter yacht
turbid tinsel
turbid tinsel
winter yacht
rugged radish
#

Does ComputeBuffer.SetData perform the work at the moment you call it, or it just puts the copying operation into some queue to be executed later with the next Dispatch ?

turbid tinsel
#

It does it immediately as far as I know

#

Also, there's a lot of overhead, so 3 calls are MUCH slower than 1 call with 3 times more data

#

even if they're right one after another

rugged radish
undone coral
indigo citrus
#

Hello I had to ended task the unity after doing something I didnt want to while it was loading and I think the scene got corrupted or something

#

The scene will keep like this

regal olive
indigo citrus
#

No

#

I forgot to say it

#

Its when I try to enter in the scene

#

I am in another scene and when I double click it boom just stays there

#

Something that before would just take a few seconds doesnt load at all

#

I can send the scene file if needed

regal olive
#

no idea but u might want to check if the backup scene has it

indigo citrus
harsh oyster
#

Uhm how come the terrain layer is very faintly painted??

indigo citrus
#

The scene just doesnt open

cinder cargo
#

hi, im making a dungeon, but when It generates the rooms can generate inside of other ones, I tried making a trigger collision (and normal collision) detection to check if it could spawn but I couldnt get it to work. Is there any other way to stop generation if its inside of another object?

#

not sure if this is the right area to ask this question...

compact ingot
cinder cargo
#

so simply doing this as it generates isnt an option?

compact ingot
sly grove
cinder cargo
#

yeah i posted it in here without realizing at the time

flint sage
cinder cargo
#

also I had it at OnCollisionEnter and it didnt do anything either

cinder cargo
#

ok ill check that out thanks

grizzled lake
#

Is there a Unity API call to get a collection of the available tags in the project?

I can use this in the editor:
UnityEditorInternal.InternalEditorUtility.tags but I don't think it's available at runtime.

Is there a runtime version?

sly grove
rigid dagger
#

I am having a problem with some play mode tests, I would like to completely, completely reset my scene between tests, but I have some problematic DontDestroyOnLoad objects set by some third party packages (and possibly static fields as well). Anyone know how I can deal with this?

jolly token
#

Unless you run test separately per scene

rigid dagger
jolly token
rigid dagger
#

Yeah, and I'm assuming that is just impossible

jolly token
#

So either manually reset your static states
Or execute each test separately (not just loading other scene)

#

I think second option could be automated but with painful and long process 😌

rigid dagger
#

Yeah, it will likely be running each independent

#

Yeah agreed

#

I'm almost making my own test runner at that point

jolly token
#

So it might be better to just have common static method to destroy all DDOL objects and reset static variables

#

And run that before each test

rigid dagger
#

I think I'll look at that. I halfheartedly tried destroying the ddol objects at one point but I'll revisit that.

regal olive
#

Hello people.

I have this rope simulation I have been trying to make which resembles the one from Profundum (2019): https://forums.tigsource.com/index.php?topic=64389.msg1389271#msg1389271 -- this system uses several connected rigidbody capsules connected with Configurable Joints, as has been used by the devs of Profundum themselves.

The main aim is to make sure I am able to make knots on this rope.

In my case, I have made it so that the rope segments are spawned with a bias so that the simulation doesn't jitter. However, this causes the rope segments to slip through the spaces between segments, essentially making it impossible to knot the rope. I haven't been able to get rid of the spawn bias without destabilising the simulation entirely.

The configurable joints are set up exactly in the way as shown in the devlog post.

The capsule and rigidbody data are in the screenshots below.

Additional Details
The project uses the Oculus VR Interaction SDK and as such has some other components on it. I have kept the Physics Grabbable component disabled as it causes my segments to become unresponsive to grabbing entirely. However, in every other way, this part of the simulation is working as expected.

#

Capsule Collider

#

Rigidbody

#

A single segment.

#

Rope segments in arrangement in and out of play mode -- notice the gap between each segment.

wooden bronze
#

How can I save a collider of any type to a variable and then spawn a new object with that exact type and values. Seems like you cant just use Collider because then it down casts and removes all of the info (like the mesh for a mesh collider) and on top of that I dont think it saves its type so I cant just add component with the same type as it. Do I have to just make a variable for each collider type and then check which ones are null and which ones it filled in?

#

because that seems redundant

kindred tusk
#

Maybe if you share the code you're stuck on it will be easier to answer your question.

#

You can't instantiate a component on its own, you need a gameobject.

wooden bronze
#

here one sec

#

saves each object to this struct

public struct TickCollider
    {
        public Vector3 position;
        public Vector3 rotation;
        public string tag, layer;
        public Collider AttachedCollider;
    }
kindred tusk
#

That's not a collider, it's a struct.

#

Oh, I see.

wooden bronze
#

then I loop over each struct and need to spawn a gameobject with the same collider values

kindred tusk
#

You can do this if you want:

public struct TickCollider<T> where T : Collider {
  public Vector3 position;
  public Vector3 rotation;
  public string tag, layer;
  public T AttachedCollider;
}
kindred tusk
#

You need to show the whole code

#

Like where exactly is the line where the problem arises?

#

Because what you have should work

wooden bronze
#

just in adding the correct collider to the object

#

and then copying over the values (just need to do each one so easy)

kindred tusk
#
foreach (var t in tickColliders) {
  var instance = Instantiate(t.AttachedCollider, t.position, t.rotation);
  instance.tag = t.tag;
  instance.layer = LayerMask.NameToLayer(t.layer);
}
#

That will be fine

wooden bronze
#

really?

#

will try

kindred tusk
#

What were you trying before?

wooden bronze
#

someone typeof thing I couldn't figure out

#

with trying to add a component to a new gameobject where that component matches the type of the AttachedCollider

kindred tusk
#

So... are you trying to instantiate a new object or attach a new collider to an object?

#

And does the object have a rigidbody?

wooden bronze
#

no

#

just need the collider position and mesh and size and stuff

kindred tusk
wooden bronze
#

no rigidbody

wooden bronze
#

new object and then attach a new collider to it with the same values as the AttachedCollider

kindred tusk
#

Okay.

#

Did you consider making the colliders on child objects?

#

Then you can just duplicate the child objects

#

If you attach a kinematic rigidbody it will treat the colliders as if they're on the root object.

#

That's the easiest way to do it in Unity

#

Duplicating individual objects is hard

#

Colliders don't have tags or layers, so it doesn't really make sense

#

What you're doing

undone coral
wooden bronze
#

lag compensation for multiplayer, basically saves all networked objects colliders each tick and then on the clients request (such as for shooting) tells the server I shot here, then the server sees how far the client is behind it, goes back to that tick, spawns the colliders, does the raycast hit stuff on the server side and passes back the hit info to the client

kindred tusk
#

When you want to resim the shot, move the physics player back to its old position, then bring it forward to its "current" position before running the next input frame

#

You shouldn't need to construct new objects for that

regal olive
gray zinc
#

Is there any way to store System.Action<InputAction.CallbackContext> in a terser delegate? I tried making a delegate "delegate void ControlAction(InputAction.CallbackContext context)" but when I tried assigning it to an InputAction it said it couldn't cast ControlAction to System.Action<InputAction.CallbackContext> (even though the parameters are identical)

#

Basically I'm trying to shorten a really long Action<T> by storing it/aliasing it in a named delegate (e.g. MyDelegate instead of Action<Really.Long.Parameter.Name>)

#

Also, I don't need the shorter name delegate to be generic because it'll only be InputAction.CallbackContext as the parameter for the action.

#

I'm currently just using an alias "using MyDelegate = Action<blah blah>" but if it would be possible to declare a delegate inside my namespace and then just use that instead of having to put the alias in every file I want to use it in that would be much better.

random dust
#

So just assign your delegate to the ControlAction instead of assigning it as an Action and storing that as the ControlAction instead

regal olive
misty walrus
#

Is anyone familiar with implementing custom android themes? I have this:

<resources>
    <style name="CustomTheme" parent="@android:style/Theme.NoTitleBar.Fullscreen">
        <item name="android:windowBackground">@android:color/black</item>
    </style>
</resources>

in a file next to my androidmanifest. This line <application android:theme="@android:style/CustomTheme" in my manifest file is causing an error. error: resource android:style/CustomTheme not found. I couldn't find any documentation online so I'm not sure how I can make my custom theme accessable.

hazy hearth
#

Hello there, I've published a title that I've been working for a year and through that process I've managed to learn plenty of c# tricks and skills. Although I am embarrassed to say that even now I do not quite understand how for instance something like this works (programming wise ):

Something.ContinueWith(task => {
          ...            
});

Do you guys have any tutorial in order for me to understand code that goes beyond the loops and the ifs ?

flint wraith
#

i dont understand them after 10 years yet use them 😂

hazy hearth
misty walrus
gray zinc
random dust
#

Hmmm

#

Then you might be limited to using an Action

undone coral
#

i didn't read the forum thread super carefully. you might have to dynamically change the friction of rigidbodies participating in a knot?

undone coral
#

this sounds low stakes though

alpine adder
#

does anyone have experience with linker errors with unity cloud build and xcode?

undone coral
#

linker errors are generally not related to the build server. it sounds like you didn't check something in, or you aren't 100% sure how to include a library or something like that

shadow spear
#

yoo

#

can someone tell me how do i change the project settings in the game using code during run time

#

does anyone know how to do that

undone coral
shadow spear
#

KK

honest hull
#

Hey does the raytracingshader actually use the rt cores?
from my basic tests so far it seems that my custom computeshader rt solution outperforms it which doesnt make sense

#

and is there much delay when interoping between compute shaders and raytracingshaders?

undone coral
#

those only exist on PS5 and DX12

honest hull
#

raytracingshader is I believe how you access the hardware RT functionality
and ye im on dx12

undone coral
#

i don't know very much about unity's specific implementation sorry 😦

honest hull
#

ok thank you!
theres very minimal documation on it

alpine adder
# undone coral linker errors are generally not related to the build server. it sounds like you ...

so im trying to figure out how to go about this with cloud build. im not sure what files would be missing here is exact errors. im not sure why it can't find architecture for a cloud build server

33259: [2022-10-25T17:06:44.087Z] - 7.1.1.2.4.2 - INFO: ▸ Linking UnityFramework
33260:
33261: [2022-10-25T17:06:49.829Z] - 7.1.1.2.4.2 - INFO: ▸ ❌; Undefined symbols for architecture arm64
33262:
33263: [2022-10-25T17:06:49.829Z] - 7.1.1.2.4.2 - INFO: ▸ > Symbol: _UnityARKit_Planes_SetRequestedPlaneDetectionMode
33264:
33265: [2022-10-25T17:06:49.829Z] - 7.1.1.2.4.2 - INFO: ▸ > Referenced from: _ARKitProvider_set_requestedPlaneDetectionMode_m809BA1130FCBC827749625B811B69DACB00BF01E in Unity.XR.ARKit.o
33266:
33267: [2022-10-25T17:07:06.261Z] - 7.1.1.2.4.2 - INFO: ▸ ❌; ld: symbol(s) not found for architecture arm64
33268:
33269: [2022-10-25T17:07:06.276Z] - 7.1.1.2.4.2 - INFO: ▸ ❌; clang: error: linker command failed with exit code 1 (use -v to see invocation)
33270:
33271: [2022-10-25T17:07:06.364Z] - 7.1.1.2.4.2 - INFO: ▸ ** ARCHIVE FAILED **
33272:

undone coral
#

and is this the only error it gives you?

alpine adder
#

I can send the full file if that is helpful?

gray zinc
# undone coral i'm not sure if a global using is supported

yup apparently not. I ended up just making a helper function to create the arrays I wanted to make using params. That way I don't have to write the new System.Action<InputSystem.InputAction.CallbackContext>[] every time I want to create an array of Actions.

undone coral
#

i understand you're doing a cloud build

#

i think if you want to develop for iOS without owning a macOS device, you shoudl file a ticket with cloud build support

sage radish
regal olive
regal olive
undone coral
regal olive
#

Trying out dynamic friction = 50, static friction = 10

#

@undone coral no, the intended problem is not getting solved.

#

Let me try to extract a video of the scene for you.

undone coral
#

i'm not sure how to address this issue, i'm sorry

regal olive
#

No worries. I was intending to record a video of the issue anyways!

#

I'll just put it here for anyone else, and forward it to other servers and my faculty.

scenic lark
#

hey everyone. is there any way to run this script with lower fps than time set in unity? It's reflection but when it runs in 30 fps, it eats alot of gpu power.

abstract folio
abstract folio
undone coral
#

why does this field have no side effects in git?

#

what is the lighting data asset reference? where is this? why isn't it saved?

#

it seems to get cleared every time it is set

sly grove
#

it's a file generally shoved in a folder next to your scene file.

#

You might have it .gitignored

undone coral
#

now trying git clean -dxf and seeing if the reference is kept

#

@sly grove any idea where this reference might be stored in code? i think i have to do a [RuntimeOnLoad] and patch it up whenever the editor is opened with this scene

#

because there are too many quirks with it, potentially on different editor platforms

#

i guess this Lightmapping.lightingSettings

undone coral
#

do objects in Resource transitively include their dependencies?

smoky glade
#

Halo
Is there anything i can use around yield return SceneManager.LoadSceneAsync that returns the scene when it's loaded?
Without using SceneManager.sceneLoaded callback whatsoever?
Bcoz i'll have scenario where i'll load the same scene additively multiple times at the same time

jolly token
#

So you can use it instead of yielding it

undone coral
#

well setting the lightmapping is going to be a nightmare

jolly token
#

It is nightmare 😄 and depends on "scenes"

smoky glade
undone coral
#

why is the lightingdata.asset a binary file..

jolly token
smoky glade
humble onyx
timber remnant
#
private void HandleMouseLook()
    {
        rotationx -= Input.GetAxis("Mouse Y") * lookSpeedY;
        rotationx = Mathf.Clamp(rotationx, -upperLookLimit, lowerLookLimit);
        playerCamera.transform.localRotation = Quaternion.Euler(rotationx, 0, 0);
        float mousex = Input.GetAxis("Mouse X") * lookSpeedx;
        transform.rotation *= Quaternion.Euler(0, mousex, 0);
    }

this is the look code

undone coral
#

i'm not talking about the image data

#

it just goes to show how confusing and awful their lightmapping system is

humble onyx
undone coral
humble onyx
#

at least as far is i know

undone coral
#

it's okay, i am writing a different workaround for this quirk

humble onyx
#

the only other data file that is binary is the terrain data

undone coral
#

patching the scene on build

#

it's possible to get into enough jeopardy in the unity editor to save the scene with that field populated

#

close the editor, reopen the editor, and observe that field is empty

#

it's an editor bug i'm sure, but not one that i have the time to create a reproduction for unity QA, or to wait 9 months for them to fix it

mint sleet
viral knoll
#

how do you guys code the max exp so it doesn't go way up to the sky

lyric dragon
#

Hello guys!
I am currently implementing a plugin for android and I have a method that has to be run on the main thread. So I am using something like:

private void Start() 
{
  AndroidJavaObject activity = **init**;
  activity.Call("runOnUiThread", myFunc);
}

private void myFunc()
{
  // something to be run on the main thread
}

private void anotherFunc(int number)
{
  // do something with number
}
smoky glade
smoky glade
#

Not sure if this is by design, but it'd be nice to have a more reliable version of SceneManager.sceneLoaded

gaunt reef
#

I have a Unity project and I want it to export and intergrate it into react native app, it worked well on android and IOS but I wonder if I can export an unity project to intergrate it into windows react native app?

#

both android and ios I exported as library to intergrate into android & ios, I tried exported it as WebGL but it appear that interaction between app and game won't be as good with this solution

#

So can unity export the project as a library and intergrated into react native Windows app like android and ios?

regal olive
regal olive
mint sleet
#

my cable does 😄 @regal olive

regal olive
lament salmon
#

you could make the capsules overlap and disable collision in the joint, so that a segment doesnt collide with the one next to it.

#

changing the rigidbodies' collision detection mode might also help.

regal olive
lament salmon
#

I had to go from default 6 to like 32 for stable ragdoll simulation

#

Enable Adaptive Force might help too

hazy hearth
#

How do I yield until a method is finished?


yield return InternetManager.instance.CallCheckConnection();

CallCheckConnection return void so I have an error

random dust
#

Make both methods async, where the CallCheckConnection is a task. Await the method

#

The CallCheckConnection obviously needs to properly implement the async-await pattern

hazy hearth
#

Let me explain the problem before I proceed to changes.
As of right now my code is like this:


// Internet check
InternetManager.instance.online = false;
InternetManager.instance.CallCheckConnection();
yield return new WaitUntil(predicate: () => InternetManager.instance.online);

// AD            
RewardedAd rewardedAd = adManager.GetComponent<RewardedAd>();
rewardedAd.ShowAd();
yield return new WaitUntil(() => rewardedAd.hasFinished);
            

Whenever the player dies for the first time an internet check starts and waits until the player is connected to the internet. In case the player is offline, CallCheckConnection() shows a Try again button to check for internet again, until the player is online.

Then an ad is properly showed and I get the big money.

The thing is that my users complained about the mandatory internet connection so I was thinking of removing it. In order to remove it I need to make the panel not show up in the first place. So I need to make an internet check only to make decision whether to show the 'Watch an ad to continue' or not.
@random dust

regal olive
dapper cave
#

how do i get the GUID or path of a script's type?

sly grove
dapper cave
dapper cave
wispy terrace
#

What's the best Steamworks wrapper for unity?

sly grove
dapper cave
jolly token
flint sage
#

Any file in the project has a GUID

#

And all of the scripts are MonoScripts

sly grove
jolly token
flint sage
#

Right yeah, misunderstood then

pale pier
#

Anyone know how I can Reset a scriptable object from code?

#

Couldn't find how Unity were doing it from the CsReference repository

obsidian glade
pale pier
#

That won't work unfortunately, that would only invoke any custom Reset method I had on that script.

The best I could come up with was using

ScriptableObject.CreateInstance
to create a new object and then use

EditorUtility.CopySerialized
to copy properties from it to the original object.

It "works" but I thought there would be a more straight forward option.

misty walrus
#

Does anyone know how I can serialize an Object ? Much like in the UnityEvent, I need a field where I can chug in any object whatsoever.

sage radish
misty walrus
#

Is this kind of popup public for usage?

elfin bone
flint sage
#

The sub menu's are just strings with / in them

subtle moon
#

Hey! Quick question about the timing of collisions. In the .gif you can see black balls being spawned at set intervals. The spawning is triggered from a function that has been called with InvokeRepeating. The Debug.Log:s show the time between when the previous ball and the current ball hit the green square. My question is, why does the timing fluctuate? Is there any way I could “quantize” the time so that it is consistent?

tropic pulsar
#

What you are seeing is compounding floating point error.

#

Why do you need consistent timing?

#

Tbh, timing is almost the same

subtle moon
#

Thanks for the reply! Thing is, those marbles will be bouncing and rolling all over the place so doing my own physics calculations for them would probably be too hard for me at my current skill level. I need consistent timing because the green box plays back audio when it's hit, and the idea is that this app could be used a sampler/sequencer lol

#

I have already tried building drum loops with this, and the fluctuation is audible.

tropic pulsar
#

You are taking wrong approach, if you want consistent timing for anything do not use physics.

#

My recommendation is to change design to have "simpler" physics and to implement it yourself. Preferably using integers for positions rather than floats to avoid floating point error.

subtle moon
#

Being physics based is kind of the point of this, if that makes consistency impossible then I will just have to live with it hahah

#

Thanks, will look into that!

tropic pulsar
#

Well, you need to give us the bigger picture but the short answer is "No". 😄

tender light
#

You can decrease this variation by increasing the simulation frequency. Maybe instead of 50hz try.... 300hz?

tropic pulsar
#

Meaning physics and consistent timing do not mix well

#

Yeah, that is good idea, play with physics settings, increase simulation resolution for example.

subtle moon
#

Cheers! I'll try, doesn't have to be really perfect just enough to not be audible.

tropic pulsar
tender light
tropic pulsar
#

Another idea yeah, maybe update your simulation manually.

tender light
#

But that's more involved and complicated. Maybe more than you need? Simulation frequency increase might be good enough

subtle moon
#

That looks super promising actually. I'll look into that as well and see if I can wrap my head around it, but let's start with simply increasing the simulation frequency.

#

That seems to have done it! A fixed update now happens 5 times as often as previously, hope I can keep things optimized enough to not run into issues.

tropic pulsar
#

Sounds promising.

tender light
#

Depends on your target platform.
I would recommend you clean out your layer collision matrix try to keep your actually colliding layers as minimal as possible.

#

Never uses OnTriggerStay/OnColliderStay and you should be good.

tropic pulsar
tender light
#

That is IF your platform is PC. For mobile it might be problematic with older devices.

tender light
subtle moon
#

Seems good, still getting a stable 50FPS even while torturing the physics engine. I'm targetting PC anyway!

tender light
#

Its easier to just add the object to a list OnTriggerEnter and remove it on Exit. That way you can cache whatever component you need from it. And don't have to GetComponent<> all the time

#

PS: there will be issues with collections being modified while enumarating over them and the list containing null values. But that's a tradeoff for performance. You can solve those with some googleing

obsidian glade
tender light
tropic pulsar
#

I would not recommending doing anything with DOTS if you are not very comfortable programming and using Unity.

#

I have 10+ years exp as coder and I am struggling to get even basic stuff working in DOTS.

subtle moon
#

I know, just using that to give some indication on what's going on:D Thanks for the info about caching, solid tips. I do that as much as possible already with all my raycasts being nonAlloc etc.

subtle moon
tender light
#

Dots and Havoc are both 3D only anyway no?

#

Not that they cant be used for the music synth project but... might lead to other issues.

obsidian glade
#

it's definitely not easy, but if you want a lot of marbles running deterministic physics in a performant way, it's probably the easiest option

#

but perhaps your project can make do without one of those requirements

subtle moon
#

For now at least, maybe V2 will be built using DOTS.. Who knows, maybe DOTS itself is a bit easier to use by then too hahah

supple magnet
subtle moon
dapper cave
#

is there a performance penalty for moving a kinematic rigid body outside fixedupdate?

sly grove
#

but otherwise no. You need to be aware that transforms and rigidbodies are only automatically synced right before the physics update though

livid zephyr
#

Hey everyone!

#

I have a bunch of game objects that I want to be able to change thier colors individually when they are being started at by my camera but currently all my objects start changing colors even when they're not being stared at, can anyone provide me some tips?

#

I can share a video showing whats going on

elfin tundra
#

send the code you're using to check if the camera is pointing at the objects

#

you should be using raycasts most likely

livid zephyr
#

Yes i am using raycasts

elfin tundra
#

wait hang on

#

there might be a faster way

#

check out the OnBecameVisible and OnBecameInvisible functions

#

those are called when objects move on and off the camera's view

#

add those functions to your objects' scripts instead of raycasts and it will work better and probably faster too

livid zephyr
#

Hmmm

#

Hmmm okay i have code set up to change the color gradually because im trying to creating a scanning effect

#

Let me try that

elfin tundra
#

so it might look something along the lines of

class YourObject : MonoBehaviour
{
    bool cameraLooking = false;

    void Update()
    {
        if (cameraLooking)
        {
            ChangeColor();
        }
    }

    void OnBecameVisible()
    {
        cameraLooking = true;
    }

    void OnBecameInvisible()
    {
        cameraLooking = false;
    }
}

not sure if that's exactly what you're going for but that should work for continuously changing colors

regal olive
livid zephyr
#

I have a drone player and trying to set it up where it can "scan" the objects and once the camera has the scan area into view, the scan area will start gradually changing colors

#

i have an fps cam and a topdown cam, and the fps cam can see many zones but only want it to scan one at a time

#

so hopefully this can help

#

thank you

elfin tundra
#

awesome! hopefully it works

#

i think what i sent should work for that purpose

livid zephyr
#

@elfin tundra This works but i dont want the zone to turn red until the camera has the full zone in view and is close to it

#

@elfin tundra like this close is when I want it to start changing because at that point its scanning

elfin tundra
#

ok so you could add an additional check in the OnBecameVisible function

#

something like if (Vector3.Distance(transform.position, camera.position) < someValue)

livid zephyr
#

😮

#

of course!

#

Let me try that

visual shore
#

Hi, question about Behavior-Driven Steering at the Macro Scale. I was watching https://www.youtube.com/watch?v=6BrZryMz-ac and was wondering about the direction gizmo, I read the article and realized it'd be perfect for a system I was working on and was wondering if someone had a project or some code I could see because I just can't seem to actually recreate this. My system takes lots, around 20 positions in a sorted list, to avoid and one to find and head towards and it'd be perfect to see something like this that I could reference and specialize for my own system :)

Combat keeps the player engaged as they explore my game, so I improved how the enemy interacts with the player and their environment. This tweak made combat so fun that a tester spent over an hour repeatedly fighting a handful of enemies. At this point I knew I had an engaging combat system!

Howdy, and welcome to the 12th indie game devlog for ...

▶ Play video
royal zealot
#

guys im pretty much disappointed

regal olive
#

How do you make it so your chracter will look a certain way in 2d and any children(gun) will go to the other side?

royal zealot
#

is really Material property block useless in improving performance in unity todays unity 2021?

jolly token
#

MPB has performance improvement ofc

royal zealot
#

well...thanks about it...i just got clear on another platform

jolly token
#

But in a sense true, since MPB does not work with SRP

forest cosmos
#

Hi devs, any idea on how to use a 2d irregular bin packing library in unity?

errant plinth
#

Read the documention. Follow guides/example using the library. Do your own experiments.

forest cosmos
#

damn, thanks bro ahahaha

regal olive
#

Ray ray = cam.ScreenPointToRay(Input.mousePosition + recoil.deviation[recoil.heat]);

I am trying to add deviation from the crosshair for recoil. is it the right way if i add deviation values to mousePosition for a ray?

regal olive
jolly token
#

You should add recoil to resulting ray's direction

regal olive
#

ok thanks

rough sky
#

I'm writing my own level editing tool and as part of it I have a series of "palettes" of level components that I can drag and drop into the scene. I'm making an EditorTool for it and I have it working, except for reverting back to whatever the last tool was, eg the move tool, for further editing of the added tool. It reverts back to the tool, but I cannot use it. Furthermore, it seems to be defocussing on all windows afterwards, so if I want to edit something in the newly made objects' inspector, I must find it in the hierarchy and select it again. Is there a correct way to add and remove tools by code? I have attached how I am adding and removing it, and hope that somebody can help me resolve the issue, as I am tearing my hair out

undone coral
#

what is your objective?

undone coral
#

why are you asking about the gizmo specifically?

#

@visual shore i think this is the most important screen shot

forest cosmos
# undone coral are you asking how to use nuget package / C# .net ecosystem library in Unity?

well i was trying to figure out how to use a mechanism similar to texture atlas packing. I have a set of shapes ( not regular) with determined dimensions. I need to place the shapes in a given rectangle with specified width and length. I found out that algorithm is called irregular bin packing (used to minimize waste of space between shapes). I was wondering if there some way of implementing it in unity...

jolly token
undone coral
#

in principle you can implement an algorithm yourself directly in C#

#

it's not complicated

#

have you tried?

forest cosmos
#

i'm gonna try during next week

#

i'll update you guyzz ❤️

#

it's possible that i'm gonna need some help eheh

#

maybe i'll come back here

undone coral
#

punch something into google and get started. find out the name of the algorithm from gogole scholar then search for some tested implementations (probably written in python), and start porting once you understand what you are doing

plush elk
#

any one knows if there is a setting in unity to keep the mouse inside the game view window?
I already setup in code

 Cursor.visible=false;
            Cursor.lockState = CursorLockMode.Locked; 
             Cursor.lockState = CursorLockMode.Confined;

but my mouse allways end up leaving the game scene space if it moves out of it

abstract hill
#

Hi everyone, I'm looking to implement implement a feature for a project I'm working on where I am essentially recording the output of specific cameras, ones that are only rendering certain game-objects. Right now I have this code below (working fine) where I am using the camera I am interested in to render to a render Texture, and the using the AsyncGPUReadbackRequest, waiting and then saving.

AsyncGPUReadbackRequest request = AsyncGPUReadback.Request(_renderTexture, 0, TextureFormat.ARGB32, readbackRequest =>
{
  Texture2D texture = new Texture2D(_renderTexture.width, _renderTexture.height, TextureFormat.ARGB32, false, true);
  texture.LoadRawTextureData (readbackRequest.GetData<uint>());
   
  byte[] bytes = texture.EncodeToPNG();
  Destroy(texture);
             
  new Thread(() =>
  {
    if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
    File.WriteAllBytes($"{directory}/{filename}{captureFrameIndex}.png", bytes);
  }).Start();
});

The issue I am having is that the speed in which this needs to be done is near negligible, or as close as I can get it. Right now I have though where the encoding of the PNG is extremely slow, and quite noticeable lags the games. I tried moving this to within the thread, however it is apparently not possible to do this not on the main thread.

Is there a different way to encode a Texture2D to a PNG, or is there a way to call this function in a faster way?

abstract hill
#

I am using the first link, but unfortunately the function is really slow, as for the second link, the problem is I need to render from a specific camera (not the one rendering the game but one in the same position, rendering only a limited amount of objects).

plush elk
#

@sly groveI got a feeling that this is more a problem of my system

#

@sly grovein build mode does not work

#

do I need to keep the code in update?

sly grove
plush elk
#

keeping the mouse inside the game view window

sly grove
#

DO you want the cursor visible and moving around?

#

Or invisible and stuck to the center of the screen

plush elk
#

invisible and stuck to the center

sly grove
#

Then all you need is:

void Start() {
  Cursor.lockMode = CursorLockMode.Locked;
}```
plush elk
#

I just tested it in start and it works

#

it was in awake and it didnt work

sly grove
abstract hill
# abstract hill Hi everyone, I'm looking to implement implement a feature for a project I'm work...

Hiya, found the solution for this! ImageConversion can be ran on a seperate thread and works in a near identical way, only slight difference is that I needed to get the raw data before hand. Thank you for you assistance btw @sly grove

AsyncGPUReadbackRequest request = AsyncGPUReadback.Request(_renderTexture, 0, TextureFormat.ARGB32, readbackRequest =>
{
    Texture2D texture = new Texture2D(_renderTexture.width, _renderTexture.height, TextureFormat.ARGB32, false, true);
    texture.LoadRawTextureData (readbackRequest.GetData<uint>());

    byte[] rawTextureData = texture.GetRawTextureData();
    GraphicsFormat format = texture.graphicsFormat;
    uint width = (uint)texture.width;
    uint height = (uint)texture.height;
    
    Destroy(texture);
    
    new Thread(() =>
    {
        byte[] bytes = ImageConversion.EncodeArrayToPNG(rawTextureData, format, width, height);

        if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
        File.WriteAllBytes($"{directory}/{filename}{captureFrameIndex}.png", bytes);
    }).Start();
});
split sierra
#

Hey, i just made a game and uploaded it to itch.io, my problem is that i have a build in leaderboard with playerprefs. This works fine for pc builds locally but on itch it does not really make sense since everyone can only see their own scores. Is there a way to make the leaderboard shared and somehow save the data on itch.io or some workaround that could make it work?
thanks in advance (:

gray zinc
#

Not sure where to post this, but i'm totally unable to get a Linux Standalone64 Server build to run on the Ubuntu terminal

#

I'm using a scriptable build pipeline to generate the build, these are the settings:

#

Nvm as I was typing this it decided to start working 🤠

#

I think i didn't do the chmod +x correctly initially

young wraith
#

hi is there a hit.textureCoord in RaycastHit2D hit??

#

here's my code that I wanted to convert in raycasthit2d

spring gorge
#

i have 2 way to do my job

  1. I set up a collider and use TriggerEnter
  2. I use check distant on Update
    which more performance?
jolly token
jolly token
#

Do use the profiler if what you're doing is performance critical.

young wraith
jolly token
young wraith
#

Thanks

devout orbit
#

Hey,

Does anyone know how to get a OnDestroy method in Editor?
I making a editor tool, and I need to clean up some stuff if someone removes the script in the scene.

#

Regular OnDestroy doesn't get invoked

flint sage
#

Does ExecuteAlways not also execute ondestroy? 🤔

devout orbit
#
    private void OnDestroy()
    {
        #if UNITY_EDITOR
        LoadAddressableUtility.RemoveAddressableAsset(CastleTaskHelperGenerator.SharedPath + $"/{transform.parent.name}/" + $"{LocationKey}.prefab");
        CastleTaskHelperGenerator.RemoveTaskFromMap(transform.parent.name, LocationKey);
        #endif
    }```
#

Tried it like this but no luck

flint sage
#

I think it goes on the class

devout orbit
#

Ah, you are right

#

I thought It was possible to put it on the method

#

Works now

#

ty

rough sky
#

Is there anyway to access the icons that the prefabs store for use in an editor window?

#

I want these icons, presumably they must be a part of the prefab file somewhere

tropic lake
rough sky
#

nice

#

That looks good, but I don't think it's what I want

#

I want exactly the icon the project explorer uses

#

I don't think there is a way unfortunately, so I settled for just using the default prefab icon

rough sky
#

same thing

#

all these methods give these sorts of icons

#

I'm trying to find a way to get the project explorer prefab preview

rough sky
#

Oh my god

#

you're my saviour

#

I had given up hope

#

Yes! Thank you!

wispy terrace
#

Yeah, I ended up going with it, facepunch.steamworks was giving me trouble and it hasen't been updated in over 2 years

regal olive
#

How would I make a gun shoot a bullet I already have a prefab do I just use instantiate?

devout hare
odd veldt
#

I'm going to parse a shader file, then I want to know which uniform defined as a Texture2D, get the uniform's name
what is this tech called

jolly token
#

Why are you making inconsistent state by setting active state false when creating, but setting true when getting from pooled object? Result of both should be identical. Also, if it's instantiated then it shouldn't be called 'prefab'. You'd need general understanding of object pooling. #archived-code-general

#

It is relevant because you are using word 'prefab' wrong in your question. Implies that you are probably using object pool in a way it is not mean to be used.

wispy lion
#

How have you determined that your pool gets a "gotten" prefab? And what does "fail" to get a prefab mean? Are you getting some error?

sly grove
#

what do you mean by this?
What do you get?

#

YOu have to get something. is it Null? Is it an already destroyed object? Something else?

#

Are you ever releasing your objects back to the pool?

#

can you show all your code

sly grove
#
  1. Why do a layer check in code? Just use layer based collisions
  2. Is it possible you're releasing the same object more than once?
#

and for 2 - doing the check before what?

upbeat path
#

have you checked which object is generating the Null Ref? I count 4 possible options

#

you do NOT get a Null Ref is nothing is null. So stop assuming and check

#

and yet you still get a Null Ref. Please explain.

#

'and it just throws a nullreference ' !

#
GemObjectPool.current.gemObjectPool.Get(out GameObject pooledGemstone);

even there there are 4 chances of having a null ref, are you checking those?

#

I dont see it in your code

#
 GemObjectPool.current.gemObjectPool.Get(out GameObject pooledGemstone);
            pooledGemstone.transform.position = new Vector3(transform.position.x, transform.position.y - (diggerSO.gemSize * 0.025f), 

I'm just going to assume it all worked

#

so post your .Get code

#

I mean the code which is executed when you call .Get

#

pooledGemStone is an out parameter, it needs to be set in .Get

#

I have asked you to post the code of the .Get method, if you will not do so then there is no helping you

#

As I said, there is no helping you.

#

Stop making assumptions, you know your code is wrong yet you seem to refuse to acknowledge this

toxic hill
#

I am not sure if this is advanced-worthy, but I have a neural network that I'm visualising via a heatmap, the heatmap itself is working (for now), but the network isn't. For some reason my input nodes are never being evaluated and everything just returns 0. This is what I believe to be all relevant code.

//The constuctor for thenetwork
          public NeuralNetwork(int inputs, int outputs, int layers, int nodes) // nodes here is nodes per hidden (intermidiary) layer
        {
            inputLayer = new(inputs);
            NeuralLayer previous = inputLayer;
            for (int i = 0; i < layers; i++)
            {
                var newLayer = new IntermediaryLayer(nodes, previous);
                intermediaryLayers.Add(newLayer);
                previous = newLayer;
            }
            outputLayer = new(outputs, intermediaryLayers[layers - 1]);
        }
//The configuration for the Network
private readonly Networker.NeuralNetwork network = new(2, 1, 2, 5);
//The function that gets called to get the network's output
        public double[] Calculate(double[] inputs)
        {
            for (int i = 0; i < inputs.Length; i++)
            {
                inputLayer.nodes[i].inputValue = inputs[i];
            }

            double[] output = new double[outputLayer.nodes.Count];
            for (int i = 0; i < outputLayer.nodes.Count; i++)
            {
                output[i] = outputLayer.nodes[i].GetValue();
            }
            return output;
         }

(1/2)

#
//The constructors and calculations for the Hidden and output nodes
        public IntermediaryNode(NeuralLayer previous)
        {
            foreach (NeuralNode node in previous.nodes)
            {
                weights.Add(node, rand.NextDouble());
            }
        }
        public override double GetValue()
        {
            double output = bias;
            foreach (KeyValuePair<NeuralNode, double> node in weights)
            {
                bias += node.Key.GetValue() * node.Value;
            }
            return output;
        }
//The input node
    private class InputNode : NeuralNode
    { 
        public double inputValue;
        public override double GetValue()
        {
            Debug.Log("An input node just evaluated to "+ inputValue); //This never seem to happen
            return inputValue;
        }
    }

(2/2)

#

If you need any more code, please ask

#

also, please ping me or I will forget that I've ever asked this question

jolly token
toxic hill
#

Good idea, I forgot those existed

viscid blaze
#

heyy, i have created a banner ad and added the unity mediation code for see my banner but i never see this and i have not error for this too idk why
https://hatebin.com/lnvhzkyumq

long ivy
#

if that's the unedited game id you're using to start up with, it's wrong. Your use of task run is suspicious. Confirm that your methods are actually being called with logging or breakpoints

thin mesa
viscid blaze
viscid blaze
thin mesa
#

ah, i misread the comment and saw that there's also an OnFailedLoad event being subscribed to. So then sprinkle some debug.logs in there or use breakpoints to make sure it is actually working. You also need to make sure you are calling the InitServices method somewhere since that would be done from an outside class

gray zinc
#

does anyone know how to start a Linux unity game executable with arguments?

#

I tried doing ~/MyGame/Build -nolog -single-instance but it seems to just ignore the args

viscid blaze
gray zinc
#

should I have two minus symbols? or do I need to pass "--args" first?

viscid blaze
long ivy
#

but not for loading, and your code is calling load on a separate thread. Since the docs I see don't do that, that's what makes your code suspicious to me. You might break something. Any errors in logcat?

muted widget
#

I have an AI traffic system that works okay. I use this culling system to move the traffic around the player and re-positions the vehicles when they move outside of the player's area. The game divides the city into cells and assigns roads to them. The FindNewRoads function at the bottom is what the traffic uses to find a new location . But traffic does ocasionally all spawn around a singular location. Is there a better way to do this? To fix the logic in FindNewRoad https://gdl.space/iritefusiw.cs

vocal dagger
#

Im using Universal renderpipeline and i want to set a texture/sprite onto my mesh. However its... just... transparent for some damn reason, no matter what properties i set. Why ?

#

I need to use the "Sprite-Lit-Default" shader, however with this one its just transparent, any ideas why ?

flint sage
#

Why are you using a meshrenderer with sprite shaders?

vocal dagger
#

Is there a special renderer for only sprites ?
Its because i have a 3D plane... where i wanna put a sprite onto it basically

#

Like imagine a 3D game where the ground is made from 2D tiles, each tile is a 3D plane... and i wanna put a 2D texture onto it

flint sage
#

Well the sprite component sets up the material and stuff for you

#

So it's hard to know what the sprite shaders require to render properly

#

But one thing is clear is that they're not meant for this

vocal dagger
#

However the sprite renderer only works on ui or am i wrong ?

flint sage
#

No that's Image

#

Idk if sprites work at random world space angles but again, you're abusing a shader that's not meant for this

vocal dagger
#

Oh i see, well however i cant change to much here... its a library i use which does the tiling for me basically. All i know is that since i upgraded from 2020 to 2021 its broken. It worked before and showed the tile properly

#

And it used the shader before the change

flint sage
#

In that case, go compare the shader and see what changed

#

You can download unity's shaders from their website on the download page

gray zinc
#

calling BuildPipeline.BuildPlayer(options) seems to set the build target in the editor. Is there a way to make it not set he build target or to reset the target? This is pretty annoying because my scriptable build pipeline builds for Server but I want my editor set to build for Windows for all other cases. There also doesn't seem to be a way to set it back.

turbid tinsel
gray zinc
#

it turns out 1 minus symbol was fine, the problem was not related to the args. i think two minus symbols is for Windows?

turbid tinsel
#

Also depends how you get your args

#

Different ways of getting them have different results
Technically you dont need to have any minus signs, if you're doing it the most low level way

gray zinc
#

Yeah

#

I was trying to run Unity without any terminal output at all, but it turns out -nolog only gets rid of the log unity produces on shutdown, it doesn't actually stop unity from taking over the cmd

royal zealot
#

how to set up 60 fps target framerate for android?

#

i mean what is the procedureZ?

woeful trout
#

So, I'm a little lost

#

We're building a topdown with Unity for our term project

#

And our current task is to build some kind of diagram mapping system. The next phase is building a code skeleton, and then we move on to implementation

#

But honestly, I'm drawing a bit of a blank

#

Can someone help me get started?

velvet rock
#

I probably would start with generation of it from your data source, let’s say json file. Instanciate a prefab for each node of the diagram, the connection between you could programmatically draw or find some asset that draws an arrow. Not sure what a code skeleton is, assuming a programmatically created skeleton, but the 2D hinges can work for bone structures

turbid tinsel
royal zealot
#

what the hell is Gfx.WaitForPresentOnGfx?

#

its killing my whole game

sly grove
#

CPU waiting for GPU

royal zealot
#

yeah...the leafs of the tree uses alpha blended tranparency

#

when camera get closer to the leafs

#

fps drops down

#

and Gfx.WaitForPresentOnGfx rise up as a huge spike

#

idk what is the way out to get rid of it?

#

is it any batching issue?

#

what can i do to solve this?

royal zealot
#

understood the problem

#

alpha blend shader calculate the all the pixel beyond a gameobject

#

its the main cause to buffer

undone coral
gray zinc
#

I can't compile my game anymore when using the builtin render pipeline and the default terrain shader. Is this a known bug with 2021.3.11f1?

#

It compiles fine when I get rid of the terrain and the terrain materials.

bold berry
#

What type of coding can you do with Python within a game engine, do I need to think about creating tools?

undone coral
sly grove
bold berry
#

Sometimes i read think like scripting that can be done with Python to create tools for engine like blender, unity, unreal whatever.

sly grove
gray zinc
#

everything in unity uses C# except for the core internals that use C++

undone coral
undone coral
#

that is the idea

sly grove
#

It's not called "Boa Constrictor" now is it?

bold berry
#

It's just that game development in general is broad, I have seen it's to much for me so I just wanna focus on a langauge to niche more, so thought python was used for creating tools.

#

C++ for now way to heavy.

undone coral
#

usually when people say "tools" and "python" they mean file format conversions

#

and other things related to "pipeline"

#

@bold berry is that what you are interested in making: pipeline tools??

bold berry
#

What specifically can you present to a company, to show off you coding skill, without being to much busy with, level design or whatever.

undone coral
#

i see, are you a student?

bold berry
undone coral
#

in my experience there are so few programmers with advanced knowledge of C# in Unity that it's obvious when you see one

#

i've seen the source code for many, many video games written in C# in unity. in my experience, code style is predictive of developer quality / personnel performance. use of advanced things like IDLs, build tools, async/await, Jobs is highly predictive but very rare. "years of experience" after "1 year" has not been predictive (so 0 versus >0 is predictive, but 2 versus 3 is not). @bold berry

bold berry
undone coral
# bold berry I just try to narrow down what projects I can work on and what technics companie...

so if you were trying to work for me, whether now or at the game studio i worked at 10 years ago, i would want to see some pre-existing unity project you worked on. doesn't have to be fully authored by you, as long as it is "git blame" clear what you did. then i would look for things like

good:

  • mastery of git especially using the cli exclusively, GUI / idiomatic merge tools
  • comments and documentation in code
  • use of access modifiers
  • [SerializeField] private float m_SomeNumber
  • struct versus class used sensibly
  • two space indentation
  • union types ([Serializable] struct NumberOrString { float number {get;set;} string text {get; set;})
  • C# features like sealed, unsafe, const
  • switch, enums
  • using HDRP / URP, custom passes / render features, volumes, graphed / vendor materials
  • reactive programming (UniRx)
  • functional programming (Linq)
  • async/await (+UniTask)
  • Event System for UX
  • Event System for 3D UX (PhysicsRaycaster3D)
  • simple UI framework for screens / pre-existing one
  • use of packages and focused asset store assets
  • DOTween for animations
  • cinemachine for camera control
  • new input system
  • vendor multiplayer solution (photon)
  • build tooling (npm, gradle, bazel, cmake, etc.)
  • IDLs (protobufs, msgpack)
  • VFX Graph and Shader Graph
  • networking IDLs (openapi, grpc)
  • server backend background knowledge (what REST is, OIDC basics like what a token is, Authorization: Bearer xyWZ versus Authorization: [base64 encoded username: password])
  • CI/CD knowledge (writing tests, building from the command line)

bad:

  • stubbornly using source control GUIs (with the exception of merge tooling)
  • scriptable objects with behavior in them
  • built in render pipeline
  • writing your own shaders for built in render pipeline
  • amplify shader editor
  • updateloopese void Update() { ... timer -= Time.deltaTime; if (timer < 0) { ... }}
  • input based updateloopese if (Input.GetMouseButtonDown(0)) buttonThisFrameDown = true;
  • writing your own tweening Vector3.Slerp(...)
  • writing your own event system if (Physics.Raycast(..., out var hit)) { UserDidClick(); } especially if you already use it for UGUI but don't comprehend you can use it for 3D
  • writing your own state machines
  • writing your own networking new UdpClient() ...
  • writing you own sprite tooling, like creating sprite clips based on how files are named
  • low level networking used directly
  • multiple canvases
  • multiple main cameras
  • multiple scenes
  • "dont destroy on load"
  • no access modification public float someNumber
  • custom serialization ISerializationCallbackReceiver
  • gratuitous generics X : MonoSingleton<X>
  • gratuitous interfaces GameController : IGameController
  • gratuitous coroutines / coroutines that don't yield
  • flawed, plain async
  • zenject / dependency injection frameworks
undone coral
#

on the other hand, the people you are talking to are not going to be experienced enough, necessarily, to know any of this

#

B people hire C people...

#

@bold berry hope that list is helpful

gray zinc
#

what's wrong with writing custom state machines?

undone coral
#

you don't understand yet that it's unnecessary and a distraction

#

or you haven't figured out how to solve the problem better because you lack the background

#

but really, that's a matter of experience

#

someone with a lot of checkboxes in the good column will be able to pick up the language features / paradigms that obviate state machines

#

so they never try authoring one

gray zinc
#

huh ok

undone coral
#

of those things in the bad column i used to do, probably gratuitous generics was #1

#

since experience isn't really predictive after 1 year

#

the thing i would be looking for is, do you anticipate that there are better paradigms than timer -= Time.deltaTime

#

for example

#

there are people who have been writing C# unity code for 10 years who still do timer -= Time.deltaTime

gray zinc
#

instead of using a timer, stopwatch or a Task?

#

ah because your list specifically is in the context of Unity C# development, not C# as a whole

undone coral
#

instead of using a coroutine (good) or an async UniTask (better)

gray zinc
#

or a plain C# async Task?

undone coral
#

or a tween

undone coral
gray zinc
#

what if I want my code to work outside of unity?

#

what do you mean?

undone coral
#

async void Start() for example is really problematic

gray zinc
#

Yes plain async methods are problematic

#

I'm saying using System.Threading.Tasks

undone coral
#

like functional / reactive programming

gray zinc
#

Ok

undone coral
#

i would also suggest using cli tools in general - for example, using git from the command line exclusively

#

i can write it in order of what's most predictive (CLI use of git is probably #1, followed by code style, then functional & reactive programming)

#

really if you are not stubborn about using Git GUIs

#

being stubborn and using a Git GUI even when someone tells you not to

#

that's super predictive of bad

gray zinc
#

i mean if all you need to do is push and pull doing it from the app is fine imo

#

refusing to use the CLI git is not fine though

undone coral
#

like i said

#

100% cli git

#

i think what @bold berry is discovering is that a lot of the things he's looking for is on the "bad" list

#

like zenject

#

there will be people who want zenject, and they'll hire someone who is excited about it, and it'll be a team of B people hiring Cs

#

i'm not saying those opportunities don't exist, i just cannot speak to them as good

gray zinc
#

that's fair

undone coral
#

like you'd think writing your own networking is impressive and it's actually a really bad sign

#

it means you're choosing to do something super low ROI and pointless

#

for your game that no one will play

#

whereas functional programming you can use forever

undone coral
# royal zealot what the hell is Gfx.WaitForPresentOnGfx?

also in editor it's different than in standalone. if you're on windows and using URP / HDRP, try

mygame.exe -force-gfx-mt -force-gfx-jobs native -force-dx11

to enable all pipelinining features. QualitySettings.maxBufferedFrames should be kept on its default (which i think is 2)

royal zealot
#

whats about mobile?

#

someone says to uncheck "graphics jobs" on the quality setting

bold berry
#

@undone coral whats bad about ```- updateloopese void Update() { ... timer -= Time.deltaTime; if (timer < 0) { ... }}

  • input based updateloopese if (Input.GetMouseButtonDown(0)) buttonThisFrameDown = true;
  • writing your own tweening Vector3.Slerp(...)
  • writing your own event system if (Physics.Raycast(..., out var hit)) { UserDidClick(); }```
#

How would you detect input?

abstract hill
#

Hi all, I was wondering if someone could explain to me why the load Task is being considered complete before it calls the debug log Debug.Log("Test: 2"). I want to process some large files from JSON to a class without needing the game to freeze, but for some reason the loadTask.IsCompleted triggers true before it actually has. Something strange as well is that Debug.Log("Test: 2") never seems to be called even after waiting for quite a while, when before hand (when the function wasn't async) the game would freeze for 10 seconds and then load it. My thoughs where that JsonUtility doesnt work with async and causes it to break out of the lamda, but I have no errors in the console.

public IEnumerator ProcessInputs()
{
    Task loadTask = LoadAsync();
    yield return new WaitUntil(() => loadTask.IsCompleted);
    
    Debug.Log("Test: 3");
    
    Task processTask = ProcessAsync();
    yield return new WaitUntil(() => processTask.IsCompleted);

    Debug.Log("Test: 6");
    
    Save();
}

private async Task LoadAsync()
{
    Debug.Log("Test: 1");

    Task loadTrackingData = Task.Run((() =>
    {
        _trackingDataContainer = (inputTrackingData == null) ? null : JsonUtility.FromJson<SessionTrajectoryDataContainer>(inputTrackingData.text);
    }));
    
    Task loadEventData = Task.Run((() =>
    {
        _eventDataContainer = (inputEventData == null) ? null : JsonUtility.FromJson<SessionEventDataContainer>(inputEventData.text);
    }));

    await loadTrackingData;
    await loadEventData;
    
    Debug.Log("Test: 2");
}
#

This is the debug log

undone coral
#

or input system for those rare non touch games

undone coral
#

almost none of this will do what you think it does

abstract hill
#

Is UniTask a package? And could you explain why it isn't going to work too? (Sorry I'd like to understand where I went wrong with this)

fresh salmon
#

You're mixing up async and coroutines basically

#

That's not going to turn out well, either do it all coroutine or all async