#archived-code-advanced

1 messages · Page 44 of 1

undone coral
#

sucks

#

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?

obsidian glade
#

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

glacial wedge
#

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;
    }
glacial wedge
timber flame
#

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?

undone coral
undone coral
#

UniRx has lower performance impact than OnEnable / OnDisable

undone coral
glacial wedge
#

I'm reading the readme... the last update was 3 years ago?

undone coral
#

many people use it every day in many big games

#

like me

#

anyway you have now learned something amazing you will really like!

glacial wedge
#

yes, it's very interesting thanks, do you use it with odin too? the inspector integrate it without problem?

undone coral
#

what are you trying to do? you can definitely animate sprite properties

undone coral
#

it is one line

#

odin will interact with it like any other serializable type

#

what are you trying to do?

languid canyon
kindred remnant
#

v v cool, looking forward to digging into this

undone coral
#

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

kindred remnant
#

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” atwhatcost

ancient rain
#

Is unsafe c# comparable performance wise to c++? Solely just wondering

compact ingot
spark raft
#

you can just make your code faster when writting properly since you have a lot more freedom

real galleon
#

Like relative to PYPY

sly grove
#

You don't have a choice of which C# compiler/ runtime to use in Unity except for Mono vs IL2CPP

keen cloud
#

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?

sage radish
# keen cloud 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.

keen cloud
#

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

sage radish
#

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?

keen cloud
#

Yes it’s an editable text box

#

That I would like to have an undo redo function for

sage radish
#

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?

keen cloud
#

Is there another method?

#

That functions the same as the text on changed

#

Like I am adding to the stack using the onValuChanged

sage radish
#

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.

keen cloud
#

It is

#

That’s the issue

#

It is invoked either way

sage radish
#

So you have tried using onValidateInput? Because you've only mentioned onValueChanged so far.

keen cloud
#

Ahh I read that as onValueChanged apologies eyes are blurry I’m tired lol

#

What is the difference between those?

sage radish
#

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.

keen cloud
#

Mine may have multiple characters

#

If someone selects multiple and deletes it it should be able to undo that

#

This feels so odd

#

Lmao

#

This is my janky code rn

#

It just feels so disgusting lmao

sage radish
#

@keen cloud TMP_InputField has a SetTextWithoutNotify method to modify the text without invoking the value changed event.

keen cloud
#

Ooooooooooo

#

I’ll look that up

#

Thank you

languid canyon
sleek idol
#

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 😅

sage radish
# sleek idol I've a seperate process from which I want to populate / update the pixels of a t...

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.

dusty wigeon
sleek idol
sage radish
# sleek idol Thank you, that was enough extra keywords. In my case I can always assume it is ...

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?

sleek idol
#

A full update. I need to essentially pipe a directshow source into it (continuously)

sleek idol
sage radish
#

And is using DirectShow a requirement for this?

sleek idol
#

yes

sage radish
#

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.

sleek idol
#

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 🙏

glacial wedge
#

Is it possible to make a collider inside other collider to invoke OnTriggerExit when it's radius became zero?

dusty wigeon
glacial wedge
#

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

sly grove
#

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

glacial wedge
#

I know, but I tried with enable disable the collider itself but this doesn't trigger the exit correctly

sly grove
#

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)

sleek idol
# sleek idol yes

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 😅

undone coral
sleek idol
#

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

undone coral
#

what's the game?

#

like what's the idea

sleek idol
#

My own implementation of mixed reality

#

game is beat saber

undone coral
#

gotchya

#

what is the idea iwht the capture card

sleek idol
#

thats the input of the IRL camera

undone coral
#

okay but

#

what's going on with this camera? like why aren't you using a webcam

#

what is the idea

sleek idol
#

Quality

undone coral
#

okay, what quality do you need

sleek idol
#

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

undone coral
#

hmm

sage radish
#

But it's still specifically for non-vga type webcams, or would you also want to to support regular webcams?

undone coral
#

but what is the quality you need?

#

what is the idea?

sleek idol
sleek idol
undone coral
#

i'm asking what is the quality YOU need?

#

what is the idea?

sleek idol
#

Well that is what I would want to support at least

undone coral
#

the way you are expressing quality right now is telling me a lot

sleek idol
#

unless I'm misunderstanding the question

undone coral
#

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

sage radish
# undone coral what is the idea?

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.

undone coral
#

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?

sleek idol
undone coral
#

virtual one
?

sleek idol
#

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

undone coral
#

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?

sage radish
# sleek idol correct

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?

undone coral
#

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?

sleek idol
#

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

undone coral
#

okay.

sleek idol
#

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

undone coral
#

for the purposes of streaming beatsaber playthroughs live? am i misunderstanding something or doesn't this already exist?

sleek idol
#

It does exist, its called LIV, and its a stutterfest - Theres no alternatives to it, and thats why I'm here

undone coral
#

okay but

#

you know, it doesn't sound like you have any clear idea for why it is a "stutterfest"

sage radish
#
undone coral
#

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?"

mellow plinth
#

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)?

sleek idol
#

But we are kinda drifting off into offtopic here

undone coral
#

i'm saying, doy ou know WHY it is not a smooth experience?

sleek idol
#

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

sleek idol
sage radish
undone coral
#

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
sleek idol
#

Sure, but how does that help me

undone coral
#

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

sage radish
#

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.

sleek idol
#

They were reported these performance issues various times over the past year or so, they are certainly aware

undone coral
#

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

sleek idol
#

I was responding to MentallyStable.

undone coral
#

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

sleek idol
#

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

undone coral
#

i just can't see how you can possibly get anything working without the hardware you want to write it for

sleek idol
#

because the interface is exactly the same as real hardware

undone coral
#

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

mellow plinth
# sage radish I've never seen documentation for this. Are you unable to test it yourself? But ...

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... 😕

undone coral
#

anyway. you should probably only deal with capture cards that use UVC (i.e. webcam style) as the way you grab the video

#

which in my opinion is way out of scope

sleek idol
#

Yeah I was gonna say, that is not viable

undone coral
#

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

sleek idol
#

Again, dictating the target hardware is not an acceptable path for me.

undone coral
#

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

undone coral
#

what are you actually trying to do?

#

something something procedural mesh generation?

undone coral
#

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

sage radish
# mellow plinth I was trying to avoid having to test it, but ok. I will check. I must to know ab...

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

mellow plinth
# undone coral what are you actually trying to do?
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
undone coral
#

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?

mellow plinth
undone coral
#

🥺

mellow plinth
undone coral
mellow plinth
undone coral
#

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

mellow plinth
undone coral
#

to see if it matters if it is burst compiled

#

what do you mean batch raycast?

mellow plinth
undone coral
#

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

mellow plinth
undone coral
#

hmm

mellow plinth
#

I guess that raycasts may be one or two frames outdated due to the asynchronous nature of job system, not very problematic for me

undone coral
#

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 job IsCompleted
#

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

mellow plinth
undone coral
#

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

undone coral
#

every time a frame is rendered and presented to the screen, it ticks down

undone coral
#

if you need the results synchronously call .Complete()

mellow plinth
# undone coral 4 frames

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.

undone coral
#

it's that you are doing this in an Update or whatever

#

count the number of presentations (i.e. frames rendered)

mellow plinth
#

So, if I allocate at Time.framecount, it becomes invalid at Time.framecount + 4?

undone coral
#

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?

mellow plinth
#

So if (job.IsComplete || jobCreatedAtFrame + 4 <= Time.framecount) job.Complete()

undone coral
#

if you want to use temp allocated yes

mellow plinth
#

Great, thanks!

undone coral
#

is probably what you meant

mellow plinth
#

No, because that would stop immediately. It should be if the current frame is greater than jobCreatedAtFrame + 4

undone coral
#

oops yes

#

sorry my bad

#

i meant the first yes lol

mellow plinth
#

Great

mortal gust
#

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?

undone coral
mellow plinth
undone coral
#

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

mellow plinth
undone coral
#

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?

mellow plinth
#

I see, you take advantage of Update and LateUpdate loops

undone coral
#

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

mellow plinth
#

last update? Not sure what is that, is a UniTask concept?

undone coral
#

but it's not

undone coral
#

it has a lot of specific timings

mellow plinth
#

So FirstUpdate is at ExecutionOrder(int.MinValue) and LastUpdate is at ExecutionOrder(int.MaxValue)?

undone coral
#

sort of

mellow plinth
#

I see

undone coral
#

unitask injects player loops

#

in order to make the timings go brr

mellow plinth
#

Interesting

undone coral
#

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

mellow plinth
#

Ok, thanks

undone coral
#

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.

mellow plinth
#

Ok

mellow plinth
#

Question, must I put [ReadOnly] in all readonly fields in Job structs or is just for NativeArray and other Native collections?

undone coral
low junco
#

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 ?

low junco
pale silo
#

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

violet valve
violet valve
pale silo
#

thank you

pale silo
#

using plugins or anything

violet valve
violet valve
pale silo
violet valve
#

@pale silo If you use Post to send data, does the data get truncated on receipt?

#

Also, can you share your headers if any?

pale silo
#

using UnityEngine;
using UnityEngine.Networking;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Threading.Tasks;
that's all of them

violet valve
#

Nono I mean headers in the HTTP Post request itself, but based on your last answer that might not matter.

pale silo
violet valve
#

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

pale silo
#

and I only copied the assets folder... so it was strange

violet valve
pale silo
#

mhm... now i am onwindows ... also made an ios app and tried to run it on xcode on mac

#

and same thing.. crash

violet valve
#

But do you have any knowledge of if the app hits 100% CPU or just doesn't respond to system messages?

pale silo
violet valve
pale silo
#

oh nvm now i got it

midnight violet
pale silo
midnight violet
#

You know about version control and using git, right? Just back it up and open it in another version then

pale silo
#

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

karmic surge
#

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();
midnight violet
#

So have like a back forth stream and let the server decide what to do with it.

karmic surge
#

would you mind to elaborate?

midnight violet
#

So, you have three connection points, right? "Some application", a Unity application and your ML Python Application. Is that right?

karmic surge
midnight violet
#

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?

midnight violet
#

I am just here when I am, so no hurry, I will look back between work chunks 🙂

livid kraken
#

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?

midnight violet
#

cant you just use Find in this case?

violet valve
#

I think the implementation might depend on whether we're dealing with 20 items or 20,000.

midnight violet
#

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

livid kraken
#

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

midnight violet
#

Okay, good to know, so we forget about no duplicates. Did you actually check how .Find() performs ?

livid kraken
#

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

midnight violet
#

What type of array is it?

#

Not sure how this is code advanced related tbh 😄

livid kraken
midnight violet
#

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

livid kraken
#

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

violet valve
midnight violet
#

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?

violet valve
violet valve
# livid kraken 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.

livid kraken
#

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 😄

pale silo
#

@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

violet valve
frail parrot
#

trying to make some sort of dialogue system. any reason on why the subdialogue isn't showing up in the editor?

random dust
frail parrot
#

wdym? I added the serializefield cause it wasn't working anyway and I thought it might help

random dust
#

I mean you try renaming it to Serializable and try again

frail parrot
#

serializable doesn't exist, and system.serializable can't be placed inside of a class

random dust
#

🤷

#

Maybe change it to a property, and try again

frail parrot
#

it's ugly but it works

frail parrot
#

better solution

potent shoal
#

How can I get the sprite from a tileBase?

hazy epoch
#

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.

potent shoal
#

@sly groveThank you.

midnight violet
hazy epoch
# midnight violet 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.

midnight violet
hazy epoch
#

Yep.

hazy epoch
# midnight violet Can you show your code so we can understand, what you are trying to do?
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;
}
midnight violet
hazy epoch
#

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.

midnight violet
#

How about not passing a finite position abut the transform?

#

So you always get up to date values of the target

sly grove
#

Erm

#

I mean

#

UI Instead of Grid

hazy epoch
hazy epoch
sly grove
midnight violet
hazy epoch
hazy epoch
midnight violet
#

So why do you not use anchoredPosition?

sly grove
#

And why not just put your tiles into a GridLayoutGroup

hazy epoch
hazy epoch
midnight violet
#

of what element, the spawned one or the target?

hazy epoch
#

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).

midnight violet
#

And they change when you instantiate a gem?

hazy epoch
#

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.

midnight violet
#

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?

hazy epoch
#

Yes.

sly grove
midnight violet
#

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?

sly grove
#

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?

hazy epoch
# midnight violet And your target existing UI element does change when instantiating? Or do you ju...

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().

karmic surge
midnight violet
obsidian glade
karmic surge
hazy epoch
karmic surge
# karmic surge yes,

if it helps,
the python program, can be an instance that was run by unity, I have complete control over it

hazy epoch
#

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).

obsidian glade
#

you're relying on the auto formatting of the layout group code to position itself?

midnight violet
#

Camera feed to python

hazy epoch
obsidian glade
#

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

sly grove
#

That's not an answer

#

To the question about why you built it out of UI

hazy epoch
#

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.

sly grove
#

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

hazy epoch
#

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.

midnight violet
#

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.

hazy epoch
midnight violet
#

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

hazy epoch
# midnight violet Its the issue. Unity has its order of execution, and if you base on start and aw...

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?

midnight violet
#

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

hazy epoch
# midnight violet I am confused, because screen resolution should not change after initialised onc...

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.

hazy epoch
midnight violet
hazy epoch
#

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.

midnight violet
hazy epoch
#

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.

midnight violet
#

But in ONE FRAME...

hazy epoch
#

NO... ALL Start methods don't not ALWAYS finish in ONE FRAME. That's what I'm saying.

midnight violet
#

You get it now? its called before anything is calculated your script already tries to access

obsidian glade
hazy epoch
midnight violet
#

... I give up

obsidian glade
#

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

midnight violet
#

If you want to badly hook into the fact, that the UI is the issue

midnight violet
obsidian glade
#

I posted it above - my guess is a misunderstanding in how the UI components are designed to be used

midnight violet
#

Ah, missed that, my bad

obsidian glade
#

though I haven't looked at the code in detail

midnight violet
#

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

obsidian glade
#

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

undone coral
#

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

undone coral
karmic surge
karmic surge
frail parrot
undone coral
#

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

lusty basalt
#

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

karmic surge
# undone coral hmm

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)

undone coral
#

like what's the idea?

#

it is possible

#

but in order to help you, i need to know what the idea is

karmic surge
undone coral
#

what is the application?

karmic surge
#

I thought this is what you suggested

undone coral
#

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?

karmic surge
# undone coral 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)

karmic surge
undone coral
#

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

karmic surge
# undone coral like what are you trying to do

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

undone coral
#

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

karmic surge
# undone coral a security camera feed? and why is it in unity? to recreate a 3d environment?

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)

karmic surge
# undone coral there isn't anything sensitive about what it does

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)

undone coral
#

i get it. i don't think it's really surveillance. it's like people counting right?

undone coral
karmic surge
undone coral
#

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

karmic surge
undone coral
#

reading an RTSP stream or whatever is going to be hard.

undone coral
karmic surge
undone coral
#

yeah

undone coral
#

uh oh

karmic surge
#

and I was assigned to it last week, so I barely got introduced to the topic 😦

undone coral
#

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

karmic surge
undone coral
#

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

#

@karmic surge hope this helps. don't have a heart attack

#

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

karmic surge
undone coral
#

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

karmic surge
tired creek
#

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?

west plaza
#

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

fresh salmon
sly grove
#

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

west plaza
#

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"

keen gyro
#

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

gleaming night
#

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

fresh salmon
west plaza
#

And there the Authorization code grant flow

fresh salmon
#

Okay, so now I get why you need a unique token to link Unity with your server

west plaza
#

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

fresh salmon
#

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

west plaza
#

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

fresh salmon
#

Oh, I was on the implicit flow section my bad

west plaza
#

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

fresh salmon
#

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)

west plaza
#

You mean a full authentification service with password and username?

fresh salmon
#

Yes

west plaza
#

Yea, thats maybe the best way

fresh salmon
#

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

west plaza
#

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)

fresh salmon
#

Yes

west plaza
#

Ok great

#

Thanks! 😭

#
    • 🙂
west plaza
#

@fresh salmon I Just found this:
I will try this way tomorrow

#

They start a local webserver for teh auth-process

fresh salmon
#

Yep that's another option

west plaza
#

Jup, with this the user has no need to create an account

fresh salmon
#

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

west plaza
#

Yea, true 🙂

swift quail
#

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.

west plaza
#

@fresh salmon Thanks! Have a nice day

swift quail
#

bro. noone can help me. fr?

fresh salmon
# swift quail 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

swift quail
#

yeah bro i know. i have typed my stupid problem like 3 times now.

fresh salmon
#

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

swift quail
#

i give up. just, nvm

humble leaf
#

@swift quail Stop crossposting. It's not anyone's job here to answer your question. Stay in one channel and be patient.

velvet rock
#

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?

obsidian glade
untold moth
#

Wouldn't it just be treated like a base type? Meaning that if there are any overrides, they will still be used.🤔

abstract folio
#

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?

sly grove
#

There's not a lot of good reasons for casting to object, what's the purpose of this?

sly grove
abstract folio
sly grove
#

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

untold moth
wanton thistle
#

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

visual depot
#

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 ❤️

velvet rock
#

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.

finite swan
#

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

midnight violet
finite swan
#

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

midnight violet
finite swan
#

what?

midnight violet
# finite swan 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.

finite swan
#

no, unity makes a new blank scene to put everything the test generates into

midnight violet
#

Okay, understand that. Just trying to understand, what selection you are doing that does not get reverted. But maybe I am just stumped 😄

finite swan
#

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

midnight violet
#

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

finite swan
#

Without the selection code it works fine

midnight violet
finite swan
#

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

midnight violet
#

Okay, lets elaborate then your new question. What exactly do you want to do? Just to start from scratch here 😄

finite swan
#

for the selection to return to what it was after a test

midnight violet
#

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?

finite swan
#

the selection always exists; as you can see in the video it never actually unloads sample scene

midnight violet
stuck onyx
#

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)

random dust
#

Because then you might aswell just return (T)obj 😄

#

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

stuck onyx
#

hmmmm, what if i store instead of an enm the type itsellf

#

1 sec

random dust
#

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.

random dust
#

What I would like to know is how you end up with an object type in the first place

stuck onyx
#

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

random dust
#

And since you seem to know the type you want judging by the generic method, you can just explicitly cast it back.

stuck onyx
#

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

midnight violet
#

You either have to use string comparison or do your enum as you do right now if you want to use switch

stuck onyx
#

yeah but you get the point, i would have to check 1 by 1 the type i stored and cast in accordance, correct?

midnight violet
#

Yeah, you want to store probably everything somehow. I get that point

stuck onyx
#

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)

random dust
#

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?

stuck onyx
#

uhhhh.... i didnt think of that

#

😅

random dust
#

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()

midnight violet
random dust
midnight violet
#

Ohh, you blocked me, got it 😄

random dust
# stuck onyx uhhhh.... i didnt think of that

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

random dust
stuck onyx
#
 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

midnight violet
midnight vale
#

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! 🙂

flint sage
#

Editor application. Playmode state changed

#

Then just invoke and wait until your batch file finishes

midnight vale
#

Thank you! I'll look into that 🙂

final dirge
#

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?

untold moth
final dirge
#

So what's important is setting the target to .Net Standard 2.1 and it should be good?

#

(In unity)

untold moth
final dirge
#

Ok so it seems .Net 7 is supported from microsoft docs! Thanks for the info it makes more sense now!

jolly token
#

.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.

final dirge
#

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

undone coral
#

do what you need to do

#

@jolly token is giving you the correct advice

final dirge
#

Yeah just wanted to know if there was specific things that were not compatible

undone coral
undone coral
final dirge
#

So what does generally means? Is it like part of the features might not be supported?

undone coral
#

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

final dirge
#

So I need to make a class library targeting .net Standard 2.1?

#

Instead of .Net 7?

undone coral
undone coral
scenic forge
#

Pattern matching is supported.

undone coral
#

even then, unity's .net standard 2.1 implementation is incomplete

final dirge
#

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?

undone coral
#

@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

jolly token
final dirge
#

Makes so much sense now thank you 🙂

modest vale
#

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

sly grove
modest vale
#

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

sly grove
#

It's simple. You create them with Matrix4x4.TRS(translation, rotation, scale)

#

Then you can multiply them together or use things like MultiplyPoint etc

modest vale
#

sounds really easy when you say it like that, and what are quaternions?

dusty wigeon
modest vale
#

so quaterion is just a more accruate way to store rotation

dusty wigeon
#

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.

modest vale
#

I think I'ma stick to matrices for now, but thanks

sly grove
dreamy ember
#

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?

sly grove
dreamy ember
# sly grove The NavMeshes don't need to be baked in the editor but they do need to be baked ...

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?

GitHub

High Level API Components for Runtime NavMesh Building - NavMeshComponents/NavMeshSurface.md at master · Unity-Technologies/NavMeshComponents

sly grove
#

I don't have a lot of experience with it

velvet rock
# final dirge And just so I understand it well, .Net Standard is just an old version of .Net r...

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

dreamy ember
#

Now if only I could get it working for my needs hidethepain

sly grove
#

the way the engine/editor classes are mixed

dreamy ember
#

Yeah that is pretty jank 😂

final dirge
#

Hopefully we get full support for .Net 6+ soon haha

floral finch
#

is this possible? btw sorry for bad art and typo in name

sly grove
knotty kite
#

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

thin mesa
#

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

thorn flintBOT
#
💡 IDE Configuration

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.

knotty kite
#

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

knotty kite
#

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

dapper cave
# knotty kite

whenever i get weird shit, it's misconfigured assembly definition.

undone coral
#

you shoudl be able to reason about this code

#

and find it pretty quickly

foggy dew
#

hey, what is the startTangent and endTangent and how to calculate them?

#

im watching a tutorial but they didnt say why calculate like this

warped kettle
#

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

modest vale
blazing verge
#

Does anyone know any solutions for UI toolkit with MVVM / databinding?

foggy dew
#

why this is working

#

i have one scene in build settings but its still working

autumn locust
#

how difficult is it to rename my project?
am getting tired of "new unity project"...

sly grove
#

Lastly you'll have to tell Unity Hub about the "new project"

autumn locust
#

all right, seems to work. had some errors about my main.dll but that vanished after reimporting a couple times and doing random things

spark raft
foggy dew
#

it debugges 1 btw but still loads 0. scene

abstract folio
#

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?

misty glade
#

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

abstract folio
#

"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?

misty glade
#

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?

abstract folio
# misty glade 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");
    }
misty glade
#

you don't have to type code ha

abstract folio
#

^ lol

misty glade
#

you just type the cs and ticks on the same line

abstract folio
#

(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)

misty glade
#

sorry was afk

abstract folio
#

I just keep typing.. lol

misty glade
#

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

abstract folio
#

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...

misty glade
#

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

abstract folio
#

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?...

misty glade
#

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

abstract folio
#

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!

novel plinth
abstract folio
#

string+=string?

novel plinth
#

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...

abstract folio
velvet rock
#

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.

livid kraken
velvet rock
# livid kraken I dont think you need a roslyn analyzer and if statements. Our debug library is ...

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.

tough tulip
floral finch
#

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

pine tulip
#

can some one pls helpp me i have some errors in a binary code save system i am making for my idle game

flat talon
#

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 !

warm forge
cyan aspen
#

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?

rose harness
#
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
abstract folio
abstract folio
rose harness
#

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

abstract folio
#

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.

scenic forge
#

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.

rose harness
cyan aspen
abstract folio
cyan aspen
#

no problem thanks anyway

abstract folio
#

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)

abstract folio
upper mica
#

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?
native nebula
#

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?

abstract folio
#

edit (reflection, not recursion)

native nebula
#

I'm trying to avoid that to dynamically create the buttons so I don't have to add one for each tile type manually

abstract folio
#

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)

#

you could alternatively search for all class that have a particular attribute, or implement a particular interface.

native nebula
#

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

abstract folio
#

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.

native nebula
#

scriptable object classes dont offer the functionality I need to implement sadly

abstract folio
velvet rock
#

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?

austere jewel
#

Or look at OpenUPM and see if someone's been kind enough to set up the package there

velvet rock
austere jewel
#

It's a package that is made up of dependencies

velvet rock
#

Yeah I am trying to down load each one now.

velvet rock
#

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.

velvet rock
#

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!

misty glade
#

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)

violet valve
# misty glade I'm a little stuck on this one. I'm doing a custom drag and drop thing in my gam...

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.

misty glade
#

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)

violet valve
misty glade
#

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 😛

violet valve
#

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

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)

violet valve
misty glade
#

my actual consumption of this is like this:

        public void OnPointerUp(PointerEventData eventData)
        {
            if (PlatformManager.CurrentTouches == 0) EndDragging();
        }
violet valve
misty glade
#

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.

keen gyro
#

what would be the best way to debug a BoxCastAll?

misty glade
#

iterate the results..? or are you missing results

keen gyro
#

Iterate

#

I'm beyond stumped

misty glade
#

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?

keen gyro
#

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

violet valve
misty glade
#

probably use Gizmos.DrawCube

keen gyro
#

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

rare mortar
#

Anyone know how to LIne renderer in Reverse ? or Something simliar

violet valve
violet valve
austere jewel
#

Window/Analysis/Physics Debugger also has some visualisation tooling depending on the version, but I find it limited

rare mortar
violet valve
violet valve
violet valve
violet valve
rare mortar
violet valve
rare mortar
raw arrow
#

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

violet valve
violet valve
#

For the Y axis, this would be a normal along the XZ plane.

rare mortar
#

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.

orchid marsh
# rare mortar Can we Remove Line Randerer specific index or from start unlike .. ` lr.position...

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.
rare mortar
orchid marsh
rare mortar
#

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.

orchid marsh
#

Remove points from the start but also offset each point towards the person who shot the rope.

rare mortar
#

yh removing is done how can i add this offset..