#archived-code-advanced
1 messages · Page 44 of 1
can i suggest an alternative?
what is a light property?
what is its type? and why does it have an onChanged
you should be using unirx
// make this editable in the inspector
class LightReactiveProperty : ReactiveProperty<Light> {}
// hard to tell if you need this. lots of default types already declared, like StringReactiveProperty
...
// editable in the inspector
[SerializeField] private LightReactiveProperty m_Light = new();
void Awake() {
// react to changes to light
m_Light
// only when this component is enabled
.Where(_ => this.enabled)
.Subscribe(light => /*the body of OnLightPropertyChange */ )
// remove this subscription automatically when this
// game object is destroyed
.AddTo(this);
}
@glacial wedge do you see how much better this is
what is your goal?
fwiw there's two UnityEngine.dll's - one is in the parent, ../Data/Managed which includes everything you know and love, the folder ../Data/Managed/UnityEngine/ contains more granular dll's
What?
LightProperty i a custom class that i made to groups some fields like color and intenity and get notified by onChange when they change.
I didn't know ReactiveProperty
unirx is for network related things
[Serializable]
public class LightSceneProperty
{
public Action onChanged;
public CallbackValue<Texture2D> ditherTexture;
public CallbackValue<float> ditherScale;
public CallbackValue<Color> offLightColor;
public LightSceneProperty()
{
ditherTexture = new CallbackValue<Texture2D>
{
onChanged = _ => onChanged?.Invoke(),
};
ditherScale = new CallbackValue<float>
{
onChanged = _ => onChanged?.Invoke(),
Value = 0.1f
};
offLightColor = new CallbackValue<Color>
{
onChanged = _ => onChanged?.Invoke(),
Value = Color.black
};
}
}
this one implementation
[Serializable][HideLabel]
public class CallbackValue<T>
{
// così tanto zucchero da farti diventare diabetico
public static implicit operator T(CallbackValue<T> instance) => instance.Value;
public Action<T> onChanged;
public CallbackValue()
{
}
public CallbackValue(T cachedValue)
{
this.cachedValue = cachedValue;
}
public T Value
{
get => cachedValue;
set
{
if (cachedValue != null && cachedValue.Equals(value))
return;
cachedValue = value;
onChanged?.Invoke(cachedValue);
}
}
public void ForceSet(T value)
{
cachedValue = value;
onChanged?.Invoke(cachedValue);
}
public void SetNoCallback(T value)
{
cachedValue = value;
}
[SerializeField][LabelText("@$property.Parent.NiceName")] private T cachedValue = default;
}
this subscription with where clause has higher performance impact than my OnEnable OnDisable version, isn't it?
In 3d tile map games, the optimization procedure is to combine tiles and no render hidden faces? Can we go further? any more optimized way?
unirx you can use for anything, not just the network.
no
this is reinventing UniRx
UniRx has lower performance impact than OnEnable / OnDisable
lots of ways to achieve this with UniRx, all more succinct and performant than what you have now
I'm reading the readme... the last update was 3 years ago?
it is maintained
many people use it every day in many big games
like me
anyway you have now learned something amazing you will really like!
yes, it's very interesting thanks, do you use it with odin too? the inspector integrate it without problem?
what are you trying to do? you can definitely animate sprite properties
there are notes about how to make reactive properties of custom types visible in the editor
it is one line
odin will interact with it like any other serializable type
what are you trying to do?
Oh thanks for this!
It should change the sprite by all logic but it doesn’t
i feel dirty for not knowing about unirx sooner
v v cool, looking forward to digging into this
lol
i had to go into salesman mode
UniRx has lower performance impact than OnEnable / OnDisable
the intellectually honest answer is there is no meaningful impact of any of these approaches, but i'll let him figure that out
to be honest, i had already assumed it falls under the ‘so negligible it’s not even worth thinking about’ category
in my experiences, it’s almost never worth considering the performance implications of one library’s implementation vs another when it comes to some common functionality
and it’s always the same people who iterate over the same list every frame, worrying about whether or not they should change it to an array “for performance” 
Is unsafe c# comparable performance wise to c++? Solely just wondering
unsafe gives you access to techniques that are not available in safe code, those techniques can get you pretty close to optimal performance. The comparison to C++ is irrelevant as C++ is not fast by default or because it does anything special.
Thanks
you can just make your code faster when writting properly since you have a lot more freedom
Like relative to PYPY
You don't have a choice of which C# compiler/ runtime to use in Unity except for Mono vs IL2CPP
What would the best way of making an undo redo system for TMPs? I have mine mostly working but feels awkward to do it with onValueChanged cause whenever you undo or redo you gotta make sure those don’t get placed back on the stack and stuff
Is there a better way you’d recommend?
So, you can't control how or from where the TMPs are modified? Because that's what I think of first; make your own methods for setting the text where the undo is recorded and have the redo bypass that and modify directly.
I am unsure if I know what you mean. Is there another way to get when the value is changed?
My issue is when you set the text box equal to the text on the stack, that counts as a value changed, so what I do is I peek it and if that text on the top is not the same as the text in the box I add it to the stack
If that makes sense at all rn
But the whole thing feels awkward again
I'm assuming this is for runtime, in which case these modifications are probably being made by the user. The user is only able to modify the text because of some UI you made to allow them to do so. Am I correct in this assumption so far?
So why do you need to use the onValueChange event, when instead you can just add to the undo stack whenever you modify the text in your UI code?
Or are you using some built-in component to make the text editable?
Is there another method?
That functions the same as the text on changed
Like I am adding to the stack using the onValuChanged
TMP_InputField has a onValidateInput event, which I assume is invoked whenever the user inputs a character, but probably isn't invoked when the text property is assigned directly, which is what your redo function probably does.
I'm only assuming you're using TMP_InputField.
So you have tried using onValidateInput? Because you've only mentioned onValueChanged so far.
Ahh I read that as onValueChanged apologies eyes are blurry I’m tired lol
What is the difference between those?
I can't find documentation on it, but the event signature looks like this:
public delegate char OnValidateInput(string text, int charIndex, char addedChar);
So it's safe to assume it's invoked whenever the user inputs a new character.
And probably isn't invoked when the text property is set, because that would require multiple characters to change.
Though I don't know what would happen if the user modifies multiple characters, like selecting all and deleting. I don't even know if TMP_InputField allows for that kind of editing.
Mine may have multiple characters
If someone selects multiple and deletes it it should be able to undo that
This feels so odd
Lmao
a powerful website for storing and sharing text and code snippets. completely free and open source.
This is my janky code rn
It just feels so disgusting lmao
@keen cloud TMP_InputField has a SetTextWithoutNotify method to modify the text without invoking the value changed event.
apparently whats wrong is that animation cant changes sprites, only animator can
I've a seperate process from which I want to populate / update the pixels of a tex2d, I get that I'd use GetNativeTexturePtr for that however I'm not too sure how I'd actually write to that. My current working implementation uses a combination of GetRawTextureData, GetUnsafePtr and WriteProcessMemory from my seperate process, however this ofc requires me to call texture.Apply which doesnt exactly result in the greatest performance I can have (I would love a stable 60 fps). Is there any examples of using GetNativeTexturePtr with a seperate c# app? Google unfortunately only led me to a single forum entry with no responses 😅
GetNativeTexturePtr returns a pointer to the underlying graphics API texture object, so it could be a ID3D11Resource for DirectX 11, a VkImage for Vulkan, etc... You can't do anything useful with it unless you use the same graphics API in your separate process. It's not a raw pointer to writable memory, just a unique handle for the texture to be used in other functions in the graphics API.
You'll always have to call texture.Apply if you've made modifications on the CPU side and want to upload it to the GPU. The only way you can avoid that would be to modify the texture on the GPU, through shaders.
I would specify that you can use ComputeShader.
Thank you, that was enough extra keywords. In my case I can always assume it is dx11 / id3d11resource. If I get it correctly what I would do is create a shared resource and would then be able to write to that from my separate process with SharpDX? Since I'd then work directly with vram I couldn't need to use texture.Apply if I'm assuming correctly?
SharpDX does not allow you to read and write directly to VRAM from the CPU. I found this, but it still relies on disabling the GPU's access to the resource while writing, introducing a sync point.
https://learn.microsoft.com/en-us/windows/win32/direct3d11/how-to--use-dynamic-resources
What kind of modification do you need to do?
A full update. I need to essentially pipe a directshow source into it (continuously)
Mhhh, that kinda sucks but I guess it makes sense. Swapping between two textures shouldn't be an issue tho if that is something managable
And is using DirectShow a requirement for this?
yes
In a perfect world, the video would be decoded on the GPU and stay on the GPU the whole time. I don't know enough about DirectShow to know if that's an option.
I'm far from an expert in any of this but I don't think that is possible. I will however look into it but need to leave for now tho, thank you for the chat, much appreciated 🙏
Is it possible to make a collider inside other collider to invoke OnTriggerExit when it's radius became zero?
I feel like you should elaborate what you wanna do. Maybe we can help you find a solution that would be better.
I have tons of triggers collider that changes their radius for my logic, but some of this are very big and contains other colliders. I would like to have the behaviour that with a radius of zero the collider will exit, but it doesn't.
I found that changing the layer works, but i'm having an unexpected behaviour, working to make the layer change method smoothly
A sphere collider with radius 0 is already probably an unsupported edge case itself
just have your code handle what happens when it shrinks to nothing, the physics engine is not going to work nicely with you here
Use an event
OnDisappear
I know, but I tried with enable disable the collider itself but this doesn't trigger the exit correctly
right
that won't work either
like I said
your code needs to handle this itself
The physics engine isn't going to save you here
you'll need to do something like:
when the collider enters your trigger, subscribe to an event for when it shrinks to nothing.
Then do what you need to do both in that event listener and in OnTriggerExit
(also unsubscribe in OnTriggerExit)
Actually I'm not sure if DirectShow is exactly a requirement? The source is a Capturecard, so I'm not sure if there would be any smarter way to handle this
In an ideal world I would just use a WebCamTexture but that doesnt support directshow sources 😅
what is your actual application
SharpDX
sharpdx isn't very compatible with unity's graphics devices, the reasons are complex
I need to / want to display the image of a capturecard ingame, and need to have it available in a way where I can apply shaders to it etc
thats the input of the IRL camera
okay but
what's going on with this camera? like why aren't you using a webcam
what is the idea
Quality
okay, what quality do you need
Most non-vga type webcams arent real "webcams" but can only be accessed via directshow (Or well, maybe some other way, but certainly not via WebCamTexture)
This isnt something for me specifically but will be released publicly so I'm not the one to dictate the target setup / hardware
hmm
But it's still specifically for non-vga type webcams, or would you also want to to support regular webcams?
All cameras can be accessed via DirectShow on Windows, so lower quality ones would work fine in that scenario too
most people go for 720p60+
Well that is what I would want to support at least
the way you are expressing quality right now is telling me a lot
unless I'm misunderstanding the question
it sounds like you have a piece of hardware that you want to use
that you like
and it is subjectively nicer than other hardware you personally have experience with
Implementing this, but doing the compositing inside Beat Saber in a mod and support higher quality cameras than traditional webcam APIs like WebCamTexture allows for. That's my understanding.
correct
for example, maybe you have a dslr that you use for web conferencing, and you like it, and it obviously looks nicer than your laptop webcam
is that correct? is that the idea?
I dont have any of this hardware myself, I'm testing with a virtual one, but yes usually people use a good quality camera and feed that into the composition in one way or another - And supporting that is what I'm aiming for
virtual one
?
OBS can output its viewport as a virtual webcam with its own driver etc, its accessed the same way as a real camera would be
OBS
🥺
okay how about this: where did you get the idea that you need to interact with DirectShow?
like what did you read / what is anchored in your mind about this?
I don't know much about WebCamTexture or webcam APIs in Windows. Is there a maximum resolution/framerate that you can't get around without using DirectShow? Or is it just that the capture card doesn't implement a traditional webcam driver?
well it doesn't sound like @sleek idol has a capture card
or a camera
i am still confused, it sounds like you're making a beat saber mod?
is that the idea?
I was trying to use a WebCamTexture at first until this OBS camera was not accessible through it (not in the enumeration), and from some googling the result was that it doesnt support directshow sources
If there is an alternative to DirectShow, that I dont know
okay.
And I then proceeded to ask someone who does have the targethardware to test on their machine, and its the same picture for them, not accessible through it
for the purposes of streaming beatsaber playthroughs live? am i misunderstanding something or doesn't this already exist?
It does exist, its called LIV, and its a stutterfest - Theres no alternatives to it, and thats why I'm here
okay but
you know, it doesn't sound like you have any clear idea for why it is a "stutterfest"
@sleek idol Did you come across this? It seems they have recently fixed an issue related to OBS virtual camera.
https://issuetracker.unity3d.com/issues/could-not-find-specified-video-device-error-when-using-webcamtexture-with-obs-virtual-camera
Found here: https://forum.unity.com/threads/using-obs-studio-as-webcam.898130/
it sounds like there's speculation on forums on OBS or Beat Saber whatever, but the people who write on those forums aren't programmers
it sounds like your question is, "how could i write a better LIV?"
Question, Allocator.TempJob from NativeArray<T>, the documentation says it last 4 frames... so...
Is it 4 frames including the frame which called the constructor of the array or 4 frames after that frame?
And, does the allocation becomes invalid at the start of the last frame, or at the end (start of the 5th)?
Even on high end hardware, regardless of the target game, its not a smooth experience at all. I've heard this from essentially everyone that tried it
But we are kinda drifting off into offtopic here
okay, i understand that's like a positivist fact
i'm saying, doy ou know WHY it is not a smooth experience?
How would I know that
I am talking about your own, in-vr experience
And I'm very certain that should not be the norm
I dont think I have, I'll check it out thanks
I've never seen documentation for this. Are you unable to test it yourself? But also I'm a little worried that you're looking for the exact limit. The 4 frames limit isn't a suggestion that you should try to make use of all 4 frames. It's just a healthy safety margin; TempJob allocated arrays shouldn't live for much longer than 1 frame.
okay. so to summarize
- you are trying to write a better LIV, a way to mod pre-existing games to composite a live action camera feed over an injected in-game camera with alignment.
- you don't know why LIV performs poorly
Sure, but how does that help me
it stands to reason if you want to make a better LIV, you should try to understand why it performs poorly
this directshow stuff... and then not being able to firmly answer the question about live action video quality
you're on the start of this journey
Why not let them try to recreate it and see if it performs the same, better or worse and work from there? What LIV does isn't rocket science, it's a totally reasonable project.
They were reported these performance issues various times over the past year or so, they are certainly aware
i am not talking about the positivist fact that it performs poorly
🥺 🥺 🥺
you have to learn something about how video and graphics works on this journey
I was responding to MentallyStable.
you don't have a capture card
you're wheedling with this OBS thing which makes no sense
you might have a webcam
you know, just try to make some progress on compositing something
directshow isn't going to help you
I do things that are interesting to me at the moment and use it as a learning experience, I know people that have the hardware and are more than willing to test when the times there, what I dont know is why you're trying so hard to have me not look into this
My question wasnt advise on what projects I work on
i just can't see how you can possibly get anything working without the hardware you want to write it for
because the interface is exactly the same as real hardware
well clearly it isn't
you are trying to convince me that the obs virtual camera is "the same", and like, it so obviously isn't, it's yelling at you practically that it isn't
i understand in a psychological sense you wish it were the same
but it isn't
I was trying to avoid having to test it, but ok. I will check.
I must to know about the limit because I'm using the collection for multiple jobs with main thread stuff in the middle, like:
NativeArray<int> n = new(100, Allocator.TempJob);
JobHandle j = new Job1(n).Schedule();
while (!j.IsComplete) yield return null;
j.Complete();
var k = SomeWorkInMainThread(n);
j = new Job(n, k).Schedule();
while (!j.IsComplete) yield return null;
j.Complete();
// etc
So I must to ensure allocations won't expire.
BTW, Is there a better way to make "sandwiches" of Job & Unity thread stuff? It's a pitty there is no IUnityJob interface so I can schedule jobs in the main thread in order to chain their dependencies easely and being able to force with .Complete() if I'm done waiting... 😕
anyway. you should probably only deal with capture cards that use UVC (i.e. webcam style) as the way you grab the video
https://github.com/keijiro/Klinker here's an example package that using the blackmagic decklink
which in my opinion is way out of scope
Yeah I was gonna say, that is not viable
the roland uvc-01 is an hdmi capture card over usb that supports uvc (it's right in the name)
which is to say that you don't know enough about video quality yet to understand what all this hardware is for
like what hte parameters are
i don't think you should be worrying about directshow
you should really find out what LIV actually does / how it works
you can also use an ordinary webcam. there are "720p60" webcams
Again, dictating the target hardware is not an acceptable path for me.
how can i be helpful?
it doesn't sound like you know a lot about video capture devices
which is okay
but you haven't asked about them either
i'm not trying to bully you
just think about what is helpful to know
it sounds like what you wanted was, how to get OBS virtual camera to appear inside unity, which advances your goals 0, but you believe that it does
so i guess you have that knowledge now
I can schedule jobs in the main thread in order to chain their dependencies easely
that is exactly how the jobs API works
force with .Complete() if I'm done waiting...
hmmm
what are you actually trying to do?
something something procedural mesh generation?
No
the most optimal use of jobs is when you have all the information you need to run a job before rendering, and its output is used only for rendering, at some later stage of rendering
If you have reason to believe it might take longer than 4 frames or come very close to it, you should use Allocator.Persistent.
I agree with your second point. There is a hacky workaround you can do, which is to schedule a job which just adds a callback to a static queue, which a script that updates on the main thread regularly checks and clears.
There's also this, which seems to work similarly, but without scheduling an additional job: https://github.com/domenkoneski/unity-jobs-callback
var data = ...;
JobHandle job = new BackgroundJob(data).Schedule(); // Executed in background thread
job = new UnityMainThreadJob(data).Schedule(job); // Executed in the main thread
job = new BackgroundJob(data).Schedule(job); // Executed in background thread
it becomes a more cantankerous api for mulitthreading if your output is not for rendering
what is the actual code for? what is it computing?
I already made some tools similar, but it's a pity there is no official.
Otherwise, job.Complete() can produce a deadlock if you mix background -> main -> background
🥺
In our game, enemies can attack other enemies, and their check to see if there are valid enemies in range is expensive.
So I modified it to use Job System which makes a sandwich of job and main thread stuff.
based on this, it sounds like you are using jobs for a complex task... but what is it? you probably already know to use allocator.persistent
okay
yes, I could perfectly use allocator persistent, just wanted to understand better TempJob
so the only way job system can make this faster for you compared to traditional multithreading is via burst compilation, but the code for this task might not make a big difference when burst compiled
in unitask, you can simply
UniTask.Void(async () => {
await UniTask.SwitchToMainThread();
var gatherPositions = FindObjectsOfType<Enemy>().Select(e => e.transform.position).ToArray();
await UniTask.SwitchToThreadPool();
// this could be parallelized using linq or any number of ways
var answer = gatherPositions.Aggregate(0, p => { ... });
await UniTask.SwitchToMainThread();
this.lastGoodAnswer = answer;
});
which is what you want. i mean that's sandwiching
literally
do you have a few lines from your job
I was using Job System because I did some batch raycast. but I guess I could use normal multithreading for other parts
RaycastCommand
okay. do you need the latest raycast results every frame?
it doesn't sound like this is essential for rendering
but it might be bad if the answer is out of date
by the time it is used
I don't understand your question
hmm
I guess that raycasts may be one or two frames outdated due to the asynchronous nature of job system, not very problematic for me
okay well it sounds like there's a lot going on
- you have a game where units use raycasts for targeting
- but also, the logic for this can be out of date
which is fine. jobs does give you a way to more efficiently query the physics state of your game on multicore machines than you can any other way. it sounds like you should just poll the raycastcommand's jobIsCompleted
and simply do not use Complete alone*
i.e. if (raycastCommandJobHandle.IsCompleted) raycastCommandJobHandle.Complete();
does this make sense?
the moment you poll it should be the latest possible time you can use the data it computed
for your gameplay purposes
I'm already doing that.
I just wanted to know
- How much exact frames does
Allocator.TempJoblasts? - Is there any official way to mix Jobs & Main thread?
unity simply cannot run C# code from a callback on anything but the main and render threads. that is a limitation of their architecture. so you must poll
4 frames
every time a frame is rendered and presented to the screen, it ticks down
Is there any official way to mix Jobs & Main thread?
yes,if (raycastCommandJobHandle.IsCompleted) raycastCommandJobHandle.Complete();if you do not need the results synchronously
if you need the results synchronously call .Complete()
The question was if the frame that created the allocation counted as the first frame or was the 0th frame.
But I just tested creating an allocation at framecount 0, and the error was after 5th frame but before 6th. Which is what I wanted to exactly know.
Ok
it's not after the fifth frame per se
it's that you are doing this in an Update or whatever
count the number of presentations (i.e. frames rendered)
So, if I allocate at Time.framecount, it becomes invalid at Time.framecount + 4?
if you allocate at framecount N, N will be presented and tick 4 to 3. then N+1 will be presented, 3 to 2. then N+2 will be presented, 2 to 1, then N+3 will be presented, 1 to 0. If you do not deallocate or finish the job by presentation N+4, it will see that the ticks are 0 and give you a warning
so you have to call complete on or earlier than Time.frameCount + 4
does that make sense?
So if (job.IsComplete || jobCreatedAtFrame + 4 <= Time.framecount) job.Complete()
if you want to use temp allocated yes
Great, thanks!
is probably what you meant
No, because that would stop immediately. It should be if the current frame is greater than jobCreatedAtFrame + 4
Great
Why not use persistent and clear the memory when used if it's a reoccurring computation? 🤔 Feels like you tie it down to a safety feature instead of setting your own limitation of e.g. how long realtime it should take?
this will always be one frame delayed if you only take this approach alone
Because anyways I don't want jobs to take too many frames. So the maximum duration of the allocation (4) is already enought for me.
if you want to still be able to use the raycast results "the same frame" in general, you have to kick off your raycast command job very early in the player loop (e.g. UniTask.PlayerLoopTimings.FirstUpdate) and check it again at the last time you could possibly use this data
using unitask, you can still write this more effectively
instead of trying to spread out the state machine
Because in the 1st frame I create the job.
In the 2nd frame I call .IsComplete, which batches the job (so it guarantees false).
And then in the 3rd frame, the call .IsComplete may (or may not) return true depending if the job is finished or not.
Right?
for example
class EnemyAi : MonoBehaviour {
AiState latestAiResult;
void Start() {
// AI loop
UniTask.Void(async () => {
// while this is active and enabled too, etc. etc.
var raycastHandle = default(JobHandle);
while (Application.isRunning) {
await UniTask.Yield(PlayerLoopTiming.FirstUpdate);
// finished previous frame
if (raycastHandle.isComplete) {
raycastHandle.Complete();
latestAiResult = ComputeAiResults(results);
raycastHandle = default(JobHandle);
}
// need to schedule job?
if (raycastHandle == default(JobHandle)) {
...
commands[0] = new RaycastCommand(origin, direction);
raycastHandle = RaycastCommand.ScheduleBatch(commands, results, 1, default(JobHandle));
}
await UniTask.Yield(PlayerLoopTiming.LastUpdate);
// finished same frame
if (raycastHandle.isComplete) {
raycastHandle.Complete();
latestAiResult = ComputeAiResults(results);
}
}
});
}
void Update() {
DoSomethingWithAiResult();
}
}
@mellow plinth does this make sense?
I see, you take advantage of Update and LateUpdate loops
this isn't late update
it's just hte last update
by late update i assume it's too late
if this was effected by rendering then i would wait until lateupdate
last update? Not sure what is that, is a UniTask concept?
but it's not
yes. imagine "the last Update call"
it has a lot of specific timings
So FirstUpdate is at ExecutionOrder(int.MinValue) and LastUpdate is at ExecutionOrder(int.MaxValue)?
sort of
I see
Interesting
you can see these player loops in the profiler
executionorder is radioactive 🙂
the pattern i authored illustrates how you can wait for long running jobs
Ok, thanks
you can achieve this with execution order, but you can see how it can be more complicated. for one, you'd need two scripts
it's painful
every script that would possible be able to use the ai results
would need the later sexecution order
it's too cantankerous
use async.
Ok
Question, must I put [ReadOnly] in all readonly fields in Job structs or is just for NativeArray and other Native collections?
i think they mean different things
hi guys on quick question how i can make an rpc affect only me ? example , how the others will be notified that i closed or opened my flash light ?
#archived-networking is a more appropriate channel
Yes sry it's late here brain is almost like frappe
hey everyone, I am sending a post unity web request and my ios build is crashing
it's supposed to be solved but it is not apparently... unless i need to modify somethingin the project settings and such.. can someone help
That sounds weird and I am terrified to click and learn about it.
yeah 🤦♂️
I'm going to click, but I doubt I can help.
thank you
have you found any way to solve this
using plugins or anything
No, I'm actually a bit distracted at the moment. I'll take a serious look now.
oh sorry
All good. Are you one of the posters in that thread?
no I just faced the problem and started looking for threads and solutions
I used to work for Apple, but don't go telling anybody.
@pale silo If you use Post to send data, does the data get truncated on receipt?
Also, can you share your headers if any?
the whole app stops it crashes and i have to close it
using UnityEngine;
using UnityEngine.Networking;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Threading.Tasks;
that's all of them
Oh, then that probably has nothing to do with the transmission itself.
Nono I mean headers in the HTTP Post request itself, but based on your last answer that might not matter.
yeah it doesnt matter.. i have tested the requests on webgl and android and they worked without any problem
My impression is this does sound like a bug on Unity's part.
So... are you publishing your game to iOS and then the final build crashes on an iOS device?
Also, does the software become unresponsive but tame or does it absorb ridiculous system resources first?
@pale silo @pale silo @pale silo
i tried in the beginning to copy the project files to a mac ... that's when I encountered the crash for the first time... even the inspector in mac crashed
and I only copied the assets folder... so it was strange
That sounds like a mess.
mhm... now i am onwindows ... also made an ios app and tried to run it on xcode on mac
and same thing.. crash
But do you have any knowledge of if the app hits 100% CPU or just doesn't respond to system messages?
no idea it just closes... same thing happens when i run the game on windows when i switch to ios platform
Oh, then I hope there is some log to explain what is happening first. This does seem like a ticket for Unity support, as loathe as I am to say it...
i wrote one but i am trying to do something for number 2
oh nvm now i got it
Did you try another version of Unity just to be sure, its not your system?
i dont want to try some other version because it could mess up my project (i am using the latest lts version)
You know about version control and using git, right? Just back it up and open it in another version then
ok sure (and yes I am using git so true nothing to lose)
ill try it and let you know
I have just sent the ticket.. we'll see what happens... I wil now try the other version
I would like to do the following:
I have a video stream from some application that communicates with unity
I want to send that stream, to another application (ML application in python) where it does object detection and then I want to get the frames from that application back into my unity app
any ideas how to do it?
basically want I want is during my update
var frame = get_frame_from_ip(); //this part is done
send_frame_to_python(frame);
var new_frame = get_frame_from_python_after_processing();
You should be able to just stream any video you want and on serverside do the work of updating the "content" of the video
So have like a back forth stream and let the server decide what to do with it.
I don't understand what do you mean?
would you mind to elaborate?
So, you have three connection points, right? "Some application", a Unity application and your ML Python Application. Is that right?
yes
and it has to go through that order, I can not let the server connect to the python program directly (not my choice, that is just how project managers want to control it).
Okay, yeah I do not question your setup, not my job to judge 🙂 So, you got a video stream, how do you fetch it in Unity?
give me a couple of minutes ^^
I am just here when I am, so no hurry, I will look back between work chunks 🙂
Hi guys, so I have a pre-allocated array of structs. At runtime the structs are being generated and I need to check if the struct is already in the array and return its index or append it at the end if it’s not a duplicate. Obviously I can track the last free index with a variable for the append part, but what would be a smart way of checking for duplicates?
cant you just use Find in this case?
Probably going through the whole array and checking for each item whether it exists or not, but how scalable this is would likely depend on your setup. How big is the array? Can you cache any of this?
I think the implementation might depend on whether we're dealing with 20 items or 20,000.
If you have to check for duplicates, you have to check every item. So you might think about not even generating duplicates if possible. But we need more information about your setup then
You could also simplify your search by holding a second simpler array with just ids of the items and check that, not sure if that is really faster, but could imagine depending on your count
Well not generating duplicates is not a option. Im generating rendering data that needs to be stored and used later for the draw commands per gameObject. Im not expecting the actual array to be very big since, in fact it should be quite small like no more than 64. How ever I could very well have to process like 500 objects this frame and get indices to the array for each
Okay, good to know, so we forget about no duplicates. Did you actually check how .Find() performs ?
I have not. I also should have mentioned that its a native array since I need to pass it to a job. Not sure if that even has a .Find
What type of array is it?
Not sure how this is code advanced related tbh 😄
sounds more like #💻┃unity-talk to me
NativeArray<MyStruct>
Oh I just read "its not a native array" 😄 My bad, let me check with you
Yeah well, no, you could only use the ToArray method first to then be able to filter it out. So you could try the suggestion of holding a second simple array that just keeps your ids updated and you can check against those. depending on your struct of course
Hmmm I could make a GetHash for the struct and store that in a NativeHashMap as the key and the index to the actual array yes
That could be a useful way to approximate whether the struct is already in the collection, yes! 😄
Not that firm with native structs but would you be able to also set the key to a "null" object and therefore use that hashmap to get the open "slots" too?
I think you cant have nullables in native space, right?
I think it needs to be NativeHashMap<Nullable<T>,U> iirc.
approximate ?
Assuming you never produce the same hash from two separate structs, it's a good approach for determining if a struct value is already included in a large collection.
I doubt that I will get a hash collision, like I mentioned the amount of structs is not that high, the amount of checks against the structs can be a bit high
thank for the pointers guys 😄
@violet valve the error might be solved in the 2022.2.6 version... the inspector didn't crash and now i am going to test it on an iphone
Good! I'm not surprised to hear that this could be a runtime environment issue on iOS.
trying to make some sort of dialogue system. any reason on why the subdialogue isn't showing up in the editor?
SerializeField -> Serializable?
wdym? I added the serializefield cause it wasn't working anyway and I thought it might help
I mean you try renaming it to Serializable and try again
serializable doesn't exist, and system.serializable can't be placed inside of a class
it's ugly but it works
better solution
How can I get the sprite from a tileBase?
So apparently Unity Canvas elements don't have their actual position set until after Awake() and Start() ...despite the fact that they pre-exist in the scene. What can I use to determine at what point Canvas elements actually have their real transform.position set? I have code that needs to initialize at the Start() that relies on their positions.
I suppose it's worth noting that the Canvas is a Screen Space Overlay.
@sly groveThank you.
You can force a layout rebuild if you need up to date values
Nah. It's not that. I need to Instantiate some other canvas elements at the Start() and make them children of the set them to the position of the pre-existing elements. However, since the pre-existing elements are not in their correct positions (yet), the Instantiated children are not where they're supposed to be.
Can you show your code so we can understand, what you are trying to do?
Yep.
public async Task Init()
{
Tiles = new Tile[Rows.Max(row => row.Tiles.Length), Rows.Length];
width = Tiles.GetLength(0);
height = Tiles.GetLength(1);
var sequence = DOTween.Sequence();
// Initialize Grid
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
SOGem gemSO = null;
//MAKE SURE WE DON'T START WITH MATCHES
if (x > 1 && x % 2 == 0) //WE DON'T NEED TO CHECK THE FIRST OR SECOND COLUMN IN THE ROW
gemSO = StartWithMatchesCheck(Rows[y].Tiles[x - 1].GetGem().GetGem());
else
gemSO = GemDatabase.Gems[Random.Range(0, GemDatabase.Gems.Length)];
Tile tile = Rows[y].Tiles[x];
Gem gem = Instantiate(gemPrefab, spawnRow.GetChild(x).position, Quaternion.identity, spawnRow.GetChild(x).transform);
sequence.Join(gem.transform.DOMove(tile.transform.position, dropTweenDuration));
//Debug.Log($"Tile {tile.name} at row {y} index {x} is at position {tile.transform.position}", tile.gameObject);
tile.SetGem(gem);
tile.Init(this, x, y, gemSO);
Tiles[x, y] = Rows[y].Tiles[x];
}
}
await sequence.Play().AsyncWaitForCompletion();
isInitialized = true;
}
you can add cs after the three ` so it looks better
The issue is with the sequence. It's moving the Gem to the wrong place, because the tile's transform.position was incorrect during Start() (which is ultimately where this Init() is called.
How about not passing a finite position abut the transform?
So you always get up to date values of the target
Is there a reason you're using Tilemap instead of Grid for this?
Erm
I mean
UI Instead of Grid
DOTween.Sequence() isn't a method of mine. It's a part of the DOTween package on the Asset Store. I can't modify what values it accepts.
Because they're canvas elements in a Screen Space Overlay canvas. They're not world space GameObjects.
Then why are you dealing with Transform.position which is a world space thing.
Oh wait, you are trying to move your world space object to the canvas space position?
Canvas elements also have transform.positions. It just pulls their RectTransform position.
No. Everything is a part of the canvas. It's all UI stuff.
So why do you not use anchoredPosition?
And why not just put your tiles into a GridLayoutGroup
They are in a layout group. But that's not addressing my issue. As I said, the issue stems from the fact that Canvas elements are not at their actual position, before Start.
anchoredPosition is also not set properly before Start.
of what element, the spawned one or the target?
The Tile elements (which are the ones that the Gems rely on when being Instantiated), pre-exist as children of a Row element (which has a Horizontal Layout Group). The Row is a child of the Board GameObject (which has a Vertical Layout Group).
And they change when you instantiate a gem?
Yes and no. They don't change because the Gem was Instantiated. They change after Start. I've Debugged in Awake, Start, and that Init method that I posted. In Awake and Start...this is the data...
RectTransform position is (192.60, 138.90, 0.00) and position is (192.60, 138.90, 0.00) and anchored position is (0.00, 0.00)
After Start, in Update, is when the elements get their actual positions...
RectTransform position is (770.40, 208.35, 0.00) and position is (770.40, 208.35, 0.00) and anchored position is (577.80, -69.45)
I'm positive this is because it's a Screen Space Overlay Canvas, which means their actual positions aren't calculated until the screen's resolution has been calculated.
I cant barely understand your setup now. You got a grid (mixture of layout groups). I got that, and then you instantiate a gem which refers to an existing UI element. yes?
Yes.
My confusion is why you don't just anchor your new objects the same way the other objects are anchored so that they end up moving to the same position
And your target existing UI element does change when instantiating? Or do you just throw all gem instantiating into a Start function when you run the game?
Look at the code above.
I see it
Let me ask another stupid question here: why have you built the primary gameplay elements of your game as UI?
This is bejeweled or similar right?
Order of events...
Game starts..
GameManager.cs...in Start()...calls stateMachine.SetState(gameSetupState)
GameSetupState.cs in OnEnter() calls Board.Init()
Board.Init() is the code I posted above...and where the Gems are Instantiated. It's not the Init method causing the Tile's (the existing UI element) to change it's position. The position changes because the Screen Space Overlay Canvas recalculates the Tile's position as it calculates the screen resolution (which happens somewhere between Start() and the first frame of Update().
Similar, but not the same.
Basically I have a method
that get me the
RGBA data from the camera frame.
Okay, and now you want to pass that to a another system, right?
something about Horizontal & Vertical layout groups always seem to end up causing issues like this - they are finnicky to make sure they update properly as they trickle down - setting a position after adding it to a layout group wont necessarily do anything until the layout recalculates next frame
It's not quite clear if that's what is happening here, but it sounds like it
to be exact, this is called on lateUpdate
Well the Gem that is having it's position set is having it set to the Tile's position, which already exists in the scene as a part of a Layout Group before the game's even started.
if it helps,
the python program, can be an instance that was run by unity, I have complete control over it
In Awake and Start the Tile's position is (0.0, 0.0) ...but AFTER Start, it's set to it's correct position (NOT by anything I do in code).
and the Tile's are part of the layout groups?
you're relying on the auto formatting of the layout group code to position itself?
Camera feed to python
Yes. I guess that ties back into the whole thing about calculating all that during Start when it's grabbing the screen resolution.
screen resolution might be a red herring here
this is just how layout groups work, as far as my understanding anyway, they are designed to control the size & position of the children rather than have dynamic children update the layout
you can work around it by adding content size fitter components, or forcing updates on layout groups
I'll repeat this...
I'm not going to get into that. It's the way this game's design needs to be, based on what it is. It's also an unhelpful deviation from solving the problem I'm facing.
Your problem would be solved easier by switching out of UI and into world space.
Right now you're actively fighting against the layout system of the UI because you want to set object positions this way. Simply using a Grid in world space would eliminate that whole struggle
It's a relevant deviation. Right now I see this as an XY problem
That's an assumption you're making, based on not knowing anything else about the game... As I said. THIS game requires that it's match system be a part of the UI.
So, you say its needed, thats a fact we should accept. Then I do not see your problem being the UI not updating correctly, but I see your usage of DOTween as a problem, if the tweening only takes finite values.
Yeah. That's another place I can look for/find a solution. Wasn't hoping to go that route, but I agree, it could solve this.
Its the issue. Unity has its order of execution, and if you base on start and awake , you run into those problems. I stilld o not get, why your UI is "changing", because I think you just shoot everything out on Start with some calling on other objects. What about going away from Start and control the execution yourself with init functions
I'm completely confused about what you're saying here. Start and Awake don't cause problems just because. I mentioned several times, that the UI is changing because it's based on screen resolution (Screen Space Overlay) which it isn't explicitly stated in any document, but seems to be calculated at the end of Start. So the UI is not changing based on anything I'm doing. Lastly you mentioned getting away from Start...and control it with Init methods. That's exactly the method I posted when you asked for the code. However, where do you suggest calling that method from...if not Start?
I am confused, because screen resolution should not change after initialised once. You do not wait for the UI to get calculated and throw all your stuff in at the same time. Thats why I was asking, do you hit the playmode and everything executes at once
Just for testing, throw a simple timeout in, like 2 seconds after Start (start can be an IENumerator too) and then init your gem stuff
Press Play...
GameManager.cs...in Start()...calls stateMachine.SetState(gameSetupState)
GameSetupState.cs in OnEnter() calls Board.Init()
I can't be anymore clear than this. Nothing's happening "all at once". If the UI is calculating itself in Start()...then yes it's happening at the same time as my code...which is why my original question, at the start of all of this...is what other method or listener can I use to know when the Canvas is done.
This would only work if I could tap into the Canvas' Start method.
Nah, this works because ALL start methods are being called in a frame, so in the next frame basically, it should already be updated. But jsut to be sure, we do not wait for frames but seconds
All Start methods are called for all pre-existing scene MonoBehaviours at the same time, yes...but they don't all FINISH at the same time.
That's what's causing the issue. Because the Canvas hasn't finished it's "Start", the UI elements aren't in their final positions.
Thats what I mean... do not rely on Start(). One frame calls ALL start methods once, then all are done. Next frame all should be done.
No. That's a misconception. GameObject A and GameObject B will have their Start called at the same time (provided they pre-exist in the scene). However, GameObject A may finish it's Start before the next frame, but GameObject B might not.
But in ONE FRAME...
NO... ALL Start methods don't not ALWAYS finish in ONE FRAME. That's what I'm saying.
You get it now? its called before anything is calculated your script already tries to access
all Start methods are called before the first frame? unless you're running async code and waiting for frames they will finish before anything is rendered and before the next frame
Exactly, and because Start methods can be coroutines, they can, "not finish", before the next frame. And as I said, we don't know what goes on under the hood of the Canvas because there's no documentation on it.
... I give up
I genuinely think you're going down an unnecessary rabbit hole here, I don't believe Awake or Start is even your issue here, nor is the Unity implementation of Canvas
Agreed.
Interested in your opinion on this case 🙂
I posted it above - my guess is a misunderstanding in how the UI components are designed to be used
Ah, missed that, my bad
though I haven't looked at the code in detail
I still think its the mixture of Dotween and the execution order, that is giving you the issues here. You throw a position into dotween before the UI could update in the execution order. Just for testing you could just use vector3.lerp in update and pass in your transform.position as target instead of a vector3 predefined
read through properly & I think you're right (unless he is actually changing those layout groups / adding children to them) - easy to test & troubleshoot further anyway
if no luck with the above I'd also test just removing the layout groups and see if you still experience the same behaviour
the interpretation of Start being async and requiring multiple frames to "finish" just screams issues with layout groups to me
before you do this, consider using Ink, which has a unity plugin
there's also the Dialogue Engine asset that ships with a conventional video game dialog ui for runtime that is compatible with Ink authored dialogue scripts
there are a lot of details in this stuff
usually you use unity barracuda to do this. you can also browse Keijiro's githubs to see if he has an example of what you want to do precisely. inter-process communication is going to be too slow to send realtime video
I was looking into IPC and I thought Mapping should be quite fast no?
if you are suggesting I do the ML detection using unity itself, I don't think I can, unless unity has a way to load pytorch models like python does? if so, I would appreciate any links that does it (the contractor of the project provided their own trained models which we have to use so, I can not train or use other ML model)
Alright, I’ll look into it, though for now this works for me ;P
hmm
what is this for?
i think there are a lot of moving parts in what you're describing
if you had to make an application for a lot of people, that like, works, it is going to take you a year at least
which it doesn't sound like that's what this is
reading the webcam in unity, from the CPU, then sending each frame to another process, then running something on that process, and rendering something on top of it is going to have very high latency
you can't just Not Engineer a way to deal with all of this. for example, if you try to do this synchronously, i assume the FPS will be very low (below 10) and it will screw up other stuff in unity
I feel stupid right now, but I cant get this simple vector math right and this is killing me:
I want to move an object along the plane projected by the current camera projection/near clipplane, at the position of the mouse, so that it always has an offset the same distance relative to the camera. How do I do this?
Every version of project on plane and math I've tried hasnt worked, even though Ive been SURE on like 4 of them lol
Even chatgpt cant give me a straight answer
if there is a way to create a pytorch model (what python program is using) in unity and then use the already trained weights, then I can get rid of python completely
so I assumed this is what you meant when u said
barracuda in unity. (but as far as I have researched this does not seem possible)
what is this for?
like what's the idea?
it is possible
but in order to help you, i need to know what the idea is
🙃 then nvm, I misunderstood your comment
what is the application?
I thought this is what you suggested
then I can get rid of python completely
you can, there is a way to do this
you can use barracuda with a pytorch model
but i am asking what the application is
what is the idea? what are you making?
I am really not allowed to discuss it outside the company, but it is basically an application that does some object detection on some camera feed. the camera feed is coming from a server.
(it has already been 1.5 years in development, so it is not like I am building things right now)
very interesting, will look up how to do it!
thanks!
what does it do?
there isn't anything sensitive about this
like what are you trying to do
i appreciate the explanation because it will help me give you a Right Answer
which is going to save you literally months of time
I am not following, what are you asking exactly?
I did mention what the unity application is doing and what I am trying to do, to repeat,
the app is supposed to be rendering frames after running object detection on them, detects people, cars, etc.
what I am doing is piecing up multiple pieces of the project together,
i.e. the camera feed to unity app to python program.
is there something unclear about this
in less abstract terms, is this like
a security camera feed? and why is it in unity? to recreate a 3d environment?
like what is the application
trust me, your people say what this is to others all the time
there isn't anything sensitive about what it does
alright well i think you'll figure it out sorry i can't be more helpful
Kind of security feed, it is for private surveillance
why unity? my company is developing applications with unity, I am not sure either to be honest how the tech stack was selected.
there is no 3D environment, there are multiple people who are going to get the stream back after applying object detection on it. so, after I do some pre-processing on the image, I will have to send it back to those people, tho we are currently only testing with a single person who must receive as much in real-time as possible.
this person is the one who sending the feed in the first place, the rest are getting it for different purposes (some for further analysis, some for storage keeping, and so on)
I don't care if other people are saying sensitive data, I am just making sure I keep my side of the contract, so I take some time to write it down and make sure I am not sharing anything that is sensitive (which is why I took sometime to reply, not like I did not want to say it, I just made sure it is within the permissions of what i am allowed to share)
okay, you're saying the feed comes from a server. are you saying it's an NDI based networked camera?
i get it. i don't think it's really surveillance. it's like people counting right?
NDI? what does it stands for
it's a networked camera standard
No.
it is a surveillance feed, not counting feed.
anyway since it also sounds like you want to make this a real, normal application
this is kind of hard
you can search "pytorch export to onnx" and "unity barracuda pytorch onnx" and you'll find the pretty straightforward docs
you will be able to convert the pytorch model (a piece of python code) and its associated training checkpoint into a onnx inference model
then you can look at keijiro's barracuda examples for running this on a live camera feed
webcam textures only come in from UVC and similar devices. he also has a package for NDI cameras, which is far more likely to be what you're actually going to be able to use
what do you mean?
reading an RTSP stream or whatever is going to be hard.
there's just a lot of moving parts. like i said expect to spend at least another year making something that will actually work
beat me, it is going to be
RTSP
yeah
the dead line in 2 months.
uh oh
and I was assigned to it last week, so I barely got introduced to the topic 😦
well one thing you can do is turn rtsp into something else using ffmpeg on the machine
i believe keijiro also has an example of this
this is the best approach for networked camera feeds though - https://github.com/keijiro/KlakNDI
will look it up
thanks!
whatever you use for video will already support NDI
klakndi already uses an "ffmpegpipe" i believe no you will have to find ffmpegpipe, authored by keijiro, in its latest state, and then adapt it to write to unity rather than the other way around
there is probably an asset store package, but i doubt it will be hardware accelerated so it will be too slow
i believe that's what this package does - https://assetstore.unity.com/packages/tools/video/vizario-h264rtsp-player-222837 - pipes from ffmpeg
@karmic surge hope this helps. don't have a heart attack
@karmic surge you'll want to get acquainted with https://colab.research.google.com/drive/1O1KDIVsmYyYDqEqv7hEqofsHMCa49xaZ?usp=sharing
as an example of converting a complex model to something that is compatible with barracuda
imo all of this might be too slow for real time each frame application. i don't know if you need that @karmic surge you probably want to just run 1 frame per second for inference
the model takes exactly
between
12ms to 15 ms to do object detection
so my hope is to be able to do the pre-processing and communication within the next
15ms (33ms for 30 fps)
if the model is already gpu accelerated, i would expect it to take 2x as long once you go through this pipeline
unless you figure out a way to keep the video in hardware, it will take about 2-5ms of latency to deal with all the decoding and copying, and then unity itself has to use the GPU to render. on NVIDIA platforms, you would need tensor cores if you don't want to impact rendering performance
anyway, id on't think barracuda uses tensor cores
so it's hard to know
i would expect it to be running at 10-15fps
if you need everything synchronous
of course, you shouldn't be doing that. you should just buffer it, the realtimeness is pointless
well,
will see how it goes.
Thanks for the input and comments
How is it determined whether AnimationClipPlayable is done playing? If I just let it play and it reaches its duration IsDone() returns true, but if I SetTime() to something equal or larger than clips duration IsDone() returns false. Does anybody know why is that?

Hi, I created a Server Api which gets called from my game.
Now I need to identify the client (the user).
So, I thought to generate a random GUID Token and save this on the local machine.
When The user start the game the token will send to the server an check if there is a client for this token. If yes the server send a success-command.
Is this a good and save way?
I Don't know if it is a good idea to save the token locally on the clients computer
By "identify" do you mean authenticate the user (username + password combination) or just check which client sent a request for tracking purposes?
What will you do to stop people from identifying themselves as other users?
Also what if a user wants to "log in" from another device
how will the token get from one device to another
These are the reasons there is generally some kind of authentication/sign in process
Hmm good question.
My Problem is this:
I want to connect Twitch with Unity.
Twitch has a Authorisation-Flow. The User needs to call an url with my client id (the client if of the registed app in twitch).
After calling the url a twitch window pops up where the user can authorize.
After clickíng the button, twitch sens a access_token to my server
No I don't really now how to authenticate the user, because on the client there is no Token, its just on the server.
My idea was to generate a token by starting the game and send this token after clicking the "twitch-Button"
sup yall, I'm making a top down player controller and I'm trying to get the player to dash or roll or dodge or whatever
any words of wisdom? I'm pretty stuck. I've been looking up a ton of stuff and nothing seems to work or make sense
Okay Im having an odd issue at this link you can download packages to create in app rating for android, https://developers.google.com/unity/packages#play_in-app_review but for some reason even when I download and install the package it wont allow me to access it and wont let me see the linked namespace og Google.Play.Review. Any idea of why I cant see this namespace?
Im using unity 2020.3.30f1
One client ID for your app (for all your users), or one per user?
Am I on the right docs page here: https://dev.twitch.tv/docs/authentication/
One ClientID for my App.
Use this site: https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/
And there the Authorization code grant flow
Okay, so now I get why you need a unique token to link Unity with your server
Yea, if this is a good way
If not I think I will create an own User System and the user have to register and connect the twitch account on a website
If you have one token for the whole app, then I'm not sure why you need some token to make the link, just request the server? Or there's something I'm not getting
At First you need a ClientID that Twitch know your App.
With this CLientID the User Can start the Authorization code grant flow
For this flow the user call an url with the clientID of the app
After doing this my app is connected to the twitchaccount of the user
Oh, I was on the implicit flow section my bad
and I gets the acces_code.
With this code I can get informations about the user, maybe the name or the viewer count +
My Problem is, how can I get the access_code on the client
On this Step, my server know the user but the client doesn't
Yeah you'd need a way to bind the user requesting the token through your app, to the server
I would do a full authentication for that. Your user would log in using an account, and from there, access tokens are linked to the account (database maybe)
You mean a full authentification service with password and username?
Yes
Yea, thats maybe the best way
User logs in from Unity, which does the necessary binding on your server, so you get their access token
With that you could even switch to one of Twitch simpler auth methods, like the implicit one
yea thats true
And you would the user directly log in in the unity app (so that the user type the password and the account in unity)
Yes
@fresh salmon I Just found this:
I will try this way tomorrow
They start a local webserver for teh auth-process
Yep that's another option
Jup, with this the user has no need to create an account
The code in this gist is rather old-styled though (async callbacks date from years ago when async/await was not a thing), so you could try and make it clearer as well
Yea, true 🙂
ok, someone in here mabey. Is anyone in the mood to come call with me. other ppl cant fix my (i think) easy issue. and i am so tired of typing back and forth.
@fresh salmon Thanks! Have a nice day
bro. noone can help me. fr?
Start by not asking your question in multiple channels (cross-posting). And then ask an actual question.
There's little chance someone will get in a call with you, you're better off posting a video of what's happening as well as a complete description of the issue. See #854851968446365696 at the top for how to ask a question
yeah bro i know. i have typed my stupid problem like 3 times now.
Then you can make a thread, and reference the thread. Still no cross-posting though, if you link the thread in one channel, keep the future links in that channel only
i give up. just, nvm
@swift quail Stop crossposting. It's not anyone's job here to answer your question. Stay in one channel and be patient.
If I cast a unity Object to system object will there be issues with null checks(as unity overrides equality check for destroyed Objects)?
not ??= checks but just if (value == null)
The overridden operator should still be used right?
you should test it, but I assume that null checking a system object will behave differently
Wouldn't it just be treated like a base type? Meaning that if there are any overrides, they will still be used.🤔
I have a function that’s trying to run asynchronously:
```public void LoadGameNow(string fileName)
{
Debug.Log("Starting LoadGameNow function");
SurrogateSelector surrogateSelector = new SurrogateSelector();
StreamingContext context = new StreamingContext(StreamingContextStates.All);
SOSurrogate.PopulateSurrogateSelector(surrogateSelector, context);
IFormatter formatter = new BinaryFormatter(surrogateSelector, context);
FileStream s = new FileStream(fileName, FileMode.Open);
Debug.Log("Starting LoadGame deserialize now");
stateData = (GameStateData)formatter.Deserialize(s);
Debug.Log("Done LoadGame deserialize now");
s.Close();
if (stateData.currentTacticalMap != null)
stateData.currentTacticalMap.InitSceneObjectsOnLoad();
Debug.Log("Done LoadGame function, invoking completed event now");
onGameLoadComplete.Invoke();
}```
When I invoke the function normally (not asynchronously), it runs as expected, but holds up the main thread for a few seconds. I do this like so: GameState.Instance.LoadGameNow(filename);
However, when I invoke it as a “Task”, it never even reaches the second Debug.Log statement, nor do I get any exceptions or errors in the log. This is how I launch it as a task:
Task runningLoadTask= Task.Run(()=> { GameState.Instance.LoadGameNow(filename); });
When I step through the function using the debugger, it gets to the line : SOSurrogate.PopulateSurrogateSelector(surrogateSelector, context); but when I try to step past that function, it never gets to the next line. When I try to step INTO that function, I find myself inside some internal class Messager function- SendMessageCallback(IAsyncResult result).
Any idea’s how to get that function to run properly, asynchronously?
Null checks will no longer check for the object being destroyed
There's not a lot of good reasons for casting to object, what's the purpose of this?
When you run code in a background thread and you try to access any Unity engine objects, your thread will be unceremoniously killed by the engine
I was aware that was the case when usin threading- that's the case when using a TASK also?
Task.run runs in a background thread
It's not an inherent thing for async in general but in this case it's a bg thread
In addition to what has been said, make it an async method to run it asynchronously on the main thread.
how do I pass arguments into MacOS terminal? On windows I know you use /C at the start but that doesn't work on Mac
Hello, I'm in the process of creating an item system for a roguelike project.
I have a bunch of key game events happening that I have categorized into Interfaces.
On any given Item (Relic in this game), I simply inherit from the interface to get the functions I want.
Everything works great, I have a quality of life question for it instead.
I'll showcase one of the interfaces and a class as an example.
I have the EncounterEvent Interface.
public interface IEncounterEventListener
{
public void OnEncounterStart();
public void OnEncounterEnd();
}
In another class where I want to do something on encounter start it looks like this.
public class ExampleRelic : MonoBehaviour ,IEncounterEventListener
{
public void OnEncounterStart()
{
//Do some specific logic.
}
public void OnEncounterEnd() { }
}
Here even though I don't need the OnEncounterEnd, I still have to declare it and give it an empty body.
I tried adding a default interface implementation like so,
public interface IEncounterEventListener
{
public void OnEncounterStart() { }
public void OnEncounterEnd() { }
}
{
public void OnEncounterStart()
{
//Do some specific logic.
}
}
This fixes the need for me to declare it in the ExampleRelic class, but I lose out on my IDE's ability to generate the missing interface functions for me xD (this is such a stupid problem haha)
Is there a way to get the best of both worlds?
Also the issue is, this is just 1 of the interface, there's several others and if implemented they look something like the screenshot.
My ideal solution would be to get something like this Generate Unity Event Functioin window in Rider, but for the implemented Interface instead.
Any help would be appreciated thank you ❤️
That is what I am thinking, since those opperators are on object and object is the base odject Object. So far I am having no issue, but I can't explain how deep down I want Unity to actually change their null operator like they were thinking so ??= works.
Like everytime I do if (value == null) not even if (value is null) kills me.
a little part of me dies because of you Unity.
So i cant find a testing channel so i will put it here.
I am testing an attribute i wrote that will automatically link components in the inspector.
So, my tests will create a new game object, attach a monobehaviour, and then set the Selection to that object so it can get a chance to link.
It then waits a frame, validates, and then over.
My problem is once the tests are done and unity reload the previous scene, it doesn't revert the selection if i make a change.
[SetUp]
public void Setup()
{
_previouslySelectedObjects = Selection.objects;
}
[TearDown]
public void Teardown()
{
Selection.objects = _previouslySelectedObjects;
}
This doesn't do anything if the previous selection is the scene
Not sure I get this right. Why should it revert something if you make a change?
becauses Tests should not "change" anything
everything it does should be reverted
which Unity handles automagically..... except for selection
well it does, except when i make change to the selection at least
Is the selection itself tied to the test scope or the editor scope?
what?
Does Unity treat the Selection as an Editor object and therefore does not care if you are running a test or not or is it storing selections while running a test differently? For me it looks like the selection is not tied to the Test.
no, unity makes a new blank scene to put everything the test generates into
Okay, understand that. Just trying to understand, what selection you are doing that does not get reverted. But maybe I am just stumped 😄
would it help if i made a video of it? lol
I've tried manually creating a new inspector window and locking it to the created object in the test scene too instead of using Selection but still nope
I am coming here from a perspective of a test newb, so I tend to ask simple questions 😄 But as you said, Unity generates that blank scene and creates the test objects, how would it keep that selection alive if your test is done? Sounds like a valid behaviour that the generates objects of the test are being removed when the test is done
Without the selection code it works fine
And the whole code is just those lines up there?
oh actually not its not. hmm was before
welp looks like it never worked
so my question pivots to "how can i make this work" insteaed
because that jazz is annoying
Okay, lets elaborate then your new question. What exactly do you want to do? Just to start from scratch here 😄
for the selection to return to what it was after a test
Okay, and the "valid theory" I brought up, that the selection is not existent after the test is done, could that be a thing? Basically you are having two different objects in terms of lifetime IDs
So you might have to store not the objects but som ekind of array of names/ids, whatever we can ask for and then search the previous scene for that to select it?
the selection always exists; as you can see in the video it never actually unloads sample scene
But as the scene dropdown arrow collapses back again, I assume it is somehow generating a Test scope copy of your objects to not affect the SceneEdit version of it
Im trying to do something very simple but i dont find the exact way of achieving it..... having a variable stored into an object type and also knowing it's type which i stored in the type TypeCode enum... i would like a function that passing the object and the type returns the variable casted to its type
public static T ConvertObjectWithVarType<T>(object obj, VarType type)
{
switch (type)
{
case VarType.Int:
return Convert.ToInt32(obj);
something similar to this
but i dont find the way of achieving it since if i do this approach i have to know the type in the caller to in order to do.... Convert<TheType>(object,vartype)
But is the type of the object? Is it not guaranteed to already be whatever VarType is?
Because then you might aswell just return (T)obj 😄
This might work otherwise: https://learn.microsoft.com/en-us/dotnet/api/system.convert.changetype?view=net-7.0
But the thing with this is that it can go wrong in so many ways
So tbh you might aswell create a method that takes a dictionary of types it can convert, with its value being the way to convert it
I don't understand how you could have an object type, and then proceed to pass a generic of the exact type you need. I would assume object can then just be the generic type you try to convert to in the first place, or it is the type it currently represents, and not object.
You can just do that and compare types, no need for the enum
What I would like to know is how you end up with an object type in the first place
lets say its a tutorial with multiple steps, a step can have tons of results to get to the next step, and in some cases i want for the next step to have the last value i stored in the previous step
it can be a int, double, list of ints
and i thought of storing it into an object and in a later step cast it again
Yes but then the object is still the type you set it as in the first place, so you only need to cast it
And since you seem to know the type you want judging by the generic method, you can just explicitly cast it back.
yes, but i wanted to do that inside of a method, which i think is not possible
i would have to do this:
i guess i would have something similar to this
You cant use switch on types directly.
You either have to use string comparison or do your enum as you do right now if you want to use switch
yeah but you get the point, i would have to check 1 by 1 the type i stored and cast in accordance, correct?
Yeah, you want to store probably everything somehow. I get that point
i wanted a function by which i would do:
var myCastedVar = Converter(myObject, myType);
which would be easy if i could store the myType in a way i can use it for casting later
because then i would do
var myCastedVar= (myType)Converter(myObject,myType)
I mean, you can just turn the type to a string, and compare the string equivelant, i.e. switch (type.Name) {} and case ("int") so that is no problem.
I'm confused why you would have multiple types as an argument. If it can be an Int16 and a Double, why don't you just assume it's always a Double?
Also, like I said, if you store your variables in memory as an object, your underlying type is still the same, so you can just explicitly cast it back. There is absolutely no need for all this conversion stuff, unless you explicitly change the type using something like .ToString()
And even if you did, this exists: https://learn.microsoft.com/en-us/dotnet/api/system.convert.changetype?view=net-7.0. But like I said, it can go wrong very quick.
Like I said here... but why not repeat it 😄
I have no idea what you are referring to since I can't see your messages
Ohh, you blocked me, got it 😄
Even if the type is something that can't be implicitly cast (like a string and an integer), can't you just pass nullable types? If you only pass an integer, you would pass (null, "string") for example, or (1, null) in reverse
Figuring out what you are passing is seriously complicated, especially once you start passing more than 1 argument
Here you just need to do a null check
var buildID = currentMarker.getValFromPreviousStep
? (int)GetPreviousStepParam()
: currentMarker.buildID;````
fuck it
for the moment ill assume all them are integers
ill see on each case depending on the context
GetPreviousStepParam() returns an object btw
which in this case it has to be an integer
so whatever
thanks a lot for your help and for allowing me to see how bad im doing things
You can always just cast against the type and see if object.type "is" your desired type you expect on the next step.
Is there any way to automate the running of a batch file in Unity when you press the play button? I have a batch file that generates some assets that are saved in the Resource folder. Ideally I'd like to run this batch file before Unity starts the project so I always have the latest version of the generated assets. Any help would be appreciated. Thanks! 🙂
Editor application. Playmode state changed
Then just invoke and wait until your batch file finishes
Thank you! I'll look into that 🙂
Quick question about DLLs, when they're compiled and added to Unity (drag and drop the DLL into Unity), does it matter if they've been made with .Net Framework 4.8 or .Net 7?
If they're compiled to intermediate language they should be the same from my understanding?
.net is the intermediate language. Or rather IL is part of dot net. And there might be differences in it between the versions.
So what's important is setting the target to .Net Standard 2.1 and it should be good?
(In unity)
I guess so. Honestly not sure what net versions unity supports ATM. But I think standard is among them. They do mention it here:
https://docs.unity3d.com/Manual/UsingDLL.html
Ok so it seems .Net 7 is supported from microsoft docs! Thanks for the info it makes more sense now!
It means .NET standard 2.1 dll can be used with .NET 7 project. Not really relevant to Unity
.NET 7 dll cannot be used with Unity, you should build the dll targeting .NET standard 2.1 or lower to make it compatible with Unity.
It seems to work when I put it in Unity though
Like I build my DLL from a .NET 7 project and I had no issues
Yeah just wanted to know if there was specific things that were not compatible
you should author an asset importer*
a .net 7 targeted DLL is not generally compatible with a .net standard 2.1 runtime
So what does generally means? Is it like part of the features might not be supported?
i don't know, because i've never done this
i have never tried to do something that the docs say directly not to do so i have no experience with it lol
i have never tried to run a .net 7 targeted dll on .net standard 2.1, because that's a wrong thing to do
did you author TypeCode? you are complicating things with generics. i don't think unity supports pattern matching in c# yet, does it?
you should make your class library target .net standard 2.1
Pattern matching is supported.
even then, unity's .net standard 2.1 implementation is incomplete
Yeah makes sense haha
And just so I understand it well, .Net Standard is just an old version of .Net right? Framework seems to be "deprecated" and standard is on the way out as well right?
@stuck onyx
(not recommended, reimplements System.Converter's architecture in essence)
class UserTypeCode {
public int typeId { get; private set; }
public static readonly UserTypeCode<int?> INT = new(0);
public static readonly UserTypeCode<string> STRING = new UserTypeCode<string>(1);
public static readonly UserTypeCode<bool?> BOOL = new UserTypeCode<bool>(2);
private static readonly IDictionary<int, UserTypeCode> typeCodes;
static UserTypeCode() {
typeCodes = new [] {(UserTypeCode)INT, STRING, BOOL}.ToDictionary(t => t.typeId, t => t);
}
// *** this is the thing you are trying to author ***
public static T ValueOf<T>(object obj, int typeId) {
return ((UserTypeCode<T>)typeCodes[typeId]).ValueOf(obj);
}
// optional, if you want to somehow make it possible for strings to be interpreted as ints in general, or you can store a "1" in a typecoded field of int
virtual public string ValueOfString(object obj) { return ValueOf(obj) ?? ""; }
virtual public int ValueOfInt(object obj) { return ValueOf(obj) ?? 0; }
}
public class UserTypeCode<T> : UserTypeCode where T : class {
public virtual T ValueOf(object obj) => obj as T;
internal UserTypeCode(int typeId) {
this.typeId = typeId;
}
}
i believe your underlying desire is to interpret strings as ints and vice versa sometimes
this might be easier to do with a struct IntString that stores whatever and has implicit casts
i don't know if you need to deal with general stuff
you can also look at the implementation of the system converter methods which are the same thing
.NET standard is not bound to specific runtime and thus cannot be executable, it's literally 'standard' dll format that can be used for project targeting either .NET Framework, .NET Core, or other runtimes like Xamarin.
Oooh this is why I can't make a console app using standard for example, got it
Makes so much sense now thank you 🙂
Can someone please look into my code, It's about matrix multiplication so be watch out.
The critical code, the one which I'm unsure of is at line 85 I still send the entire thing because I'm not sure about anything anymore
My issue is that using the transform component, the child rotates around it's self instead of rotating around the parent this is my code:
https://paste.ofcode.org/4TKq2UG3SSbtGYuCaKFzR
Unity provides a Matrix4x4 struct to handle this stuff you don't have to write it yourself
yes I know
but I litterly don't understand it that's why I'm making my own..
ik that's just a me thing
It's simple. You create them with Matrix4x4.TRS(translation, rotation, scale)
Then you can multiply them together or use things like MultiplyPoint etc
sounds really easy when you say it like that, and what are quaternions?
Quaternion is a way to represent Rotation which is different then the way rotation are handle in a Matrix.
In matrix, you represent rotation with 3 vector. (Up, Forward, Right)
so quaterion is just a more accruate way to store rotation
no
Its a different way of representing rotation. Quaternion is vector of 4 numbers
Euleur Angle, Quaternion, 3 Vectors and AngleAxis are multiple way of representing rotation in space. There is probably more.
I think I'ma stick to matrices for now, but thanks
Simply a data type that stores rotations
Anyone here experienced with Unity's relatively new Navigation package (com.unity.ai.navigation | https://forum.unity.com/threads/experimental-ai-navigation-package.1126961/ )?
I must be missing something, but I am getting the following error when trying to get the remaining distance as per the NavMeshAgent documentation here: https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-remainingDistance.html
"GetRemainingDistance" can only be called on an active agent that has been placed on a NavMesh.
Thing is, from my understanding the new Navigation system doesn't use a baked navmesh in the traditional sense.
My agent is within the bounds of a LocalNavMeshBuilder and my floor has a NavMeshSourceTag
What am I missing? The only thing I can think of is that the agent could be spawning on a non navmesh object. I will do some checks into this, but wondering if anyone knows offhand if I'm doing something dumb or if remaining distance doesn't work with the new package?
The NavMeshes don't need to be baked in the editor but they do need to be baked at some point...
The AI Navigation package provides a workflow for building and using NavMeshes at runtime and at edit time through components.
So in theory I could disable all objects in the scene and bake once, and then re-enable them and forget about the baked navmesh?
The environment is procedurally generated, was going to use https://github.com/Unity-Technologies/NavMeshComponents/blob/master/Documentation/NavMeshSurface.md to bake it during runtime. However, navmeshbuilder appears to be more efficient?
Or am I misunderstanding what you mean?
I'm not really sure what the difference between NavMeshBuilder and NavMesh.Build() is
I don't have a lot of experience with it
I would add to what they have said, though .net standard has a better cross platform support for .dlls in unit. Also why .net library might be working is if you aren't using any new features the IL code should at times still be the same, but it will break randomly on you. And yes .net standard/.net core/.net framework are all deprecated now thank god, and just the .net 5+ are the only supported versions. Unity last I heard is on track to support .net 6 this year if all things go on track(which it is unity so probably won't).
Though .net 8 will be amazing as a lot of performance increases have happened for it. Like Linq will be the defacto
It's a new navigation library that Unity released built from NavMeshSurfaces, I'm super new to it too, but lets you do REALLY cool things, like dynamic navmesh during runtime. Would highly recommend checking out the demos.
Now if only I could get it working for my needs 
the documentation here seems incrediby janky 😵💫 https://docs.unity3d.com/ScriptReference/AI.NavMeshBuilder.html
the way the engine/editor classes are mixed
Yeah that is pretty jank 😂
Oh got it! Yeah I'll stick with Standard 2.1 then, thanks for the added details!
Hopefully we get full support for .Net 6+ soon haha
is this possible? btw sorry for bad art and typo in name
Everything is possible
Hey good evening yall ! Been using Unity for about a good 10+ years, I just ran into a issue that really has me scratching my head here, So I have a CSGO knock off I bought a few a years ago, I dusted it off, and am doing the reskin I planned and am hooking it up the game network I am building, But check this , , It's in Unity 2018.2.6f1 , It was "made" for mobile, But was well written and has the pc and controler input classes configured , it loads flawlessly , not one warning or error, When I switch the workspace enviorment from androird to either pc or universal windows , I get the weirdest syntax errors i have ever seen lol, I am think maybe its like a encoding data corruption issue or somthing, but its not I checked the documents with a tool , I am getting 14 syntax errors that are not sytax errors
This is working mobile verison with no errors or warnings
this is after I switch it to pc
scroll all the way to the first error and start there. also check for any preprocessor directives, could be something that's only being compiled for Android or whatever. also get your IDE configured !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Ok I willl double check this, but I have like 20 other projects with no issues on my pc this is why I am spooked
nagh dident solve the reproblem, I even reinstalled the editor, I am switching back to andorid enviorment with no errors, I am going to send to cloud build with a target and see what happens
whenever i get weird shit, it's misconfigured assembly definition.
it's just a preprocessor directive in the wrong place
you shoudl be able to reason about this code
and find it pretty quickly
hey, what is the startTangent and endTangent and how to calculate them?
im watching a tutorial but they didnt say why calculate like this
You can 'visualize' the tangents to understand a bit better looking at the AnimationCurve.
They make it so you don't have a straight line between point A and B, but a line that goes from A to B that bends due to the tangents.
Off the top of my head I don't remember exactly if the Draw Bezier are treated as a point, or as a direction, but basically, they curve out your line.
For you to visualize it a bit:
https://docs.unity3d.com/uploads/Main/AnimationClampedAutoTangents.gif
https://docs.unity3d.com/Manual/EditingCurves.html
is it possible that your hand is a bit shaky?
Does anyone know any solutions for UI toolkit with MVVM / databinding?
how difficult is it to rename my project?
am getting tired of "new unity project"...
Easy - just rename the folder and go to Project Settings and change the product name
Lastly you'll have to tell Unity Hub about the "new project"
all right, seems to work. had some errors about my main.dll but that vanished after reimporting a couple times and doing random things
Do you have all of the nessesary using tags?
yes
it debugges 1 btw but still loads 0. scene
Got a weird issue occurring but only when I FIRST open my project, run the game. When I try to load a Saved game: Unity freezes up for about 40 seconds.
If I stop playing, and re-start playing (without closing unity), the LoadGame process just takes two seconds, and unity does NOT freeze up. No errors show in the console, and everything works, unity “just” freezes for a while.
The load process IS configured as an ASYNC operation, and I have a “processing” UI window that pops-up and animates a thing, to show it’s not frozen. When the issue occurs, the “processing” windows DOES pop up, animates for 1 seconds (probably the Task.Delay(1000) below), then its animation freezes when unity does.
This is the LoadGame function:
code
public async Task LoadGameNow(string fileName, System.Action callback=null)
{
// Debug.Log("Starting LoadGameNow function");
await Task.Yield();
await Task.Delay(1000); //TEST: 1sec delay to test long load times
SurrogateSelector surrogateSelector = new SurrogateSelector();
StreamingContext context = new StreamingContext(StreamingContextStates.All);
SOSurrogate.PopulateSurrogateSelector(surrogateSelector, context);
IFormatter formatter = new BinaryFormatter(surrogateSelector, context);
FileStream s = new FileStream(fileName, FileMode.Open);
// Debug.Log("Starting LoadGame deserialize now");
await Task.Yield();
stateData = (GameStateData)formatter.Deserialize(s);
Debug.Log("Done LoadGame deserialize now");
s.Close();
await Task.Yield();
if (stateData.currentTacticalMap != null)
stateData.currentTacticalMap.InitSceneObjectsOnLoad();
Debug.Log("Done LoadGame function, invoking completed event now");
gameStarted = true;
onGameLoadComplete.Invoke();
if (callback != null)
callback.Invoke();
}```
What could be causing unity to freeze up on “first” play only?
I have something similar, and I profiled it a while ago and it was some sort of read file operation
it happens for me when I first fire off a big async operation - but it's not hanging in my code, it's hanging before it
but i gave up trying to solve it since it doesn't happen in builds
"doesn't happen in builds" OH! guess I should have tested that.. VERY good to know. so it just freezed up all of unity for you too?
i don't recall if this was the line
but yeah, my unity goes dark for a long time.. like 15-30 seconds
(protip you should format your code blocks with cs):
how are you calling your LoadGameNow method?
void OnLoadConfirmed(int confirmButton)
{
if (confirmButton != 0) return;
processingPane.SetActive(true);
string filename = savePath;
filename += instantiatedFileButtons[selectedFileIndex].textFieldA.text;
filename += saveGameExtension;
Debug.Log("starting load function LAUNCH");
Task loadingTask=GameState.Instance.LoadGameNow(filename, OnLoadComplete);
Debug.Log("done with load function LAUNCH");
}
void OnLoadComplete()
{
processingPane.SetActive(false);
selectedFileIndex = -1;
OptionsPopupWindow.PopUp(CloseWindow, new string[1] { "OK" }, "Loading Complete");
}
you don't have to type code ha
^ lol
you just type the cs and ticks on the same line
(processingPane is the UI thing that animates)
do I need to hold onto that Task return value perhaps? I let it fall out of scope
storing it just for debug stuff
(note the 33 seconds)
sorry was afk
I just keep typing.. lol
so i'm generally not familiar with this sort of use but you're not putting your task on another thread
Task loadingTask = GameState.Instance.LoadGameNow(filename, OnLoadComplete);
I believe that's just gonna hang for you
if you want to run it as another thread I think you have to do something like
Task.Run(async () => await LoadGameNow(...));
if you need your game to be responsive in the meantime then you need to callback to the game when the task is done, or otherwise set a value/bool/whatever to tell the game the level is loaded
thats actually how I started, but unity REALLY disliked that (I touch unity stuff)
based on the log, I dont think it's waiting for that function to complete...
i don't think it's too bad - i think there's only one gotcha that i know of, that UGS tasks have to be done on the main thread for some reason
oh, you're right
Debug.Log("starting load function LAUNCH"); Task loadingTask=GameState.Instance.LoadGameNow(filename, OnLoadComplete); Debug.Log("done with load function LAUNCH"); <- these showup BEFORE the stuff inside load
hmm.. I suspect your right on with your first answer- some kind unity- open file thing/bug?...
right, that's correct.. as your code is written, anyway
your declaration of Task loadingtask returns immediately
but no idea what the root cause is.. i seem to only experience it after leaving unity alone for a few hours
AH! I did get it once without closeing/reopening unity, but couldn't duplicate it... I'll try that tonight
alright, sonds like it's a shrug and move on issue. Thanks for the help and sanity checks!
that's a mess 😃 ...
The thing with asyncs in Unity you'd need to make sure they're being cancelled before getting in/out playmode
Also, your task.yields there are useless
yeah, the yields were really just for testing. how else is it a mess?
string+=string?
I assume you're intending to filestreamed asynchrounously, youd need to add FileOptions.Asynchronous...
Back in the day this may fallback to async if your operation already asynchronous not sure if that's still the case today, you should check...
Dang, I just tried that, alas, I still get the freezeup for 30 sec, when I close/reopen unity , then test 😦
Question can I make custom Roslyn analyzers for unity? I am wanting to make it so all my debug calls will get if statements around them so memory alocation doesn't happen if I am not logging that level. I was thinking of using a weaver(as VRTK made one that works with unity using fody), but I would like it to jusst automaticly be added, and I know Roslyn analyzers can do that.
Sometimes I forget google is a thing which is ironic being a programer. https://docs.unity3d.com/2020.2/Documentation/Manual/roslyn-analyzers.html
I dont think you need a roslyn analyzer and if statements. Our debug library is using conditional attributes on wrapper methods. That way we dont even have to wrap anything else in preprocessors, the call to the conditional method simply gets stripped out of production builds
I want to include the debug methods/don't want to have to make a method wrapper for it(as that messes with the stack trace), and also that would require me to make,,, oh what ever they are called the compile directives or what ever. I have already found a pretty good route for rosyln analyzer with ILogger. Though need to test it out more. This will allow me to have some cheat code to set debugging for users that need help.
Plus this way any other programmers don't have to worry about it, all the work is already done, and I can use standard practices.
if stack trace is the only problem, iirc one way to make a function disappear from stack trace is through inlining.
i dont know if it works even now in debug builds, but something worth trying
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.methodimploptions?view=netframework-4.8
how do i stop unity from using samplescene as main scene in vivox chat channel sample?
btw i need a guide for this
random icon example on corner
can some one pls helpp me i have some errors in a binary code save system i am making for my idle game
In a for loop, I have to do for each iteration an operation on an object's transform and on the gameobject itself.
what is better :
- first : Transform myobj = stg
- then : do stg with transform
- then : do stg with transform.gameObject
OR
- first : GameObject myobj = stg
- then : do stg with gameObject
- then : do stg with gameObject.transform
I know the performance gain must be pretty small but i need to do this for thousand of objects.
Thanks a lot !
I think it's the same performance but I prefer the second option. Looks cleaner ig
Okay thanks a lot 🙂
Hello guys i wanna ask for performance reasons 🙂 my trees im not able to put in Terrain painting because tree has stump and Top , unity dont allow me use this kind of mesh prefab ..... so if i put tress as objects in to the scene of course not thousands because alll are chopable will have it big impact on performance?
private void CarveMazePath(int x, int y, List<Vector2Int> cellPath)
{
cell = new Vector2Int(x, y);
Vector2Int nextCellForPath = CheckNeighbourValid();
if (nextCellForPath == cell)
{
//Attempts to backtrack
for (int i = cellPath.Count - 1; i >= 0; i--)
{
cell = cellPath[i];
cellPath.RemoveAt(i);
nextCellForPath = CheckNeighbourValid();
if (nextCellForPath != cell) break;
}
//Couldn't find a cell to backtrack to
if (cell == nextCellForPath) return;
}
else
{
DetermineWallLocations(cell, nextCellForPath);
maze[cell.x, cell.y].BeenVisited = true;
cell = nextCellForPath;
cellPath.Add(cell);
}
CarveMazePath(cell.x, cell.y, cellPath);
}
```Is this an efficient algorithm for carving a path? Every time I test it the max size it can be before a stack overflow occurs changes, although ik this is just due to the random nature of maze generation although I just want to double check lol
yes, many game objects can impact performance. how many can only be determined through testing as it depends heavily on what resources they each require.
the stack overflow is due to the fact that you are using recursion. If you can figure out how to make it a nonrecurive loop, that should eliminate the stack overflow. I've found this is not always easy, but always doable.
yea, I would personally use a non recursive method and I actually modified this algorithm from a non recursive one I made for a prototype a long time ago, but unfortunately its part of a challenge to include recursion our teacher set us to help us understand recursion better
hmm, well you could reduce what has to go onto the stack by making that List a private member of your class, rather than passing it each time.
If only C# had tail call recursion optimization.
But if you can rewrite your code into tail recursive, then you can more easily convert it into a loop.
oh i hadn't though of that, thank you
the trees are not that high poly ..... so is there any way how to add multiple mesh tree into a terrain editor ? ....i have it like that because if player cut the tree then top tree deactivate rigidbody kynematic and it fall so just stump will left until it destroyed too
not familiar with the terrain editor, sorry.
no problem thanks anyway
I can say that on my custom terrain stuff, I use drawMeshInstanced to draw my trees.
(but that's JUST drawing stuff, does not include rigidbodies)
oh! another idea: take a look here, and rather than using int for you coordinates, pick the smallest data type that will store your maximum coordinate (e.g. ushort) https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types
Hey can someone take a look at this? I need this to happen sooner than it is happening (the update portion)
like, I need the EditorPrefs.SetBool line to be the absolute first thing that happens as soon as I click the play button
public class AutoRefreshSetting : EditorWindow
{
static AutoRefreshSetting()
{
EditorApplication.playModeStateChanged += ToggleAutoRefresh;
EditorApplication.update += Update;
}
private static void Update()
{
if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
{
EditorPrefs.SetBool("kAutoRefresh", false);
EditorUtility.RequestScriptReload();
}
}
private static void ToggleAutoRefresh(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingPlayMode)
{
EditorPrefs.SetBool("kAutoRefresh", true);
}
}
}```
anyone know how to accomplish this?
So I'm trying to automatically create new buttons for each tile object that's a buildable tile in my ConstructionUI Script. This is so my UI can be automatic and self-serving so I don't have to spend a lot of time on that. At the moment the only solution I can think of is reading the Tiles folder so it adds a new button for every Tile script.
I don't want to use enums because I'll have to change the ConstructionUI script every time I add a new tile, which can be expensive and time-consuming if I want like 100+ tiles. I'm having a hard time thinking of another solution to accomplish this, thoughts?
are all your tile scripts derived from the same class? if so, you can use reflection to find all the various types, rather than searching your code folders. This would work at runtime too.
edit (reflection, not recursion)
Yeah, but that'll be from enums right?
I'm trying to avoid that to dynamically create the buttons so I don't have to add one for each tile type manually
no, reflection lets you look at classes, their members, their inheritance, stuff like that.
that said, it's not exactly EASY stuff, but if they ARE all derived from the same class, I have a script I can DM you that will find all derived classes of a given class.
(can prolly google one too, if you prefer)
more deets on reflection: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection
you could alternatively search for all class that have a particular attribute, or implement a particular interface.
i think im just going to make the sprite name and the enum name the same so i dont have to change anything and itll be a simple foreach method on enums
sprite name for the buttons
if your willing to configure it manually... you COULD create a scriptable object class, as an asset, that stores the list of sprites you want to use- this would at least keep you from needing to adjust code when you add a new one (well, depending on your code I guess).
if you need a particular script for each sprite, then store a list of PREFABS, that have the script and sprite already configured.
scriptable object classes dont offer the functionality I need to implement sadly
the only functionality they really offer is the ability to be stored as an asset or resource. YOU have to derive a class from it, to add the functionality you want.
I am trying to add some nuget packages, and all the tools to do it automatically aren't working currently. I am trying to manual install Microsoft.CodeAnalysis but I am not sure how. It is a combination of other packages. Do I just need to install all of them manually?
Or is there another compressed file in the NuGet package that contains the other packages?
Unity doesn't support Nuget, you have to install the dll and all its dependencies manually, or use a plugin like https://github.com/GlitchEnzo/NuGetForUnity
Or look at OpenUPM and see if someone's been kind enough to set up the package there
Yeah that is why I am saying compressed. I have been opening the nuget packages and taking the .netstandard2.0 dll/xml files out. Just I can't find any in that package, and other packages are requesting it as a dependancy
It's a package that is made up of dependencies
Yeah I am trying to down load each one now.
This is making me feel like I am going crazy. I keep adding different ddls but then the entire folder of it disappears on unity restart!
OMG it is deleting them, wtf
I moved them all from the Packages folder which I think one of the malfunctioning NuGet tools was controlling, and moved them into plugins.
Well I got them downloaded, and I am just receiving this error now.
Unloading broken assembly Assets/Plugins/Microsoft.codeanalysis.csharp.4.5.0-2.final/lib/netstandard2.0/Microsoft.CodeAnalysis.CSharp.dll, this assembly can cause crashes in the runtime
Allong with
TypeCache is unable to load attribute info on class .InterpolatedStringScanner. Are you missing a reference?
And I downloaded the 4.4.0 version of that package and it seems to be working!
I'm a little stuck on this one. I'm doing a custom drag and drop thing in my game. I'm implementing IPointerDown, Up, Drag. I want to only end the drag if PointerUp happens and there's no touches/clicks going on, in case someone does one of these:
1- Touch with one finger
2- Start dragging, touch with another finger
3- Lift one finger
4- Lift the other finger
On step 3 it hits PointerUp, so on windows I check for GetMouseButton(0) || GetMouseButton(1) || GetMouseButton(2), but on android I check for Input.touchCount > 0. The problem is, it seems like touchCount isn't updated until the end of frame.
Is there an easy solution to this? Or do I need to iterate all the touches, and subtract one from my "true touch count" if they're in TouchPhase.Ended or TouchPhase.Canceled?
(I'm assuming this is why the implementation works this way - so that a "touch ending" still counts as a touch for this frame)
I'm a bit foggy on old input, but my intuition is that the interfaces such as IPointerDown are generic between clicks and touch events and lives as a response to a UnityEvent, but your use of Input in any case is aligned to the timing of the old Input system. I believe the solution is to read the eventData provided to the IPointerDown method to get the information that you need and not be reading input.
unfortunately eventdata only shows me the "current" handler - ie, in step 3 of my above, I get the details about that pointerup, but not that there's still another touch that's active
i'm trying this approach (building now) and seeing if it's reasonable..
public static int CurrentTouches
{
get
{
#if !DISABLESTEAMWORKS
return Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2) ? 1 : 0;
#else
return Input.touches.Count(x => x.phase != TouchPhase.Ended && x.phase != TouchPhase.Canceled);
#endif
}
}
(ie, just counting up all except for the touchphase.ended and canceled touches)
Can you put something together using PointerEventData.pointerId? That should reliably reference the id of the finger (0 through 9 I believe).
hm.. not sure I need that.. I want to keep the interface as clean as possible - all my platform specific code is in one file, so the consumer just has to care that PlatformManager.CurrentTouches is 0
if I'ms tarting to pass in pointerevent data.. and manage some sort of data structure in the platform manager.. hm.. maybe that's correct but i don't know that I need that much engineering
my pixel phone supports at least 10 touches but ... then i ran out of fingers to test 😛
If I'm following, your platform manager caches state in Update and then you use that result from IPointerDownHandler events, which seems like the best way to me. @misty glade
no caching - just static calls to it whenever i need touch counts.. but the important bit was that Input.touches returns 1 in the frame that I stop touching (which seems weird to me but I guess I understand that it's still a touch but it's just in TouchPhase.Ended for this frame)
Could caching between frames solve your issue? There's probably a better way than this, but I'm not familiar with it.
my actual consumption of this is like this:
public void OnPointerUp(PointerEventData eventData)
{
if (PlatformManager.CurrentTouches == 0) EndDragging();
}
Yeah, can you update CurrentTouches during Update and not just immediately reference Input?
Hm, while it works (eliminating touch phases canceled/ended) but now I've got another bug since the location of the new drag is different.. so.. I'm actually going to need to track the id of the touch and just end it when only that ID ends. Poo.
what would be the best way to debug a BoxCastAll?
iterate the results..? or are you missing results
I wasn't asking, with "iterate the results", sorry, I was saying, that's probably the best way to debug it 🙂
Your question's a little vague.. what's the problem you're having?
Im using a boxcast to detect enemies on click that are in front of the enemy. I was wondering if there was a proven way where you can draw out the box almost like a gizmo
making editing easier
The proven way would be to implement this yourself, probably in MonoBehaviour.OnDrawGizmos().
probably use Gizmos.DrawCube
I was thinking of Debug.DrawLine but that's probably easier and wont take as much time
I'll give it a shot and report later
thanks yall
Anyone know how to LIne renderer in Reverse ? or Something simliar
LineRenderer.SetPositions(LineRenderer.GetPositions.Reverse());
ohhh Thx I Try
That is 10/10.
Window/Analysis/Physics Debugger also has some visualisation tooling depending on the version, but I find it limited
Somehow i dont see that Reverse Method ...
Aahh, GetPositions takes an array and assigns it non-alloc.
lineRenderer.GetPositions(positions);
positions.Reverse();
lineRenderer.SetPositions(positions);``` Here's an update. GetPositions is non-allocative so takes an array to store the results to.
🤝 ThX Brother i Look
I didn't test the first code; this I put together in VS and ought to work better.
Ohhh the Code Work Just Fine But i guess i didnt make my self clear in the first place XD
i want to draw back my line randerer.
i just trow a rope to a point now i want to get it back.. the rope get streat after it reach the point
the above code indeed reverse the values but i want to reverse back to 0 ;-; Got any Idea Bro.
If by 0, you mean no positions to draw between, then it sounds like you should just remove the last element every X many frames or something like that until you reach zero positions.
hmmm yh that sound good.. if i just able to make some motion that will be more better soo it feel like a rope unlike a line ..
how can i accomplish this ?
how do i rotate a quaternion about the y axis, to point the object's forward direction along the z axis in the opposite direction? i tried multiplying the quaternion's x and w values by -1, and this works for when its euler y angle is -90 or 90 degrees, but when its 0 or 180 degres, the object's forward direction is the same
ie:
object's initial euler y angle is -90 degrees, multiplying object's quaternion's x and w by -1 results in object's final euler y angle is 90 degrees
object's initial euler y angle is 180 degrees, multiplying object's quaternion's x and w by -1 results in object's final euler y angle is 180 degrees, when i want it to be 0 degrees
This isn't a very complete answer, but you want to make the points along the line jiggle believably and (slightly) randomly? I would look into https://docs.unity3d.com/ScriptReference/Mathf.PerlinNoise.html for some inspiration on how you can adjust the points' position over time.
If you want to invert a quaternion along a specific axis, you can use https://docs.unity3d.com/ScriptReference/Quaternion.Inverse.html. The transform argument in this instance would be pointing perpendicular to the plane upon which you want the Quaternion reflected.
For the Y axis, this would be a normal along the XZ plane.
thx ill try it out
Can we Remove Line Randerer specific index or from start unlike ..
lr.positionCount -= 1; This will remove point from end
and i want to remove form start.
You could get all of the positions, remove the unwanted elements, then set the positions.
https://docs.unity3d.com/ScriptReference/LineRenderer.GetPositions.html
https://docs.unity3d.com/ScriptReference/LineRenderer.SetPositions.html
Removal options are: converting the array to List, removing unwanted elements then converting to array from the List or Array copy segments...
//Example of removing any number of elements
var positions = new List<Vector3>(lr.GetPositions());
positions.Remove(...);
...
lr.SetPositions(positions.ToArray());```
or ```cs
//Example of removing an element
var count = lr.positionCount - 1;
var dst = new Vector3[count];
var src = lr.GetPositions();
Array.Copy(src, 0, dst, 0, index);
Array.Copy(src, index + 1, dst, index, count - index);```
If it were me, I'd not use the `GetPositions` call from `LineRenderer` and simply keep a class List for points and adding to both the `LineRenderer` and the List, when adding points. Removing would simply require the removal of elements like above, excluding the `GetPositions` statement and assigning directly back to the `LineRenderer`.
*Alternatively*, you could shift single elements and decrease the count:```cs
//Example of removing an element
var count = lr.positionCount - 1;
for(int i = 0, j = 0; i < index && j < count; ++i, ++j)
lr.SetPoisition(i, lr.GetPosition(j));
for(int i = index, j = index + 1; j < count; ++i, ++j)
lr.SetPoisition(i, lr.GetPosition(j));
lr.positionCount -= 1;```
Although it should be noted that the docs themselves suggest assigning a completely new array rather than individually modifying elements, implying that it isn't cheap to access the internal array of `LineRenderer`
> Consider using SetPositions instead, if setting multiple positions, as it is much faster than making individual function calls for each position.
OH i see Thank YOu soo Much I didnt wanted to chnage all tho but i guess i have on choice..
do you also know how to re take your line randderer (rope) from target to initial point.
with reducing point each time i can make effect like taking back to initial point but the issue is it's too straight i want some movement in it.. Got any sugguestion ? how it can be poosible
I'm not sure what you're asking.
this is the rope i have trow to the target postion using line renderer
now i want to take back to my hand.. but with some rotation or movement like that.
Remove points from the start but also offset each point towards the person who shot the rope.
yh removing is done how can i add this offset..