#archived-code-advanced
1 messages · Page 165 of 1
Ok, this is for a WebGL build on a game jam.
There's probably something I'm forgetting though.
So .Net Standard is the way to go.
If you want broader compat, yes
Unless you have a specific reason to use .NET Framework, then yeah go Standard.
Framework is dead anyway now, they're not updating it anymore. Waiting for the big switch to .NET5 or above
Yeah. Microsoft wants .NET Core everywhere, so .NET 5.0+ are all .NET Standard-based.
.NET Framework was from the time that they still wanted to leverage C# as a Windows selling feature.
It's hard to tell actual revenue of any given product because Microsoft plays the shell game with their divisions, but they're now focused hard on Azure, so .NET is focused on cloud development, which means Linux needs to be a first-class citizen, which means .NET Framework needed to get eclipsed by .NET Core.
But, even though .NET Standard is newer, it's not a 100% replacement for .NET Framework, so both hang around.
standard actually excludes non compliant features or they are unlockable somehow?
You mean in Unity? Unity maintains their own Mono runtime.
Or do you mean in, like, .NET 6 console applications?
There's some Swift only Apple API I'd like to write a "wrapper" around, and I'm considering my options
Is the easiest route to go through the painful experience of writing C wrappers and the call into those from Unity?
Is anyone familiar with a tool for getting currency symbols for given countries based on country code?
I've also thought about going the IPC route, maybe with something like Foundation.NotificationCenter
We're doing Swift wrappers right now. ObjectiveC calls appear as
[DllImport("NameOfYourDylibWithoutTheExtension")]
private static extern returnvalue your_exact_function_name(extact_parameters parameters);
``` Note that these require restarting the editor if you change the dylib. (Once it's loaded, it stays loaded.)
You can work around this by doing dlopen and stuff... but it might be easier to just close and open the editor.
Do you @objc your Swift files types and functions, or does Unity just eat them as is?
We have an objective C header file to bridge... ... ... not sure if you can do it directly from Swift with an @objc attribute. Maybe?
All the ObjectiveC code does is maybe convert parameters and then forward into Swift.
but this is all just functions, or can you also pass types into Unity?
It's things with a C ABI... which means blittable types (ex: float[] appears as float*).
Objective C wrapper is basically a C wrapper, yes.
The benefit comes from forwarding those C calls to... ... ... a not-C language lol.
Personally, I'm a fan of C++, but that might not be ideal, especially if you're interfacing with Cocoa or something.
I mean fair
It's that Apple hasn't exposed GroupActivities API to anything but Swift:
https://developer.apple.com/documentation/groupactivities
I should note that I'm not tooooooo into macOS stuff. Only picked up the platform when I joined LightTwist a couple months ago.
Before that, I've never owned a Mac.
So I'll have to write a lot of wrappers around this XD
Yeah...
Probably best to boil down what you need to a handful of C function calls, and, using swift on the other side of those C calls, expand into the actual stuff.
Add as you implement more stuff that needs to talk to Unity.
Hopefully the initial isn't too bad.
I'll just use this for the type, and then write as C-like API as I can, and then wrap that in as C# like API as I can on the other end:
https://developer.apple.com/documentation/swift/opaquepointer/
and then use... protobuffer for like more extreme types
That's one option. We haven't gone to this length yet, but we were planning on sending JSON and/or Protobuf across our C API.
Gets more complicated because the other end of the C API is mach_ports into a completely different process.
Scott since we think so alike, can you hire me :P
makes it perfect to just use protouf!!
I tend to get scared when heavy dependencies are added... although the other devs are happy with it.
I just thought about it, maybe I can just use protobuf Unity <-> Unity, and have the Data / unsigned short[] passed through the bindings
Yup. Just make sure it's clear who owns what.
But, for the duration of a function call, that's not too bad.
because there's no reason really to decode the handle the date outside of Unity
I'm curious what you're using mach_ports for in a Unity project, but that's really not my concern
I can't really comment either way I really have no idea what you're actually doing lol.
We're communicating with a Cocoa application.
I'm planning to write a Unity wrapper for SharePlay
It might be a little more low-level than necessary, but it's an architecture that works.
SharePlay is almost as high level as they get XD
Hi!
What is the correct component to use when spawning a dynamic amount of buttons on an axis? (1-10)
You probably need to write a custom component. You want a class with a public endpoint that receives an integer, then creates that many button objects? You can couple it with a LayoutGroup and LayoutElements to have them automatically spaced/positioned/sized in an area of your choosing. Is that what you're going for?
That sounds correct. At the moment I'm testing it with GridObjectCollection, instantiating prefabs and then updating the collection.
But I would love if I could test the instantiating part inside the prefab editor.
That would indeed be helpful. I simulate this by entering the prefab editor via a prefab instance in my scene, placed where it will actually be, then Unity at least retains the layout and graphical appearance of the rest of the scene while I edit. Then I can drag and drop my button prefabs inside to make sure they are correctly positioned.
I want to have a function where the number of buttons corresponds to the number of files an Assets folder. What do I expose in the inspector, and any tips on turning audio files over to audio clips?
For counting files, use https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=net-6.0. Then you can iterate over them and check their extension if you want.
For converting audio files to audio clips, use https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestMultimedia.GetAudioClip.html
I'm essentially loading short audio clips to work in a sequencer, should I structure that around StreamingAssets or Resources?
Re: WebRequest
Ahh I see. Sorry, I'm not sure on that one. Scratch what I said about GetAudioClip, there's probably a better way to do that with a tool like one of the ones you mentioned
Nice, looks good. Small optimization: change the type of rowPrefab to Sequencer, then re-assign in the inspector. Then you can spare the GetComponent call.
Oh, does it only return a component from the instatiated object then?
Yes, Instantiate will return an instance clone of the same type of its first parameter
So it will hand you a Sequencer instance ready to use
But rowPrefab is a prefab, and Sequencer is a component. Tried what you said but didn't work.
Oh wait
rowPrefab happens to be made into a prefab but it is of type Sequencer, just as it is of type AudioSource, Transform, GridObjectCollection, etc. It is of the type of all components you assign.
Part of unity's somewhat confusing component oriented structure
Did you get it working?
The crash is probably unrelated to switching rowPrefab to Sequencer type
As long as the Sequencer component is assigned to your rowPrefab GameObject and you've assigned the prefab to your rowPrefab field on whatever class that is, that should be good to go.
Wait is there no autosaving in Unity?
Scenes are backed up during a crash but are wiped as soon as you reopen Unity
You should be using a form of source control regardless
I did, until Unity tanked my Teams pipeline and I can't get Plastic to work properly
Stuck on the good ol'
[Collab] Archive::ArchiveError: Unable to perform requested action on a project that has been archived. To unarchive this project, navigate to the Developer Dashboard at http://developer.cloud.unity3d.com and click View Archived Projects. Select the 'Unarchive' button to restore the desired project.
on an un-archived project
How about good ol git hosted on GitHub? 😄
How did Unity manage to break your previous version control solution? Not exactly sure what Teams pipeline refers to, but I'm assuming Azure DevOps?
Used Unity Teams to transfer between 2 PCs, suddenly it broke at the start of January. Refuses to sync.
You most likely won't suffer from these magical errors with external source control solutions
True
Think I gotta go there
Furthermore, I need to instantiate a button that then needs to be linked to the object that instantiated it, responding to clicks of the button. Do I need to do a "when pressed: transform.parent.something" or is there another way?
Need to create this event at runtime
you have to write a plugin. you can buy a prime31 plugin and see how they organized theirs
I'm making a motion capture app and seeing "prime31" really confused me for a bit there
you have to report this bug to unity
What are the differences between these two?
nothing that really matters
One pretty straightforward solution: have your controller class pass your button instances one of its methods in the form of a UnityAction<int> or <float> (whatever that value type is) in a public initialization method after they're instantiated. Have them cache the UnityAction, then invoke it when they're clicked, passing whatever value they need to back to the instantiating controller class
it sounds like you need to use unirx @arctic robin
if you want to do complex stuff iwth events
I think(?) I tried a version of this, but it somehow just ends up sending 5.
you don't quite yet
for(int i = 0; i < buttonAmount; i++)
{
GameObject button = Instantiate(buttonPrefab, new Vector3(0, 0, 0), Quaternion.identity, this.transform);
//button.GetComponent<Interactable>().OnClick.AddListener(() => RadioClick(i));
button.GetComponent<Interactable>().OnClick.AddListener(delegate { RadioClick(i); });
}
Due to the complexities of variable capturing (closures) when using a delegate inside of a for loop you need to assign the indexer to a local variable before using that in the delegate
for(int i = 0; i < buttonAmount; i++)
{
int localIndex = i;
GameObject button = Instantiate(buttonPrefab, new Vector3(0, 0, 0), Quaternion.identity, this.transform);
button.GetComponent<Interactable>().OnClick.AddListener(delegate { RadioClick(localIndex); });
}```
Never knew why that technique wouldn't work for me before, ty
Awesome, that worked perfectly ❤️
Is there any way to keep certain components from spawning before others are loaded?
What issue are you trying to solve?
I'm using another library, and it's designed to instantiate parameters in the inspectors before runtime. I'm however creating the variables during runtime, resulting in it complaining that certain fields are empty.
At the moment, all my functions are using Start() as opposed to OnAwake(). Could this be a potential solve?
Furthermore, Unity is taking a solid 10 seconds to unload after I stop playing. Any common reasons for that?
Specifically, this line of code.
Time.UnscaledDeltaTime ignores the time scale right ? I want to create a slow down up mechanic for spesific objects only but doc says unscaled its best fit for that its ignores the time scale but when i change time scale unscaled delta time values are changeing how can it possiable ?
Yea you could set it up in Awake. These things are pretty situational. If the library component is on a different GO, you could try instantiating it later
There's also DefaultExecutionOrder attribute if you can't find other ways
Got it, noted.
At the moment I'm having trouble spawning a prefab correctly lol
I keep getting this error from this code:
SequencerDriver childDriver = Instantiate(blockman, new Vector3(0, 0, 0.5f), Quaternion.identity, this.transform);
RowsConstructor asd = childDriver.GetComponent<RowsConstructor>();
Debug.Log(Sound.Bass);
switch ((Sound) sound)
{
case Sound.Bass:
//asd.sound = Sound.Bass;
asd.SpawnMe(Sound.Bass);
break;
case Sound.Lead:
//asd.sound = Sound.Lead;
asd.SpawnMe(Sound.Lead);
break;
}
Does GetComponent not work if it's not a GameObject?

This could easily be solved with a prefab variant, but from what I can tell, the variant doesn't derive any further changes to the original prefab, like position, size etc.
Question, haven't really worked in Unity for over a year but more with C# itself. Now I'm back trying to make a nice game. Now I want to create one SceneManager which holds all the code to use on buttons inbetween scenes. Now what would be the best way to assign the OnClick functions using this SceneManager object as DontDestoryOnLoad()?
Hi, I need little bit help related to jsonUtility;
I want to store Dictionary in json format, eg Dictionary<float,customClass> foo
It's not directly supported. Use Newtonsoft JSON or look up unity serializable dictionary
why not suggest System.Text.Json?
Newtonsoft is much more robust and free, there's almost no reason not to use it afaik. It gracefully handles nested object serialization, custom converters, OnSerialized/OnDeserialized callbacks, and more
At the same time, if you only need light JSON functionality, System.Text.Json is perfectly fine and saves you a package import.
true and fair
hey is there a way to render a mesh without indices in unity?
we dont have that in unity i thought
Oh you're super right, you'd have to add the System.Text.Json dll if you wanted to use it. I thought they were referring to unity's JsonUtility, my mistake
Graphics.DrawProcedural should be capable of that.
Anyone familiar with nativegallery?
anyone here familiar with MLAgents? I'm getting basic code throwing an error(in editor, won't compile) that's basically a copypaste from documentation, and I can't seem to figure out why. been stuck for 2 days...
Try asking in #archived-machine-learning also?
Anyone know how to read input while the window is unfocused I'm trying to use ovr and send an input when the home button is pressed.
Hey guys, im getting an invalid typecast here when i try to downcast to an inherited member. How to fix?
nvm just used as Type instead of (Type)
fyi I think the is operator is a better fit for what you're doing. I'm assuming HeroExtension and EnemyExtension are mutually exclusive
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#is-operator
if(target is HeroExtension a)
{
// Do hero relevant checks here
}
else if(target is EnemyExtension b)
{
// do enemy relevant checks here
}
You can also do similar in a switch statement
Not only do I want to implement acceleration gradually rather than instantly, but I also want to implement slope physics to add on to that.
Is there any references that can help?
why does my projectile bullet can moving through walls with continuous collision detection?
May be going too fast for the collision to keep up. Use a Raycast to check coillision instead
Like for the update frame, raycast from the previous position last frame to its current position, and if something is in the way, consider it collided
really! i'm an idiot)
Thanks a lot
You'd first build a really efficient spatial lookup datastructure then implement your collider shapes in a nice and computationally optimal way, then come up with some collision detection mechanism based on shapes and the spatial lookup, then you'd implement a collision resolver that can separate overlapping shapes, maybe add some simulation of mass, drag, friction etc and then you run that 50 times per second, cry for a bit as your performance goes to the toilet and then start spending the rest of your near-to-midterm future getting it closer to where PhysX, Havok and other systems already are. Eventually you'll need a neat API for it all and you'll implement raycasts, rigidbodys, colliders and more specialized versions of those.
maybe you should come up with that yourself then if its for a work test
not gonna help you cheat
plz tell me you're interviewing for a job doing nasa simulations or something. this is giving me a headache just thinking about it lol
what would be the purpose of that?
Not really no
You can publish the source without publishing the assets (that you are not allowed to redistribute)
I think a private repo that you include using submodules/subtree is the easiest
oh... yeah that's a dead end
I have this code for "flashing" the Windows process icon on the task bar
static extern int FlashWindow(IntPtr hWnd, bool invert);``` Which works on WinForms when using ``Control.Handle`` (IntPtr) but it does not work when I try supplying ``Process.GetCurrentProcess().MainWindowHandle`` or ``Process.GetCurrentProcess().Handle`` Can anyone help me here? I want to be able to flash the process task bar icon on command
I want to flash my Unity game process icon in the Windows task bar for instance when a multiplayer game is found and Application.isFocused = false so that the user will know when they've joined a game
I'm not sure how to get the proper handle to supply to the user32 FlashWindow method, because clearly Process.GetCurrentProcess() isn't working
Async methods continue to execute when you stop the game in the editor, what the best way to stop if from happening
worst part is prefab clones are staying in the scene even play mode is off
Hello everyone. It is unlikely that anyone here will help solve my problem, but maybe they will be able to suggest some idea or rethink the existing one. I'm doing a Bullet Hell, that is, I want everything to be normal even with a few thousand bullets, so I gave up GO in them for a long time (except for visualization, but this is not particularly important yet) and I seem to be satisfied with performance, but I understand that I don't even check collisions yet and always need more, especially for mobile phones. That is, I decided to rewrite everything to Jobs (I will immediately answer that I don't want to switch to a full-fledged ECS, because I want to solve the problem somehow without it (since I've been suffering for so long, heh), and then only bullets will then work on it, because I want to write the rest on OOP). In general, I mean that so far I'm collecting the behavior of bullets like this ( https://cdn.discordapp.com/attachments/910812777709441025/910896056554905650/2021-11-18_17-11-49.mp4 (the old video, but not the point is important)) and these elections, factories with a date field were created, which are structures, and there the logic of the motion component was already called on polymorphism. What happens is that I don't need factories and components with logic anymore, so I decided to take IJobParallelFor and write "systems" and that's where the main problem begins. I also have general bullet data (by type of position, rotation, size, etc.), and there are dates specific to a certain movement system. And the whole problem is that how to transmit to all systems only the positions (or other general data) of the bullet she needs now? Otherwise, I simply will not be able to start all the motion systems at once, since they will use the same NativeArray, thereby jobs system simply will not be able to understand that I am not violating the race condition, although I know that I will definitely not violate it. And in general, so far I have only a few ideas:
- Store NativeArray in a certain "updater" that simply launches the desired system and stores an array of indexes (NativeArray<int>) from the general data. But then, again, all movement jobs will be waiting for each other, and not immediately distributed in a reasonable way. And then the additional taking of indexes, although it probably still turns out to be productive for the ideas given below, except when the latter;
- Store everything as above, but make copies using for (well, you can do it through UnsafeUtility, but for you need) to prepare a NativeArray for the current frame. Then I'm sure with a high probability that everything will be distributed correctly, but then it's just a bunch of copying, which I think is terrible, since I'll have to copy everything back after work.
- Remember the ECS Unity and think about their ideas of archetypes and chunks. That is, my idea is to store them in a row in one array for each group of systems (motion systems, systems etc.), and then create slices (subarrays) of these errors. That is, I will be able to achieve confidence that everything will be disassembled at the same time, but I will still have to copy the general structure, because they can still change in theory in another group of systems (for example, a magnetic bullet or, when destroyed, a bomb will create a shock wave that will scatter bullets around). But this is definitely a productive second method, although maybe if someone knows how Foreach or a filter works in Unity ECS, well, or in another ECS (that is, it finds only entities with the necessary components (although, to be honest, I can guess how to do it myself, the only question is how to put it all into native collection and productively parallelize))...;
- I'm forget that have been suffering for so long and do it normally on ECS Unity (but don't switch to drawing using DOTS, but use it only purely to calculate data), but then it will probably be less manageable. Well, in terms of what, where and in what order to call.
Cancel them with cancellation tokens
Thank you kind sir/madam
Might be overkill but I created 2 separate classes to do so:
And you can see i have a static CancellationTokens that deactivate on scene change or when the game stops
this is some good 💩 , gonna have much fun by discerning it
Good stuff, but I can't help myself, I suggest looking into the recommended IDisposable pattern to help with the terrible GC
What do you mean, I'm using the IDisposeable.
What do you suggest I should change?
Thought maybe that will be useful as well (I tried imitating all features of courotines, like the way they stop when the object is disabled or destroyed):
Most of the time you don't really need to worry about your code performance, until you do
GC is one of the most heavy operations in the CLR
But then again, its until you do need to worry about it
Just to be clear, your code isn't terrible... I meant the runtime CLR garbage collector is terrible 😛
Your code is actually pretty good, it's just that it's not completely conformant. I'm really just nitpicking
I have a very similar implementation in Xamarin, it should work nicely
I want all the nitpicking you can give me! 🙂
This code is battle tested, but I admit I usually don't mess with the GC operations at all, good chance that it's a place for improvements.
Any way, thank you.
If you're using the Mono backend, then you can already assume the GC is terrible
Which is why you want to enforce suppression on finalizers if the object has already been manually disposed
Ok, I'll read the link you sent me.
Just keep in mind, GC isn't the save and grace for your code. It's just a massive thing to keep in mind
Hi. I am creating Animation component upon gameobject using script. When I set parameter using SetFloat and return it back, it returns 0. Is there something I miss? For example setting of new runtimeAnimationController or something?
I've tried bodyPartAnimator.runtimeAnimatorController = new AnimatorOverrideController();
but without luck. I am getting this message back "Animator is not playing an AnimatorController".
Just from what I've seen in Unity, GC takes A LOT of time, especially compared to other components
I tired to implement,
demo = new Dictionary<float, Vector3>();
Debug.Log(JsonConvert.SerializeObject(demo));
JsonSerializationException: Self referencing loop detected for property <- error i got
works fine with normal datatype but vector3 seems like unsupportable.
maybe since the Vector3 is a unity type?
idk I don't know much about serialization
you could make your own Vector3 though by just having 3 floats x, y, z
yeah, its working with normal float x,y! 👍
is a scene gameobject InstanceId a good way to save reference in ScriptableObject?
Afaik there are no stable IDs in builds. What are you trying to do?
to save the ID of specific Scene Component in scriptableobject used as state for my statemachine
Unity employee couldn't save references across scenes without creating a separate ID system. https://github.com/Unity-Technologies/guid-based-reference/
Well the across scenes part isn't too important, since I still don't think there are any stable IDs left in the build.
That's editor only unfortunately.
https://www.toptal.com/developers/hastebin/olalucoqos.csharp
I'm using this piece of code to generate platforms which guide a ball towards a goal (trick shot style) using PhysicsScene.Simulate.
The code works perfectly when the validation logic is not triggered, and GeneratePlatforms runs only once.
The trouble is whenever the validation logic is triggered, something often goes wrong with the path generated: platforms in the beginning or middle don't appear, causing the real ball (since the path is traced by a "fake" ball) to not follow the generated trajectory.
I need permission to provide the full source code but I can help set up a basic project to reproduce the issues.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
fuck!
my entire StateMachine doesn't work in build
it seems that the Machine doesn't read the ScriptableObject of the transitions
it lose the dictionary values in build with IL2CPP
public readonly Dictionary<string, StateDataSO> states;
this value works in editor, but not builded for android with IL2CPP
hey is it ok to throw exceptions in unity? or is it prefered to return null. curious if exception throwing crashes the app
exceptions are caught by the engine and will be converted into an error-log message
If that's the terms of service then every large company is breaking them including unity
any ideas what these files could be? never seen them before and now they are just added randomly. I did recently switch from visual studio to rider to try it out
Yeah that's rider metadata
awesome thank you
i see. yes, unfortunately private submodules are your best bet
if you'd like to minimize the number of private submodules you have, you can create a private unity package repo, and install your asset store assets there
and just reference that 1 package
hope that helps
yes in my experience you can add .idea/ to .gitignore
oh
you can definitely commit assets to a private repo
are you saying you want to put this in a public repo?
How to round 0.9999 to 0.9 ?
- 10, floor, / 10
0.9999 * 10 == 9.999
Mathf.Floor(9.999) == 9
9 / 10 == 0.9
Just make sure they're floats all the way, otherwise you'll stumble upon integer division
so what? now im confused maybe i should i writed in beginner or general x)
if its 0.99999 its a floats and i want the numbers to be 0.9, i did try ToString("0") but dident work
Oh you just want to format the float so it appears with one decimal? You should have said that
theFloat.ToString("1F");
Will work fine
Or "1F", if that doesn't work
Yeah it's "F1"
Note that will round the number, so in your case it'll display 1.0
If you are using an interpolated string you could do {theFloat:#.#} to format it to one decimal place without rounding
That rounds too unfortunately
Does it really? 🤔 I guess I misread the info
So without rounding, apply the multiplication, flooring, and division method
haha what?
This
Yeah you really shouldn't have posted here frankly
It's a formula, some pseudo-code
To truncate a number to one decimal you need to:
- Multiply it by 10
- Floor the result
- Divide the result by 10
And avoid cross-posting.
yeah but u gave harder answer so i asked somewhere else lol
It's #archived-code-advanced after all, expect advanced grade answers. Cross-posting is against the rules
So if you post and get answered in one channel, stick to it
hey how do i use assembly in unity
I'm bored of following C sharp's rule
I want to make my own rules
fr
anynoe
You can't
Because Unity is backed up by a closed source C++ back-end, and you would need to modify that to integrate another language support
And since you don't have access to that ¯_(ツ)_/¯
ammm
You can make native plugins. It's an easy enough Google. But the question itself is disingenuous spam that would be better off not being asked at all
Yeah this, if you want to code in asm, find a game engine that supports it
how did u guys learn unity
Or make your own
engine
This isn't a question for #archived-code-advanced , go back to #💻┃unity-talk and don't spam random questions across the discord
Ah, yes. They want to code in asm because they don't understand the C# beginner tutorials. Great
are u mod?
100% troll
Octagon?
It means "stop"
🛑
And yes, they're a mod. It literally says that if you click on their profile
I don't believe my eyes
It's not gonna end well for you mate
help?
Don't ping people into random questions either.
Hello can someone point me to a tutorial on implementing a placement system which allows dragging objects from inventory into the world, in first person. thanks 🙂
Thank you I will check it out!
are there examples of project tiny projects that use nicer, baked, non lo-fi rendering? is this possible to engineer with project tiny at all?
okay
i see that project tiny has been graveyarded
my sincerest apologies
Wait it has?
i don't think there's anyone working on it at unity anymore
it kinda flashed briefly, then sank.
"[0.32.0] - 2020-11-13"
Is there a unitygraveyard.com like googlegraveyard?
whoops, killed by unity*
yes Unity Engine
a collection of half finished libraries we call engine
I need a mod here. Someone just murdered someone.
lol
Yep.
Imagine to my surprise that using the new input system, it doesn't work on linux (I think it was linux?)
Tho I think they added linux support finally to it
It used to be so simple..
Then they started trying to pander to everyone..
Render pipelines.. package manager.. is this feature in the version I'm currently using? GitHub? Why is it on GitHub? Oh alright.
Also, let's rip out the networking layer before we have a replacement ready to even beta, let's see how that goes
Any external hardware you guys bought that help you program? 
Maybe a certain kind of monitor, usb hub, just stuff to make your job easier or enhance it
Just got a USB hub and quite frankly it's amazing 
is there any tutorial for random block generation pros
depends how pro.
you can look into Daniel Ritchie who authors the most approachable language and tutorial for probabilistic programming in procedural graphics
which is like an Intro to Pixar Stuff
not unity specific though
Hello everyone. I had an issue where I had an instance running for the game and I wanted to avoid a second instance for the game to run. I solved this by using the PlayerSettings.forceSingleInstance setting. Now I had a question, what if I wanted the second instance to fire a method on the first instance before it quits.
A couple of things come to my mind but I'm all open for options. First one was to have the script that would be used to fire the method at the top of the script execution order. And then I'm unsure of the part that comes after. How do I fire the method on that game instance? How do I find it? And after finding it, how do I execute a method on there preferably with parameters?
Using PlayerPrefs was one of the things I came across but I wanted more opinions on this.
maybe using getprocessbyname, at least if it's running on desktop windows?
https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocessesbyname?view=net-5.0
And after that maybe firing the method using Process.Start()
Process and its namespace (partially) is not available in windows il2cpp
i would suggest you to use sockets. Sockets work on literally all platforms unity supports.
In your application, try to connect to local port on some port, say 1234.
When the connection is refused, create a new port and listen to that. Add a try/catch over the bind logic to maintain concurrency incase both applications are launched at almost the same time.
Then when your 2nd process sees that it can connect to that port 1234, just shoot your message over to the first process and then close the 2nd instance manually using Application.Quit
So I tried to search a bit and found pipes, specifically named pipes.
Would that be a bad implemetation?
Again I'm not sure about the compatibility of it but since it's C# I assume it would work well with other platforms.
Yea, I saw that and in my previous experiences it's been very un-reliable. Especially when dealing with different platforms.
anyone?
named pipes is a part of ipc which is provided by Windows Communication Foundation (WCF).
I have never tried that in unity or anywhere outside of windows.
You can still implement the piping in c++ for all the platforms yourself if thats what you're looking for
I've actually just seen a video for it and I was planning on building that function as a separate DLL and importing it into unity as a plugin.
In the video tho, it was explained that the implementation for it work well on editor but fails on 64 bit versions.
And so would have to be build on 32 bit, so just lost there as well.
editor is 64bit backed by mono.
you should have no issues in making 64bit mono builds
Also the reason I was avoiding sockets is due to security reasons. Since I'm not very good at security related to sockets in general.
Ah okay. I wonder then if the person was using IL2CPP.
Since that's what I'm using.
if you are avoiding sockets, try MemoryMapped files in System.IO?
it should be there in Unity although i can't verify if that works
MemoryMapped. I can try googling it lol
Thanks for the help. I've got named pipes implemented in a test app for now, gonna build it soon and will share my findings here.
If it build or fails etc.
i need help for exposed reference
I found this video that make it works
Keep reference to scene objects from asset
Unity hack : Pirate Captain Logs
Source: https://www.patreon.com/user?u=7678785
Please LIke the video not cos of my EGO cos of ranking and more people get help.
but I can't reach to achieve the same result
is there a way so that when I respawn, the button I'm clicking will be deselected?
EventSystem.current.SetSelectedGameObject(null);
it doesn't seem to work tho
youre never releasing your mouse?
yeah
it's for the ebrake
i have it set to toggle on and off
but when I respawn, I want it default to off
even tho i respawned with it on
well in that case, use images with IPointerUpHandler and IPointerDownHandler
when you press, IPointerDownHandler is used. toggle isPressed bool to true and start accelerating.
when you die, just turn it to false. so it will have to be true again only when the user leaves and presses mouse again
I am using IPointerDownHandler
then use the rest
explain please
I already did. I dont know how to explain more than this. If you're new to unity, you would have better luck in #💻┃code-beginner or #archived-code-general
Are you referring to section 3.8 here?
https://unity3d.com/legal/as_terms
then yes, i'd use a submodule or a package referencing a private repo
containing the asset store assets
that will satisfy the terms
what's the objective?
processes communicating with each other is always painful
names pipes are really painful
the security of a named pipe and a socket bound to 127.0.0.1 are basically the same
there isn't a real scenario where listening on 127.0.0.1 exposes you to a security issue
so i'd suggest just using a udp socket listener on that address.
that said you can only have exclusive use of a port. very painful
The objective is the use custom URL schemes and launch the app. That part is simple. But to do so if the app is already running and have only one instance while having the arguments passed through. The reason I'm avoiding sockets is that the arguments might or might not contain some stuff which I wouldn't want someone to catch in the middle.
you mean for the purposes of implementing a login?
Sort of yes.
Nope
okay
So what are you opinions? Would really like to know.
i don't think there's a threat where listening on 127.0.0.1 opens you to a security issue
i don't know how detailed you want me to go into convincing you
So me opening a port locally. That's good. Someone with wireshark or something similar might simply see that the port is opened by the application, and not to mention able to sniff the packet. That's my concern here.
what scenario is it that a local user
who is seeing the deeplink url
would be now untrusted?
why would there be anything important about this packet?
you could just forward the exact deeplink url they clicked
surely that's not private?
so you can... start your second instance on a clickthrough of a deeplink url, and then message the deeplink URL over the socket to the first instance
there. nothing "proprietary" is shared
a named pipe, which maybe just obscures this stuff, isn't any more secure. but in reality, exactly zero people on earth will ever be bothering with this
The thing is, when using something like OAuth (just for example), you login on a web interface. You put in your credentials and then you get a token which is then passed onto the application. IF in case the API end points are compromised by any number of methods be it de-compiling or anything, the said person would have access to update the data. Not saying we couldn't flag it, but just trying to make it harder for people.
okay... but you're not implementing oauth correctly
I did say it's an example lol
so what are we talking about? is oauth the goal?
what do you mean the API end points are compromised?
then they're compromised. i suppose the threat actor could do anything
they probably have access to the database if the API is compromised
so it really depends on much detail you wanna go into this
They could only do it if they've got the correct clearance, in this case the correct tokens.
anyway, the end user already sees the deeplink url
I mean, I'd like to know your point of view, in a constructive manner ofcourse.
yeah
well the most straightforward answer is that no one is going to compromise anything, you're too small beans
but even in this conception, if you can't trust the user's machine, this is impossible
Alright.
zoom doesn't do anything special. it is just a deeplink with this meeting code id
once it hits a local zoom app, it doesn't really matter how they implement the details
it's not any more or less secure
depending on how they deal with this Windows UWP thing
which by the way, i'm surprised it starts 2 instances in UWP
on iOS it does not
So just going back a bit, named pipes do obfuscate a bit right? We're not trying to make it impossible. No we don't do that for someone snooping around. It's just that we could make it harder.
i think listening on a local port is pretty obscure
i don't understnad though... why would someone bother snooping on the port
they could just snoop the browser?
if they have access to the local user's machine
like why bother
it just doesn't make sense
are you trying to protect from the user? the deeplink URL they clicked on?
They don't click on the deeplink.
it doesn't make any sense to run an RPC API over a named pipe
Ugh
what do you mean?
"The objective is the use custom URL schemes and launch the app. "
Have you seen how unity does the authentication?
are you making an authentication app or a lobby code?
are you trying to do oauth?
what are you really trying to do?
I'm unsure if this is productive anymore.
i just read your question over and over again and it sounds like you want to use custom url schemes
But yes. It's an oauth process.
Yes but I wouldn't be using deeplinks directly.
"how unity does the authentication?" do you mean an official Unity.. authentication library?
The official unity.
can you link it to me?
You can try to login to your unity account using the editor.
Dude, it's not inscribed anywhere lol
it's okay
It's the usual oauth2.0 and then loopback url to the unity hub app
so is your objective to implement oauth2 login for a unity app?
and it sounds like you're working around some peculiar issue?
and you're thinking of using a custom scheme as a redirect URI?
Yes.
okay
so why didn't you say so 🙂 ?
i don't think a named pipe will matter here
anything can snoop on a native app's token that it gets from oauth2 flows
Just that the actual function is similar but still different. Hard to explain but yes the use case is the same.
hmm...
Yea
I know we can't make it impossible.
it isn't ever going to be obscured
But we can make it harder.
it's a colossal waste of your time to try to obscure it
nah
i mean you can say that in sort of a fantastical way
but all you're doing is making it harder for you to program
Nah lol. If it was just that I wouldn't bother
But it's gonna be a bit of sensitive data. And I know the "small beans" thing, but please humour me.
is it a crypto related thing?
Nope
then what is it
It is a login. Yes. But mixed with a few more things. I wouldn't be comfortable discussing the workings of what goes into it.
Thanks for all your help!
generally, i think if you want to do login, you should use a library that implements OIDC and an approach that gives you session tokens
any data that isn't login related... you can just provide via a secured endpoint
you can use OIDC and get bearer tokens
i think there are always a lot of misunderstands about what these different standards do. OAuth for example is really just designed to protect from harvesting your Facebook or Google password
people shove the token they get into databases, cookies, all sorts of stuff that exposes the token to adversaries, and Oauth never specified what to do with the token because it doesn't really care
it's a crappy and incomplete standard
OIDC says pretty clearly you put bearer tokens in LocalStorage
Your opinions on other standards?
session tokens can go into cookies
for native applications they have stuff
you can read it to do it correctly but i'd just use a library
deeplinking isn't used at all
the deeplink redirect uri thing that you see in ios apps... it predates the existence of these flows
and i'd emphasize that for the longest time, facebook didn't care what you did with the tokens. they just wanted to protect the user's password. oauth came from this
you would never deploy an app today that uses a custom scheme as a redirect uri
So if deeplinking predates, what would you recommend?
you can, it won't be meaningful, but it's not OIDC
And your opinions on other standards? OAuth2.0? Auth0?
i don't know what the objective is so it's really hard to say
if you are trying to authenticate someone via a social media login
this has been done a bajillion times
you would just use a library
It's more of "my" thing I guess.
Not usual stuff
Just something new I guess.
But anyways, yea. Thanks a lot!
The discussion was insightful.
i think you're trying to do some kind of shared unity world thing
or some kind of virtual gallery
i don't know
good luck out there 🙂
maybe just use Okta for user accounts
if you dont' want to use playfab or whatever
Learn how to authenticate users in Unity WebGL and authorize them to Azure Playfab
you can do this all with keycloak as your backend
I guess but more of a eco-system? But not just games. Idk hard to explain lol
but then you have to get a good client library and know what to look for
it's okay
i definitely want to be helpful 🙂
Yea, I'm thankful for that.
i think don't worry about the named pipes thing. but if you want proper login you'll need a backend server
and do sessions
then the "oauth dance" happens between your backend and e.g. facebook
Yea, I'm already using session tokens and then bearers
Anyone who is good in calculus know how get the rotation of an object given 4 points in world space?
Ex. Click 4 points in 3D Space and create a game object where all Y coordinates 0, would be as close to 0 as possible given those points? (Due to rotating the gameobject so that the base plane of X,Y, (z?) (2D Plane) is close to 0).
To make sure the calls are valid.
so ive a problem, i realised my button isnt working. any idea why? i thought it was the specific instance of button so i tried deleting and making a new button. but still the button doesnt work
Because you dont have an event system in the scene?
i mean, by default shouldnt the button just turn red from a hover and black when pressed, thats the colors ive chosen anyways
and i added an event listener in the Main object, but that isnt really the issue here
i just put a debuglog in it. but i think the issue is the buttons clicks isnt even being registered
That is what the event system is for...
oh
that thing i deleted
ohhh
is there a way to get it back
or just recreate it..
lol
hahaha
omg
just recreate it
lol you are welcome. The ES is a pain in the butt
tldr just leave it there i guess xP
Better to create a game object to store all the stuff you dont care about like a game manager object or something
I had a quick question about Unity components. I'm currently developing a boss fight that uses a class based state machine. Each attack state holds its own values related to their attacks. My problem is that I am currently only have one state script attached to the boss at a time which removes my ability for my designers to set the attack values in the inspector, I could of course add all the states to the boss which fixes the issue, but then the boss would always be carrying X amount of components that its not using.
I would love some suggestions or if i'm overcomplicating it and to just add all the state scripts. Many thanks!
Could you not create a list of classes (serializing them) and then create an ENUM that represents each state and then convert the Enum to a value in the list?
I'll give that a try thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class EnemyState : MonoBehaviour
{
[SerializeField]
public State currentState;
[SerializeField]
public List<TheState> states;
}
[Serializable]
public class TheState
{
public string stateLabel;
public float damage;
public float currentHealth;
}
[Serializable]
public enum State
{
Attacking = 0,
Defending = 1,
}```
That's similar to what i have, although my states inherit from a base state
ah gotcha. Well using enums might help. cast it this way (int)currentState
same for setting it. currentState = (State)1;
Could I - in theory - add all the classes as instances in my Boss's main class and then add and remove those instances as components?
or would that be the same as just adding them all as components
do you have an example of the classes you are trying to use? If you make them all of the same type (ex public class EnemyState : TheState (inheritance), you could add all of them in a list and they will have additional data, as well as the base data that you want. You could manipulate the rest of the data separately
Sure let me put together an example. One Sec
{
public enum State
{
Idle,
Charging,
}
BossState currentState;
void Updaate(){
currentState.Run();
}
void ChangeState(NewState){
currentstate.OnExit();
Destroy(currentState);
currentState = NewState;
AddComponent(currentState Type);
currentState.OnEnter();
}
}
public class BossState : MonoBehaviour
{
virtual void OnEnter();
virtual void Run();
virtual void OnExit();
}
public class IdleState : BossState
{
// BossState overrides
}
this is an extremely basic class set up that i'm using
no judgement here. All classes should be basic
better if classes can be made as structs though sometimes.
For sure, it's necessary for all these to be classes for the moment
Sorry i've tried to make that a little more clear
i'm deleting and adding a new state in the ChangeState function
For example, they need to be able to change values in the Charging state. How far the boss will charge, and the time taken to cover the distance
i could initialise those in the script and avoid this issue, but that's not really an option because my designers need access to these settings
Did you see my modified code above?
if you put a string in the first position of a class and serialize it, you can name it
Like so
That's cool i didn't know you could do that
Then they could easily change those values
i dont think I fully understand the rest of what you are trying to do. I would definitely make a public list in your script, if it doesnt show, serialize it, and have them modify values that way.
Would look something like this
I can't seem to get it working with a list of a class that should contain other classes that inherit from it
the list is made from the base class?
Yeah
Are the other classes serialized?
If you modify the list from code it looks like that sometimes
I think I'm gonna take a break and think on this for a bit. I really appreciate all the help
Sorry it didnt get you where you wanted to be. Good luck... youll figure it out
oh also... need to initialize each class... or it will look like that
Thank you, i've been working all day so my brain is just running out of steam 😅
I hear ya...
Works at runtime for me, but hides the additional variables.
using System.Collections.Generic;
using UnityEngine;
using System;
public class EnemyState : MonoBehaviour
{
[SerializeField]
public State currentState;
public float maxCharge;
public float currentCharge;
[SerializeField]
public List<TheState> states;
[SerializeField]
public TheState state0;
[SerializeField]
public EnemyState1 state1;
[SerializeField]
public EnemyState2 state2;
[SerializeField]
public EnemyState3 state3;
public void Start()
{
states.Add(state0);
states.Add(state1);
states.Add(state2);
states.Add(state3);
}
}
[Serializable]
public class TheState
{
public string stateLabel;
public float chargeRate;
}
[Serializable]
public enum State
{
Idle = 0,
Charging = 1,
}
[Serializable]
public class EnemyState1 : TheState
{
public float additionalFunctionality;
}
[Serializable]
public class EnemyState2 : TheState
{
public float additionalFunctionality1;
}
[Serializable]
public class EnemyState3 : TheState
{
public float additionalFunctionality2;
public float stuff;
}
try to avoid using lists that contain different types, even if the list items share the same base type. that said, to have a good editor experience with this, use Odin
additionally, using classes (instead of struct) for state on a monobehaviour can be very problematic
it is a minefield of errors
especially lists of classes
what did you mean by this
thoughts on Arrays of structs @undone coral that was my first thought
are you trying to say, how do you calculate the normal of the poly formed by 3 or more coplanar points? (a fourth point will not be guaranteed to be coplanar)
I am not advanced
imagine in VR, using my controller, when I press the trigger 4 times, I create a list. with those 4 poitns in 3D Space, I want to create a 2D Plane to draw on. but can only do so using those points
arrays just sort of blow because you can't force them to be copy on write or whatever. but you just have to deal
gt it
so my suggestion is the UX looks something like
also. I need the rotation of a plane due to the fact that other future information needs to derive from the "new" coordinate system
the user places 3 points with their pointer
create a UnityEngine.Plane with
those points, and canonically choose a
direction for the normal opposite camera
normal (ie facing player)
render the fourth point "locked" to that
plane using Plane's closest on-plane point
to the provided point function
@agile spoke is that helpful?
i see how in a stylistic sense you want to let the user choose a fourth point
so that it feels like a rectangle-like thing
that's fine
Not really stylistic as much as using it for averaging
Plane lets you achieve everything you need 🙂
i wouldn't try to do that for now
i would just use the 3 and cast the 4th onto the plane defined by the first 3
otherwise it will behave weirdly, trust me on this
there isn't a canonical way to "average" 4 points into a plane
so whatever you come up with will be, in that sense, weird
whereas there are exactly two ways to interpret 3 points as a plane (normal is clockwise points out, or normal is counterclockwise points out), and for your application you can always choose something that makes sense
i've been messing with runtime manipulation for a while, and have NEVER come across planes... very interesting.
or rather I've not seen this API pop up in my searches and exploring... im surprised it hasnt
lol thanks for this. I am assuming that its best that if I do create a GameObject, no need to rotate... I can use the plane functionality to do most of the rest?
this is meant to be UI right?
no...
like at first
like to visualize the four points the user is choosing
are you having them draw a poly
i know it will manifest as something you put into the world
yes in that regard
okay
you could, in principle, create a game object with a piece of geometry whose arted normal is pointing positive y (i.e. up)
then, to spawn it, set its transform.up to the Plane's normal
that will "rotate" it correctly
as long as you know what it's "art normal" is
meaning, whatever is "facing forward" for that piece of art
i don't mean to be so abstract
I understand most of the theory behind normals etc, but in practice my floor is covered in hair when trying to implement
So yes, I understand up from normal, but actually using that info, Im going to have to dive a bit deeper to get the gold of it
yeah so you will get the .normal from the Plane you created
that's the direction the poly your player made is facing
then you can set transform.forward or transform.up on a game object to that normal
and it will rotate
such that the transform's forward or up or whatever
is in the same direction as that normal
whether you use transform.forward or transform.up depends on which way the art, meaning the mesh, is really facing
a unity plane is facing forward on y positive, so you'd use transform.up
which is contrary to what is canonical, that "forward" (what you are facing) is z positive, not y positive
when you're rendering the UI @agile spoke you'll use whatever library/asset to draw the floaty lines
like the blue lines and fill in the poly
that is kind of weird considering their coordinates are mixed up (Y,Z) but the verbage actually makes sense coming from other applications
when a class is not a singleton, and no usages of it can be found in other classes, what's the likely way the MonoBehaviour was instantiated by the engine?
<@&502884371011731486> please block XXX
can you describe what you're observing and what problem you are trying to solve?
if you have a prefab in a Resources folder
lol sorry. i'm not making a game
and you instantiate the prefab
i'm looking at code from an existing game
there's a TitleManager : MonoBehaviour, which isn't referenced anywhere else
though it has to be instantiated somehow
i'm wondering what part of unity is doing this
it can be on a prefab that gets instantiated
there's no reason it would have to be referenced in code directly
a prefab is like an asset?
^^
for like hearthstone deck tracker style stuff?
all i want is TitleManager.m_currentOption
Prefabs are assets, yes
hm, would help if we had the C++ source
you have just stepped backward on this journey
nah the UnityPlayer module is surely a C++ library
but the TitleManager wouldnt be
well no, but i need to find the prefab somehow
and i have to assume it's in some collection in that module
there are things like g_RuntimeSceneManager, which is the internal SceneManager class
or s_InstanceBehaviourManager
I've built my own library for this
the latter doesn't even bring up a single google result
those are all custom
yeah
in case you didn't know about this
i believe there's a collection of prefabs, or assets, or something like that, just like there's a collection of scenes (literally an array of full scene paths). will be difficult to reverse this
i still need to figure out s_InstanceBehaviourManager as well, since that sounds really good too
As someone who is developing something to sell... the talk of reverse engineering software makes me uncomfortable to discuss. They should have obfuscated the software to make it more fun to decode. Im sure youll find more helpful information online
someone's always gonna do it, and i'm that one for this
But it won't be here, we don't allow decompiling discussions in this discord.
sorry, understood
@undone coral something like this?
yes, but you still have to process what that whole discussion about what "up" or "forward" means with respect to your art
something can help me with this problem
because LookAt won't behave correctly for the mesh created by the menu option in unity for creating a plane geometry
probably script name is not the same on the script as the class name inside of the script. Look for caps, spaces.
*edit to add. Looks like something extra is there inside of your script
im going to have to play with it for a while.
okay
but yes, the essentials are there
you just don't know yet i think that you can do
transform.up = plane.normal
i learn better by failure, so Im going to have to do the thing
and transform.LookAt is essentially transform.forward = plane.normal
it is technically
var up = transform.up;
transform.forward = lookAtArgument;
transform.up = up;
I tried to do something but I can't solve it
so 1... I should be editing the transform.?? values and not look at. 2... consider Unity's orientation
yes
you can use LookAt... provided your game object art's forward is (0,0,1)
does tha tmake sense what i am trying to say?
your art has a logical "forward"
like your human body has a logical forward
that means soemthing
and a logical up
a plane, which is a square... people ahve decided that it has a logical up
but it does NOT have a logical forward or right
if it's a square
it's just arbitrary
most instances the "plane.normal" will be facing close to up, but at an angle
you can't just look at a picture of a plane and tell me which way is +X and which way is +Z
anyway you are going through the expanding brain memes here
of what lal this stuff means
you have Plane you are already in a good spot 🙂
yes, yes. Thank you for that tid bit
that does most of the math that i was struggling with
and the rest btw.
on your script, this looks wrong. change the script to match the file name
or change the file name to match the script name (class name). They should be exact with no special characters
post the script here?
type 3 ` before and after
ex. my code
I guess I should ask the obvious too
are there any console errors?
kind of #💻┃code-beginner maybe start with a unity tutorial
so, spherecasts; can't live with 'em, can't live without 'em.
I have a really awesome bullet system set up with realistic (ish) penetration and ricochets. I love it. The issue I'm running into now though is that if I put shotgun rounds in an smg I quickly slow to a crawl after 10 shots (maybe 250 projectiles?)
obviously not being able to stick 9mm pest control rounds in my smg is a massive bummer. The profiler says my bottleneck is spherecasts, which I do 2 of per bullet (for entrance and exit logic)
does anybody know any strategies for reducing the performance hit on spherecasts? I figure I could at the very least do my bullet updates half as frequently, but they're already in fixedUpdate which updates relatively slow. tbh I would need like a 10x performance improvement to make shotgun smg viable
It works great, thank you.
Could you not use raycasting at all and let the items have spheres on them(if my memory serves, spheres have less performance hit than box colliders), attach events to those if they hit a target in the OnColliderEnter type deal?
🤔 honestly I've assumed this wouldn't work because of the high velocity. When I've tried to use physX before at realistic speeds (1000 fps or more) there's tons of issues with things just passing through walls
maybe I'm wrong about this
You could just create a wall with a box collider and see, maybe you are right though.
could you create a spline for the bullets path, and each line segment, run a ray trace?
could run the math logic in a separate thread and recieve the results in update loop. Ex (if(finishedCalculatingLinePath), (raytraceAlgorithm());
Spheres should be the cheaper primitive.
@strange hornet Are you triggering GC.Collect perhaps? Is SphereCast the only detail it gives you on profiler?
yeah basically. just 200+ spherecasts. I'm already using SphereCastNonAlloc
I'm realizing my FixedUpdate is running at like 50fps which is probably insane. going down to 5fps might actually be viable though it could potentially screw up hitreg
Not sure if changing the rate is the solution if the frame is too heavy, since you would essentially just change the frequency of the stuttering.
hm good point. maybe they could be staggered or something though
that's worked for me before with raycasts, has some weird consequences of course depending on how you choose to order them
maybe i'm interpretting this wrong tbh
What about an initial raycast? if it hits anything other than ground, enable the other checks?
the individual spherecasts dont seem to being using much...
what else is in the FixedUpdate Function? Any allocations, assignments? Instantiating prefabs? Do you use object pooling? So you can update its values instead
yeah there's object pooling. there's a bunch of math happening but I assumed that would be shown in the profiler. here it is not-raw, I guess technically spherecasts are only 11% so maybe that means my math is heavy?
I'm basically substepping inside of the loop to do friction... didn't think this was an issue but maybe
I guess I should probably do some more in-depth testing of how long each section takes
What actually does initialize mean
Everything I read says Start() is used for initializitionnnnn
You should probably read this https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
and then this https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
Not sure if raycasts can be run in other threads? but this is kind of how I saw it. Each bullet path broken down into segments, and running a raytrace on each segment. faster or slower? dunno.
but you could in theory, run it in a coroutine and that way it checks the 1,2,3 in the first segment of each bullet and each other one respectively. That way you might not have to thread but could check if each bullet hit anything on the very first frame, giving you enough time to run the others by the 2nd frame most likely
looks really sick, pretty much exactly what i imagined
Well, you cant see much from that view lol. Ill share video at some point.
@strange hornet Or something like this
using System;
public class Bullet : MonoBehaviour
{
[SerializeField]
public BulletSettings bullet;
private float step = 0;
public int stepsPerFrame;
private Ray ray;
void Start()
{
bullet.velocity = transform.forward * bullet.speed;
bullet.gravity = Physics.gravity;
ray = new Ray();
bullet.stepSize = 1.0f / stepsPerFrame;
}
private void Update()
{
bullet.pos1 = transform.position;
bullet.temp = transform.position;
for (step = 0; step < 1; step += bullet.stepSize)
{
bullet.time = Time.deltaTime;
bullet.Run();
ray = new Ray(bullet.temp, bullet.val);
if (Physics.Raycast(ray, (bullet.val).magnitude))
{
Debug.Log("I HIT SOMETHING!! -- NOW DO SOMETHING");
}
bullet.pos1 = bullet.pos2;
}
transform.position = bullet.pos1;
}
}
[Serializable]
public struct BulletSettings
{
public float speed, time, stepSize;
public Vector3 velocity, gravity, pos1, pos2, val, temp;
public void Run()
{
velocity += gravity * stepSize * time;
pos2 = pos1 + velocity * stepSize * time;
val = pos2 - pos1;
}
}
Edited to fix
this is more or less what I'm doing, with many more steps and calculations. except instead of doing stepsPerFrame sphereCasts I just do it once and apply the change in velocity 1-dimensionally in the substeps. cuts down on casts by like 95% lol
friction calculations don't play nice with continuous functions 🙄
this means that gravity isn't applied until the end of the frame and bounces require a recast
or any 3-dimensional change in velocity
I did want to ask... are you sure you can jobify raycasts?
I'm pretty sure you can't, there's a bottleneck due to needing to access the scene information
yes, but from the profile it looked like it was being "jobified"
would be really rad if you could bulk query the scene for an arbitrary amount of casts but I don't see that functionality anywhere 😵💫
OH yeah I noticed that when I posted it... not really sure why
I'm just doing them in fixedUpdate
it does seem like they're doing a lot of job waits though
Almost all devices using Unity are multi-cored with at least 4 cores. I feel like they should find a way for sure to make all data accessible on any thread.
not sure if this is what y'all are looking for, but: https://docs.unity3d.com/ScriptReference/RaycastCommand.html
maybe make a flag in the gameObject such that when any gameObject is being manipulated it is pushed ignored.
then add it to a list of go that were ignored
then check list again
looks pretty useful, not sure what hes using
for each bullet in FixedUpdate. one cast forward to get entrance points, one cast backwards for exit points
do you know if there are any negative implications of doing this? timings, etc?
I just know it exists. Never used it, don't know anything about it
have you tried removing "var" and seeing performance?
not saying its anything... but I never use var
looks extremely promising. thanks for the tip
I could be wrong but I would think vars are resolved on compile, not runtime
that being said no, I haven't tried that
you are probably right, its just a habit I have to eliminate any source of potential problems.
why is it a spherecast exactly?
because the bullets have a size?
Hello, I have a problem with my tilemap.
when I go this;
[SerializeField]
private Tilemap tileMap;
// Start is called before the first frame update
void Start()
{
Tile tile = (Tile)tileMap.GetTile(new Vector3Int(0, 0, 0));
Tile tileTest = (Tile)ScriptableObject.CreateInstance(typeof(Tile));
tileTest.sprite = tile.sprite;
tileTest.color = Color.red;
tileMap.SetTile(new Vector3Int(0, 0, 0), tileTest);
}
``` it's work , the cell at position 0,0,0 change color to red color
but with costum tile :
[Serializable]
[CreateAssetMenu(fileName = "New Tile", menuName = "Tiles/costum Tile")]
public class TileTest : TileBase
{
public Sprite sprite { get; set; }
public Color color { get; set; }
public Matrix4x4 transform { get; set; }
public GameObject gameObject { get; set; }
public TileFlags flags { get; set; }
public ColliderType colliderType { get; set; }
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
tileData.flags = flags;
tileData.transform = Matrix4x4.identity;
tileData.sprite = sprite;
tileData.color = color;
tileData.gameObject = gameObject;
tileData.colliderType = colliderType;
}
public override void RefreshTile(Vector3Int position, ITilemap tilemap)
{
tilemap.RefreshTile(position);
}
}
and
void Start()
{
Tile tile = (Tile)tileMap.GetTile(new Vector3Int(0, 0, 0));
TileTest tileTest2 = (TileTest)ScriptableObject.CreateInstance(typeof(TileTest));
tileTest2.sprite = tile.sprite;
tileTest2.color = Color.red;
tileMap.SetTile(new Vector3Int(0, 0, 0), tileTest2);
}
``` the sprite is changed but not the color
@strange hornet okay... here's a better question. is there a rigidbody or a collider on your bullet prefab?
instead of dumping the code can you succinctly say what your issue is
the problem is that with My class which inherits from TileBase, when I modify the sprite it works but the color does not change
@strange hornet also, do you have deep hierarchies?
can you try flattening the hierarchy on your static geometry / make sure static is checked on all static things, and make sure that whatever has colliders and/or rigidbodies on it is just located in the top level hierarchy of the scene?
properties are not serializable
also get tile data is weird
all this code is weird
what are you trying to do?
you have weird spacing
are you using an IDE?
you should probably get started with the pins in #💻┃code-beginner
it's the copy/past
this for example
i try to change the tilemap in runtime
this tells me you are not using an IDE
i mean, you clearly are using an IDE
but it's not set up
it's juste the copy/past of my code ^^
if you need to change the color of a sprite, reference the sprite and change its color
this scriptable object is strange
Yes it's pure test
i'm not sure what it does, or why you're using it
this is the only way to change a tilemap at runtime according to the docs
okay
i see now that you are doing a collider Contains query
try not doing that
i don't know, there's a lot of work to make this efficient
oh, penetratingCollider is a poorly named HashSet. not doing contains on a collider
yes, all bullets have a diameter
I think there is one collider but it's disabled. The main thing it is is a tracer mesh that I'm also updating each frame, but since that isn't visible in the profiler I don't think it's that
Is there a way to check if the player setting force single instance option is enabled at runtime? Or alternatively check if the current build is a "development build?"
#DEVELOPMENT_BUILD is defined in development builds
Perfect, thanks!
Just out of curiosity, does anyone know how Application.genuine works? Is it just checking the current assembly hash against an embedded "proper" hash?
Or is this only a iOS/Android feature? Because the docs don't mention anything about Windows, only Mobile
The sources is in C++, though it does read like it's mobile-only based on this https://forum.unity.com/threads/application-genuine-is-it-worth-to-use.902102/#post-6287441
Ah okay yeah, this definitely isn't what I'm after. Thank you again!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
void Start()
{
SaveSystem.LoadPlayer();
StartCoroutine(SaveGame());
}
//private void Update()
//{
// SaveSystem.SavePlayer();
//}
private IEnumerator SaveGame()
{
SaveSystem.SavePlayer();
Debug.Log("saved");
yield return new WaitForSeconds(3);
}
}```
why doesnt this work? it works when i use the update instead of coroutines. but shouldnt they both work?
the same function, saveplayer is called, so that should be working and im implementing coroutines wrongly im guessing?
how does it not work? do you get an error? my guess would be that you have some stuff in other components' start methods that your SavePlayer method relies on, which are all called before update (so save works from there)
idk the coroutine just isnt being called
other components start methods?
if i commented out the coroutine when i ran it in update
you aren't using the coroutine in update
I doubt that, unless you don't have this component attached to anything in the scene. Start should be called...but you can confirm I suppose
yea, coroutine is different from update right?
er the console log shows that coroutine is called once and then isnt called after
well sure, that's what you do
you call it once in start
i made save player output something to console so thats also called exactly once
yea, but shouldnt it be called every 3 seconds
you don't do anything after you wait 3 seconds, so no
see this is why you shouldn't crosspost because i just told you in #💻┃code-beginner that it doesn't loop
it will save the game, wait 3 seconds, and then terminate
wait so, how would i do it such that this is called every 3 seconds
well if i were you, i would just keep track of time and use the update loop
hm so something like having a variable for last update and if its 3 seconds since, i run the save and update the lastupdate variable?
yep
you could also just put everything within the coroutine into a loop
what exactly is coroutine for?
it's just another way to express the same thing really
you could do it either way
but if you aren't familiar with coroutines, stick to using the update loop until you get a handle on programming frame-to-frame
hm i see thanks
and then coroutines will make much more sense and can help simplify some things
also i wanna make a game where i can keep track of time offline
is there a way to get absolute time
you can get the system time
idk if thats the proper word
🌈 do not cross-post
System.DateTime.Now
mm thanks
alternatively Time.time returns a float representing the time (or rather time since application start) rather than a DateTime and would be easier to work with for a simple timer
isn't Time.time just since the game started? they said they want offline time
That is time since startup
yeah i didn't see that, that's my bad (thought they were still asking about the timer for delaying their SaveGame call)
Also there is the InvokeRepeating method
Since it's not called super often, it might be suitable
You can also use System.Diagnostics.Stopwatch in a coroutine loop
interesting results... every bullet loop I do 2 spherecasts (forwards and backwards)
apparently the 1st one takes roughly 16x as long as the second one. No idea why, but it's consistent
actually it ranges pretty wildly, between like 8x and 20x
makes no sense
in theory they should be a nearly identical operation since they have the same distance and aren't hitting anything
confirmed that most of the time is spherecasts though. although my maths are definitely heavier than I expected and also I have a LINQ call that really sucks (hitOrdering)
specifically most of the time is forward spherecasts 🤔
hey guys, how would i go about making a savable list in JSON?
can i just have a list of ints or strings and save it without doing anything to it?
yes
I recommend the json.net package https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347
@mighty cliff
cool
so there's a SphereCastCommand... but unfortunately it doesn't do multiple hits like SphereCastAll so I don't think it'll work 😭
Is there no time keeping mechanism in Bursted jobs?
I have a very expensive loop in a Bursted job that may take some time to complete, and I'd like the job to be aware of time and exit early if it has exceeded for example 10 ms.
I guess I could pull the loop out of the job and make the job only executes one operation, and let the main thread that execute the job to do the time keeping
But I'm under the impression that the overhead of starting a job might make this not viable.
probably better to ask in #archived-dots
just properly learning about GC for the first time ... is there some kind of primer on how much GC it's okay to cause? or do i actually need to aim for 0, i'm not sure how that's possible, like startcoroutine seems to be guaranteed to do its 64B or whatever
like i'd guess to just watch the actual CPU usage of the garbage collector blips in the profiler to see if there's a problem, and generally at least keep things in the random occurrences of a few hundred bytes instead of like kilobytes every frame
That's how I approach it. You can also try the relatively new Incremental Garbage Collector in Unity, which is supposed to reduce big spikes.
But optimizing something that used to allocate a bunch to allocating zero is very satisfying, regardless of whether it actually improves performance.
yeah lol it's very ... gamified
You may want to look into UniTask.
It's zero allocation and you get to use async/await instead of the ugly and unmaintainable coroutines.
FYI, you probably already have Newtonsoft JSON package from Unity if you have a modern version of Unity, since Unity's Version Control package depends on it.
oh okay
Any idea why this ``` public bool CheckWritePermissions()
{
if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite)) {
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
return false;
}
return true;
}
returns false, but the popup for permission check doesnt appear?
Can someone help me with this player code?
My character is not jumping
Here's the code:
https://gdl.space/dumofopuwu.cd
Try to keep track of your conditions
Does your jumpkey actually do something ? Does your ground check work properly
Abuse debugging and you'll find quick enough
maybe because the permission doesn't popup if the user denies it in settings
or denies it more than once
yeah, i figured it out. Thanks
the weird thing is, even tho the user allows the permissions, in code when i check it still is false, no matter if the user allowed it or not
dont return false after requesting for permission. return Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite) instead
ok
but i dont understand how that will fix
my problem
nope, still the same. Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite) always returns false
because requesting permission pauses the application depending on the device. i have came across few devices which donot pause, but most of them do.
anyway do you use custom manifest?
nope. It even happens when i restart the app
i tried uninstalling it, installing it again and enabling storage permissions through settings
still the same
I have a bit of a hard question since I dont really know how to explain it but I want to create a globe where the player can orbit a small globe that can change terrain the further you go, even if you did a full cycle around the globe. Eventually, the terrain will repeat if you go even further too. I drew a picture if that helps to visualize.
Like the shrinking world game brackey made but instead of it shrinking, the further on the road you go, new custom terrain shows up, even if you go all the way around
Sorta like an illusion
The "easiest" way to do this would be to have a flat generated terrain, and a camera effect like a shader that deforms the view to give the impression of a planet
Ohh yes! Thats a good idea, will it deform the player tho?
If applied on the camera, yes.
You could have two cameras though, one with the effect that renders everything but the player, and another that just renders the player, with no effects
Ok great! Do you know a tutorial on this affect?
Nope
Ok
I gotta try to find something online then
But first, Ill model the flat terrain
The Curved World asset does exactly this
Great thanks!
I have a "working" piece to get mic input actively as I need to read just whether the player is talking or not, going based on "amplitude" (as all the google'ing has lead me). And for some reason, there is a LOT of noise being picked up as well, even when mic gets unplugged (Have a slider to display before and after of mic filters, and the raw/before just keeps going up and down on its own when room is dead silent or mic unplugged - using headphones through monitor and as loud as possible, no sound can be heard from mic when it spikes very often randomly)
Samples mic every 1/10th of a second, with a sample data length of 1024*