#archived-code-advanced
1 messages · Page 24 of 1
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
So when accessing ReactiveProperty does it store all of the past values too?
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
What does killedBy: source, amount: amount do?
whoops i fixed it
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
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?
You forgot your meds again
lol
ugh i've had bad luck helping people lately but this guy fucks is all i'm saying
it took only a few hours and there's already all this awesome stuff happening so i'm pretty happy
this is exactly what i was looking for by posting here
yeah, and the game looks nice
anyway i think this is really good ground covered and it is coming quickly
we shouldve made a thread
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
You can solve 99% of problems without anything fancy 😅
Everything is just a tool at the end
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.
we can stick to async
i agree reactive can be weird if you don't do the web development thing also
I'd settle for 10 or 20% .. too many problems
lol
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?
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? 🙂
For sure, this is making my brain explode
lol
I think the important thing if you haven't tried it is to see how you like the approach, not everything is for everyone, but you'll never know until you try it
@obtuse flume well keep us posted on how things go and make sure to GIF & document some gameplay 🙂
Yeah for sure. I wanted to improve my enemy behavior system because I am currently working on adding more interactive and interesting enemies than just "chase the player" or "move and shoot". You can see where my game was at 1.5 months ago at "Tony Dev" on YouTube. Not too much has changed yet.
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?
looks really awesome
cool
is zenject popular?
It’s fun if a non-trivial message gets through. Makes it all worth it.
not in the grand scheme of things but it is among those who want to use a dependency injection framework in unity
I have watched a tutorial on yt and basically what it is for is to have singletons initialised before game has even started?
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?
decoupling your systems by automatically injecting the references they need based on rules and contexts defined outside of them... in other words its used to separate dependencies from the concern of a particular implementation
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
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
yes, if you don't have a perceivable problem regarding coupling/decoupling and modularity of your code, you don't need it
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
What is the syntax for setting a variable to either <a> or <b> with faster if statement
i do not understand your question
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
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
- Use a variable instead of writing the same formulas 4 times
- If car is going backwards, simply multiply that by -1
thats the point, how to know if the car is going backwards
get its local velocity and see if the front/back axis is positive or negative
Assign Input.Axis * speed; to one variable. then assign that variable to all wheels
calculating it 4 times, is poor form
okay so the velocity is called MoveForce for me
but there is a problem
like for my speedometer the speed is always positive
so idk
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
the return value of your input
Ok do you know why some programmers say Singleton is an gamedev antipattern? I don't
I have no idea why, I don't use them often but I think a lot of it is down to people's opinions
Becauae someone with a milk box to stand on said it once
so its good if i write this like if(Inupt.....(Vertical) < 0):
Singletons are perfectly fine if used correctly
formula x -1
?
hm ok
What is ironical in a milk box though?
ahah yes.....
but what i wrote can work no ?
what
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
Just means somebody who thinks they know it all
hm fine that's a saying
kk
tyy
for future questions like this, i'd advise using #💻┃code-beginner
ok thanks you man
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.
Async stuff
How did you change the mesh?
I fixed it now, you just have to rebuild the rig but originally I just removed the model
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
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
Nothing it seems, that doesnt work?
Meaning?
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
@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
I think it works now, the problem is in the function that I wrote I *= instead of = the rotated position
When using the FromToRotate function, how do I preserve my other axis?
Call FromToRotation on vectors that are only rotated on the axis you want to rotate on.
I am rotating the transform.up to the normal of a surface, are those not the only axis I am trying to rotate?
You said "other axis" you'll have to explain precisely what you mean
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
transform.rotation = Quaternion.LookRotation(Vector3.projectOnPlane(transform.forward, surfaceNormal), surfaceNormal);
Thank you!
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/fileto additional compiler arguments. - Implement
OnGeneratedCSProjectin 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
.cswith 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"
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>();
no. what if you implemented the interface in the struct?
do you mean public class Example<T> where T : IInterface, struct
I need multiple different structs. And I don't own the class Example. It is NativeArray<>
are you saying you want to have a NativeArray<ISomeInterface>?
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
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 { }
i see
why would it be a native array though
what is the advantage here? what am i missing
You need it to be a native array to use it in a job
do you mean for it to be a burst job?
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?
It is required for the IJobFor interface. I also will be using it for passing some specific data to the generators
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?
Yeah, I guess that would work. But boy does that feel real ugly
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"
What do you mean?
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
How many jobs 'can' you schedule at a time?
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
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.
i think that's fine
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
I presume you're familiar with Deform (https://github.com/keenanwoodall/Deform)?
I don't remember it having scatter, but it's all about modifiers
rather than have 1 IJobFor that is your poor man's scheduler
Nope, but I will take a look. Might be useful! Thanks!
yeah that is how they are now.
I think I know the 'right' way to approach this now. Thanks for the help!
did you observe something weird? i don't use jobs often only tweak ones in the hdrp source
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"
No, just trying to figure out how to architect the thing and pass the info I need around in a nice way 🙂
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 
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
You do know that using UDP protocol offers no guarantee that packets will be received and processed or even if they are in which order that will happen
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
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
The behaviour you're describing is the current behaviour of the code I provided
Does not look like it from
[...] // Lots of code to process the data and return it
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
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
);
}
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
- 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
- The issue you point out is irrelevant to the problem that I'm having & describing
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
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
Do you perhaps remember the client's ip and don't allow them in again as a new player?
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
I want to believe it's something like that but not at all, I don't do such thing & most importantly the server socket is set to listen to *any* address so litterally any UDP data arriving on this port should be caught! (even garbage data)
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
What's the difference between UniTask and UniRx?
I could be wrong but it looks like UniTask has all the reactive programming like UniRx
Anyone familiar with the Unity Test Framework? I've tried setting it up but the framework isn't recognizing the existence of my code. "Cannot resolve symbol 'Player'" (Player being a class I defined). I followed the instructions in in creating the assemby but I can't help but feel like there's a step missing.
https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/manual/workflow-create-test-assembly.html
You gotta add a refernce to your game assembly
how do you get all the agents currently on a navmesh from its navmeshsurface?
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.
No, you create your own asmdef for the game code
I believe UniTask is just a revamping of how Unity handles async/await/Task stuff, and UniRX adds the reactive paradigm on top of UniTask
Yes, but I don't know how to configure the asmdef so it references my game code. That's what I'm asking.
yes it's the location of the asmdef file
the file grabs all source code within the directory it's in (and subdirectories) and puts them in an assembly
Right.. so I can't have my test scripts in my game scripts folder. I need to organize my Asset folder a little differently. So that the asmdef for the tests isn't overlapping the game asmdef.
correct
The Unity documentation is kind of light on these details. I'm gonna go make the suggestion that they update them.
what's your objective?
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
@sly grove @flint sage Thank you. 🙂
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).
I also asked it on the forums with greater detail - https://forum.unity.com/threads/migrating-asset-bundles-from-assembly-csharp-to-asmdef.1352294/
asyncResult.AsyncWaitHandle.WaitOne(timeToWait); why are you doing this? @cerulean sky
i think it's best to test, but afaik the GUIDs of the scripts do not change, so it should work fine
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?
From what i remember, bundles keep a reference by name to the script, for example we once moved a class to another namespace and the asset bundle was broken due to a missing script
then i guess you can't use asmdef if you already know that it doesn't work
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
CC
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You can create SerializedProperty from object and property path, which is in modification, so..
yeah but how do i get the object
i tried to use the "PropertyModification.target"
but something was wrong with it
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
Nope "UnityEditor.PrefabUtility.IsPartOfPrefabInstance(item.target)" always returns false
Hmm alright maybe log what value the target is
Seems to be the gameobject the components are on
for each changed field
Btw Is there reason that you cannot use RevertObjectOverride or RevertPrefabInstance?
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
What is RootObject here, is it prefab instance?
Is PrefabUtility.IsPartOfPrefabInstance(RootObject) true?
"What is RootObject here, is it prefab instance?" yes
Huh I'm not sure why it have to run every frame
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
its because i didnt find a better way to trigger it
the point of the script is to make sure an object never has overrides
ever
and i also hide the children using "hideFlags"
Hmm not sure why this would be false if it returns true with Root
no idea seeing that "item.target.name" seems to be the names of the GameObjects holding the components
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
Here is the full code:
Runtime script: https://pastebin.com/RaHnRw6i
Editor script: https://pastebin.com/bvJLH5jk
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yeah at this point i have a few bodges that make it somewhat work
the prefab script runs every time gizmos get drawn and every frame if the component is at least once not collapsed
Hmm maybe it is something to do with hideFlags and it cannot recognize child object?
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
Oh nice 😌 So it remains mystery why property modification target is not part of prefab instance
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
Yes, it is necessary. Otherwise you can subscribe multiple times.
However you can use TakeUntilDisable(this) or AddTo(this) to make your code cleaner
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
Ah I see, so take until disable is just an operator that does what I did above with the indisable and the add to this disposes when the game object is destroyed right?
Yes
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.
chances are no one will give you private help
stack overflow is when you recursively call a method too deep
@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
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)
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
Hi,
I remember a website with a huge checklist to improve performance. I didn't remember the name, do you have any idea ?
Milanote?
No I think that was : https://thegamedev.guru/unity-performance-checklist/
The Gamedev Guru - Unity Game Performance Expertise
But now that isn't free anymore
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...
Why not Marshal?
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
In the case of Random it's helpful else you have to specify either System.Random or UnityEngine.Random in the code. This happens if you have both using System and using UnityEngine.
I'm never using System.Random anyway, but that's not my problem here
that's the one I ended up using, thanks!
I know, but Random will now automatically be the correct one of the two.
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 ?
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
.
thank you, very useful to know 👍
@turbid tinsel use this approach, except if you really need to cut off the rest of the symbols in Marshal, create your own static class with static methods and use the inlining attribute.
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
is this when u enter play mode?
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
no idea but u might want to check if the backup scene has it
@indigo citrus https://forum.unity.com/threads/unity-hangs-when-opening-project-in-visual-studio.1233787/
Backup scene?
Uhm how come the terrain layer is very faintly painted??
Just checked and I think that there's none cause I restarted the unity ;-
The scene just doesnt open
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...
either you check after the fact or generate such that overlap is impossible, no other options exist. Physics are a convenient abstraction to do it. Other option are more work.
so simply doing this as it generates isnt an option?
You’d not use that api
"OnCollision" is not a thing in Unity, even less so inside another function.
This is kinda #💻┃code-beginner or #archived-code-general stuff tbh
yeah i posted it in here without realizing at the time
Also please set up your ide correctly as #854851968446365696 describes
also I had it at OnCollisionEnter and it didnt do anything either
You’d use this for your use case https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
ok ill check that out thanks
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?
I don't think so but usually if you are looking for this functionality there's a better way to approach the problem than tags
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?
I'm afraid that you'd need to manually reset the states 🤔
Unless you run test separately per scene
I'm fine doing a scene reload, but the Dont destroy on load objects hang around still.
I mean you'd need domain reloading to reset static variables
Yeah, and I'm assuming that is just impossible
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 😌
Yeah, it will likely be running each independent
Yeah agreed
I'm almost making my own test runner at that point
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
I think I'll look at that. I halfheartedly tried destroying the ddol objects at one point but I'll revisit that.
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.
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
You can use Collider as the variable type, it will still be there, it just requires casting to access the fields that aren't included in the base type.
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.
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;
}
then I loop over each struct and need to spawn a gameobject with the same collider values
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;
}
Ah...
You need to show the whole code
Like where exactly is the line where the problem arises?
Because what you have should work
just in adding the correct collider to the object
and then copying over the values (just need to do each one so easy)
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
What were you trying before?
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
So... are you trying to instantiate a new object or attach a new collider to an object?
And does the object have a rigidbody?
what is this in response to?
no rigidbody
so...
new object and then attach a new collider to it with the same values as the AttachedCollider
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
And certainly isn't #archived-code-advanced for future reference
The main aim is to make sure I am able to make knots on this rope.
maybe ask for the source from profundum
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
Okay, so make one object for the physics palyer, and one for the view.
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
This is a college assignment, so perhaps that's not an option? Besides it looks like they are still making money from the game so they'd decline the request anyway.
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.
I don't think you need to reference it as an Action at all
So just assign your delegate to the ControlAction instead of assigning it as an Action and storing that as the ControlAction instead
Could someone please help me make the rope segments not slip through each other's gaps?
EDIT: Wording.
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.
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 ?
i dont understand them after 10 years yet use them 😂
I use them and everything works fine, especially with firebase and other plugins but you know 😛 I'd like to understand the flow of the code when I debug
I've found this one and maybe I'll give it a try
As in lambda functions or the method ContinueWith itself?
unfortunately I have to reference it as an Action because otherwise the InputSystem complains
maybe use friction
i didn't read the forum thread super carefully. you might have to dynamically change the friction of rigidbodies participating in a knot?
i'm not sure if a global using is supported
this sounds low stakes though
does anyone have experience with linker errors with unity cloud build and xcode?
not specifically with unity cloud build but with all automated building
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
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
what specifically do you want to change and why?
this also sounds #archived-code-general / #💻┃code-beginner
KK
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?
what is RayTracingShader? you can check out the ource and see if it uses the accelerated rt structures
those only exist on PS5 and DX12
raytracingshader is I believe how you access the hardware RT functionality
and ye im on dx12
i don't know very much about unity's specific implementation sorry 😦
ok thank you!
theres very minimal documation on it
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:
are you developing on an intel or apple silicon mac?
and is this the only error it gives you?
I am doing a cloud build on mac and these are the main ones they all seem to just relate back to these logs
I can send the full file if that is helpful?
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.
hmm so you're saying you are trying to develop for mac/ios without a mac?
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
Global using and aliases are possible in C# 10.0, but Unity only supports C# 9.0
I have applied a physics material but it doesn't help prevent the slipping-through problem.
No, it looks like just having a static setting should be sufficient for now. However, the participating segments must at least remain in the knot configuration.
did you try making the friction really high?
Let me test that right now!
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.
it's okay you don't have to do that
i'm not sure how to address this issue, i'm sorry
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.
Here's a video of the problem I am having.
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.
it looks like alot of the stuff you have in OnWillRender could be moved into a coroutine that only runs a few times per second, rather than every frame. I suspect this may cause a short lag in the reflections- but it sounds like you might be ok with that. You mentioned GPU power gets sucked up- but I'm not sure if such a change would help with that (but it WOULD help reduce CPU usage).
check out this for the coroutine stuff https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
Thanks
this looks to me like the links are slipping between the spaces between links. If you increase the connection force between the links, and reduce the space between the links, does that help at all?
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
it's where baked global illumination data is stored
it's a file generally shoved in a folder next to your scene file.
You might have it .gitignored
i resolved the issue by deleting the reference to the lighting settings in the scene tab, saving, closing, reopening, reassigning lighting settings, then reassigning lighting data asset
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
do objects in Resource transitively include their dependencies?
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
The result of LoadSceneAsync is AsyncOperation which has completed callback
So you can use it instead of yielding it
well setting the lightmapping is going to be a nightmare
It is nightmare 😄 and depends on "scenes"
So on complete, how do i access the loaded scene? Still use SceneManager.GetSceneAt or the likes?
why is the lightingdata.asset a binary file..
Yeah seems like there is no good way to fetch the reference, that's lame 🤔
https://forum.unity.com/threads/how-to-get-the-scene-loaded-by-scenemanager-loadsceneasync.1044790/
I guess to be completely certain, have the calling process claim a loaded scene by having a component in the scene hold a bool taken
And during any sceneLoaded (or async.complete), gotta go thru all of the scene with same name and check if the component is claimed, else check the next one
the same reason that texture data is binary.
text only makes sens if you have readable content and the lightbaked data is not text readable
I have camera smooth movement from somewhere else, how do i make it in my script?
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
isn't it just a bunch of references to files...
i'm not talking about the image data
it just goes to show how confusing and awful their lightmapping system is
where do you think is the light probe data stored
i guess it's in there
at least as far is i know
it's okay, i am writing a different workaround for this quirk
the only other data file that is binary is the terrain data
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
what is the problem here! Its everydays problem with damn charging cable. And so realistic that might make people go crazy
how do you guys code the max exp so it doesn't go way up to the sky
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
}
Hi all
Bumping this bcoz still having problem..
So i'm using Scene.GetRootGameObjects inside the SceneManager.sceneLoaded callback, but it says ArgumentException: The scene is invalid
So now i'm lost again. Is SceneManager.sceneLoaded getting called before scene is valid? I read it's invalid on MB.Awake, and valid on Start. So i guess sceneLoaded is before Start?
Not sure if this is by design, but it'd be nice to have a more reliable version of SceneManager.sceneLoaded
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?
I will try that but it will likely just destabilise the simulation by causing the rope segments to jitter.
Charging cables usually don't slip inside each other 😛
my cable does 😄 @regal olive
@abstract folio also, for your reference, here's the original post.
so your problem is the capsules slipping thru the gaps in between?
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.
I seriously doubt if it will keep the simulation stable. Still, worth a shot.
can also up the Default Solver Iterations and Default Solver Velocity Iterations in the Physics settings
I had to go from default 6 to like 32 for stable ragdoll simulation
Enable Adaptive Force might help too
How do I yield until a method is finished?
yield return InternetManager.instance.CallCheckConnection();
CallCheckConnection return void so I have an error
You can use an async-await method instead
Make both methods async, where the CallCheckConnection is a task. Await the method
The CallCheckConnection obviously needs to properly implement the async-await pattern
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
I'll let you know about these changes soon, say another 6-7 hours from now 😅
how do i get the GUID or path of a script's type?
what are you trying to do with it?
getting the path where the script is so that user can move the folder around and still link to the data
very cool - thanks
is there a way to do that from a type instead?
What's the best Steamworks wrapper for unity?
Since scripts need to be named the same as the type name you can do:
string assetGUID = AssetDatabase.FindAssets<MonoScript>($"{nameof(SomeType)} t:MonoScript")[0];```
I see, I'll try that. is that the case with editor script too?
Editor script is not MonoBehaviour, I don't think unity associate GUID for editor script classes.
no because there's no enforcement of filename == class name for editor scripts
I'm saying "they are not associate GUID with the class in the file"
Right yeah, misunderstood then
Anyone know how I can Reset a scriptable object from code?
Couldn't find how Unity were doing it from the CsReference repository
something could work along the lines of:
AutoPreferences mySO;
typeof(AutoPreferences).GetMethod("Reset").Invoke(mySO);
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.
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.
You can serialize UnityEngine.Object. If you want to serialize System.Object, your only option is to use [SerializeReference].
Oh I'm dumb, tyvm!
Is this kind of popup public for usage?
Yeah so like the Method should be public to be shown in the popup dropdown
You want that style of popup? https://docs.unity3d.com/ScriptReference/GenericMenu.html
The sub menu's are just strings with / in them
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?
I think what I'm looking for was this: https://docs.unity3d.com/ScriptReference/Experimental.GraphView.SearchWindow.html.
You can make a consistent simulation if you are updating the object yourself. Physics (as far as I know) is not deterministic in Unity. Meaning similar inputs result in varying outputs.
What you are seeing is compounding floating point error.
Why do you need consistent timing?
Tbh, timing is almost the same
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.
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.
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!
Well, you need to give us the bigger picture but the short answer is "No". 😄
You can decrease this variation by increasing the simulation frequency. Maybe instead of 50hz try.... 300hz?
Meaning physics and consistent timing do not mix well
Yeah, that is good idea, play with physics settings, increase simulation resolution for example.
Cheers! I'll try, doesn't have to be really perfect just enough to not be audible.
InvokeRepeating does not have sub frame precision. You can write your own that's more precise. And then simulate physics manually
look into https://docs.unity3d.com/2020.1/Documentation/ScriptReference/PhysicsScene.Simulate.html
Another idea yeah, maybe update your simulation manually.
But that's more involved and complicated. Maybe more than you need? Simulation frequency increase might be good enough
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.
Sounds promising.
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.
Hmmm these are extra expensive?
That is IF your platform is PC. For mobile it might be problematic with older devices.
Yeah. Its pretty sub optimal in my experience. If you have a lot of them it can get rough in regards to performance. Especially if there is a lot of objects on the colliding layers.
Seems good, still getting a stable 50FPS even while torturing the physics engine. I'm targetting PC anyway!
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
as an option you could consider using DOTS - the Unity dots physics and Havok physics are both (mostly) deterministic and are both boxed performant solutions which wont have you writing too much physics code, though it will mean integrating DOTS
Measuring FPS in editor is misleading. Measure in build if you really want true numbers.
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.
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.
Yeah, I considered it when I was starting this project, but I'm pretty sure it would be too hard for me lol
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.
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
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
I think it's like this because your spawning is using Update instead of FixedUpdate.
I would change the spawning to use FixedUpdate instead of InvokeRepeating.
Worth a shot, I'll try! The spawning interval can be changed in game, but it doesn't have to be more precise than the length of a fixed update, so that could work.
is there a performance penalty for moving a kinematic rigid body outside fixedupdate?
Well Update typically runs more frequently so you'll be moving it more times
but otherwise no. You need to be aware that transforms and rigidbodies are only automatically synced right before the physics update though
that's what i thought
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
send the code you're using to check if the camera is pointing at the objects
you should be using raycasts most likely
Yes i am using raycasts
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
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
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
This actually does help! I'll also change the other physics settings.
I'll give it a try
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 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
ok so you could add an additional check in the OnBecameVisible function
something like if (Vector3.Distance(transform.position, camera.position) < someValue)
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 ...
guys im pretty much disappointed
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?
is really Material property block useless in improving performance in unity todays unity 2021?
No it’s about marking shader prop with PerRendererData, not MPB
MPB has performance improvement ofc
well...thanks about it...i just got clear on another platform
But in a sense true, since MPB does not work with SRP
Hi devs, any idea on how to use a 2d irregular bin packing library in unity?
Read the documention. Follow guides/example using the library. Do your own experiments.
damn, thanks bro ahahaha
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?
Thats fine
the thing is that its not working
The value you put is too small for screen space positions
And it's not good way since it will depends on screen resolution
You should add recoil to resulting ray's direction
ok thanks
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
are you asking how to use nuget package / C# .net ecosystem library in Unity?
what is your objective?
you're asking how to create the player's targeting reticle? or are you asking how to author the boids style movement in this video?
why are you asking about the gizmo specifically?
@visual shore i think this is the most important screen shot
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...
You can just use C# library as long as it's built for .netstandard 2.1 and not using unsupported APIs...
that's cool
in principle you can implement an algorithm yourself directly in C#
it's not complicated
have you tried?
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
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
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
Try it in a build
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?
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).
@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?
What are you trying to do
keeping the mouse inside the game view window
DO you want the cursor visible and moving around?
Or invisible and stuck to the center of the screen
invisible and stuck to the center
Then all you need is:
void Start() {
Cursor.lockMode = CursorLockMode.Locked;
}```
you might have other code in another script setting lock mode to something different
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();
});
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 (:
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
hi is there a hit.textureCoord in RaycastHit2D hit??
here's my code that I wanted to convert in raycasthit2d
i have 2 way to do my job
- I set up a collider and use TriggerEnter
- I use check distant on Update
which more performance?
No.. there is no 'MeshCollider2D' so it wouldn't make sense.
Well since the result would always land on a border of collider, you could lerp texcoord from vertices data if you know which line that hit.
This would depends on how many physical objects on your scene and how many targets you're trying to check..
Do use the profiler if what you're doing is performance critical.
so I need a meshcollider for hit.textureCoord
You do
Thanks
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
Does ExecuteAlways not also execute ondestroy? 🤔
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
I think it goes on the class
Ah, you are right
I thought It was possible to put it on the method
Works now
ty
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
Warped Imagination on youtube has a video on how to use custom icons in editor windows
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
same thing
all these methods give these sorts of icons
I'm trying to find a way to get the project explorer prefab preview
I use Steamworks.net
Yeah, I ended up going with it, facepunch.steamworks was giving me trouble and it hasen't been updated in over 2 years
How would I make a gun shoot a bullet I already have a prefab do I just use instantiate?
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
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.
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?
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
^
- Why do a layer check in code? Just use layer based collisions
- Is it possible you're releasing the same object more than once?
and for 2 - doing the check before what?
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
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
You should put breakpoint and check each step and values.
Good idea, I forgot those existed
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
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
if you are getting a LoadFailedException you wouldn't know because you are catching it then promptly ignoring it. whatever tutorial you are following probably calls that AdFailedLoad method in the catch block in LoadAd()
for the gameId it's not the real i have change it for post here my code 🙂
i have juste copy paste this
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
did you try the example code here? https://docs.unity.com/mediation/SDKIntegrationUnityBannerAds.html#Show
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
with breakpoint i see, it's instantiate but never loaded
should I have two minus symbols? or do I need to pass "--args" first?
i have learn this code and it's the same of my code for show and instance my ad
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?
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
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 ?
Why are you using a meshrenderer with sprite shaders?
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
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
However the sprite renderer only works on ui or am i wrong ?
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
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
In that case, go compare the shader and see what changed
You can download unity's shaders from their website on the download page
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.
Two minus symbols
it turns out 1 minus symbol was fine, the problem was not related to the args. i think two minus symbols is for Windows?
Pretty sure it's for linux as well, but hey, if it works it works! It might be more elastic in linux
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
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
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?
What are the requirements
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
If you want to limit the framerate, you can use Application.targetFrameRate = 60 but I think it's somewhere in the project settings too
It's rendering
CPU waiting for GPU
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?
understood the problem
alpha blend shader calculate the all the pixel beyond a gameobject
its the main cause to buffer
that is an unusual mesh
why are you using the sprite material @vocal dagger #🔀┃art-asset-workflow
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.
What type of coding can you do with Python within a game engine, do I need to think about creating tools?
the official unity python package is editor only
Within Unity? Almost none, other than creating external plugins.
There are python based game engines like PyGame
Sometimes i read think like scripting that can be done with Python to create tools for engine like blender, unity, unreal whatever.
Blender uses Python as a scripting engine, yes
everything in unity uses C# except for the core internals that use C++
try to use cutout instead of blended for leaves #🔀┃art-asset-workflow
yes, you can create tools for unity using the official unity python for editor package
that is the idea
That's still Python language?
It's not called "Boa Constrictor" now is it?
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.
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??
What specifically can you present to a company, to show off you coding skill, without being to much busy with, level design or whatever.
i see, are you a student?
Not really.
No
this is a really hard question 😦
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
I just try to narrow down what projects I can work on and what technics companies wanna see, so I have better focus and motivation. My main focus is mostly game play programming.
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_SomeNumberstructversusclassused 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 xyWZversusAuthorization: [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
if you checked all the boxes in the good column and none of the boxes in the bad column, i would make you "Director of Game Programming" if that makes sense
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
what's wrong with writing custom state machines?
to me it just means you haven't ascended yet
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
huh ok
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
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
instead of using a coroutine (good) or an async UniTask (better)
or a plain C# async Task?
or a tween
no because that means you don't know yet that plain C# async is flawed in unity
plain c# async has glitches in unity
async void Start() for example is really problematic
yes, the non unity c# stuff on the good list
like functional / reactive programming
Ok
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
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
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
that's fair
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
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)
@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?
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
event system
or input system for those rare non touch games
use unitask
almost none of this will do what you think it does
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)