#archived-code-advanced

1 messages ยท Page 203 of 1

hallow cove
#

I am getting all the types and their respective icons

#

I couldn't do much except a try catch, which was somewhat slower

#

also I am not a he

novel plinth
#

checking a type with magic strings were never a good thing.. just saying

hallow cove
#

I know

#

but it works

#

and there's not much of a fix to my knowledge really

#

reflections are the bane of my existence
why does this return an Ambiguous Match Found exception:
if (userData.methodInfo.IsStatic)

#

I think I asked and will probably still ask a million questions regarding them, because even though the C# documentation says something, unity will not respect it

austere jewel
#

are you sure it's not getting the method that returns the exception?

#

I don't see what could be ambiguous about any of the above

#

though I'm not sure as to the context

hallow cove
#

it's the method Debug.Log

#

which is static

austere jewel
#

show the stack trace

novel plinth
#

proly just missed the declaringtype flag

hallow cove
#

nevermind it seems it has fixed itself

novel plinth
#

IF it still not fixed, you can test it like this

        var someT = "".GetType();
        var methods = someT.GetMethods();
        if (methods .Length != 0)
        {
            for (int i = 0; i < methods.Length; i++)
            {
                if (methods [i].DeclaringType == someT && !methods [i].IsSpecialName)
                {
                    StringBuilder sb = new StringBuilder();
                    if (methods [i].IsStatic) { sb.Append("static "); }
                    if (methods [i].IsPublic) { sb.Append("public "); }
                    if (methods [i].IsFamily) { sb.Append("protected "); }
                    if (methods [i].IsAssembly) { sb.Append("internal "); }
                    if (methods [i].IsPrivate) { sb.Append("private "); }
                    Debug.Log(sb);
                }
            }
        }
hallow cove
#

yeah but the issue was literally methods[i].isStatic returning an exception

#

the bool itself was the problem

#

but it seems to have fixed itself now

#

reflections sometimes-

#

do that-

austere jewel
#

It really doesn't lol

hallow cove
#

for instance, just now another script which worked perfectly is giving me that exact error

#

yet it still works

#

anyways, thanks lots for the help

#

I ask way too many questions here, but what can you do when the code isn't doing what the documentation says it's supposed to do ๐Ÿ’€

vestal condor
#

is there no way to draw lines on canvas in a way like linerenderer?

#

pass in a bunch of vertices and let it draw

#

or do I really have to use GL for this

austere jewel
#

Image has a OnPopulateMesh function you can use to construct your own mesh using the VertexHelper object is passes in, and you can do whatever you want

#

It's quite low level though so it's not great to work with.

#

In the future you can use UIToolkit, where they have a fantastic mesh drawing API

drifting galleon
#

using a mesh for it is ok, but i highly recommend using a shader to draw a line with signed distance fields. i've just recently wrote such an exact shader

brave talon
#

Can someone help me make a toon shader in URP shadergraph?

drifting galleon
# hallow cove anyways, thanks lots for the help

if you could post the code in whole, i'd be happy to look over it and refine it, because as i understand right now, there's just lots in there that shouldn't need to be.
only if you want of course

hallow cove
#

It's actually pretty clean

#

I have special classes to serialize Method, Field and Property Infos

#

Some methods to create nodes based on if you select a class, method etc.

#

The architecture is clean, but the code not so much actually

#

I'll post it once I finish the system and refine it myself for some last moment tweaks before slapping a "Finished" seal on it

grave bear
#

trying to use mono.cecil to generate code. Im using the ILPostProcessor and it will sometime crash right after compile. Any tips?

#

personally wish it would crash every time... that way I would know it's "fixed" when it stops crashing

drifting galleon
#

that could have many different sources of problem. maybe dump the generated code to a file so you can inspect it yourself.
not sure if you know that already, but you can now also use .net native source generators to generate code and that is in most cases a better solution than cecil

violet wolf
#

I'd say they would be the first place to check

#

Hopefully it is a unity problem and not some obscure cecil issue

grave bear
grave bear
grave bear
sage radish
grave bear
drifting galleon
grave bear
#

Granted you have to jump through a few hoops, but that's the gist

drifting galleon
grave bear
drifting galleon
grave bear
#

Which I think is really helpful

drifting galleon
#

and it's normal readable c# code

grave bear
#

Yes! that too

#

making errors less, and ease-of-use 1000x easier

drifting galleon
#

also, it undergoes syntax parsing and therefore makes it relatively error resilliant unlike cecil

grave bear
#

very nice. One question I have tho, is the Generate attribute required? Im not 100% sure how execution is handled. Im hoping I can just cut out all my cecil from my current ILPostProcessorWeaver class and replace it with .net

drifting galleon
#

first, what unity version are you working with?

grave bear
#

2021.3.6f1

#

LTS

drifting galleon
#

ok, so unfortunately, you cannot yet use IncrementalGenerators which would be the recommended ones, because 2021 doesn't have a compatible roslyn version. so you have to use the SourceGenerators v1.
but that's not a huge issue. migration to incremental generators later on is easy.
and to answer your question: source generators can take input from anywhere or none at all.
you can simply output some generated code always, have it only generate code when it encounters specific syntax nodes (e.g. attributes), or take any other arbitrary file as input (e.g. text file) and generate code based on that

grave bear
drifting galleon
#

i've not tested myself, but from the forum i've read that 2022 has an updated roslyn version again and people said that therefore incremental generators should be working

grave bear
#

good news! I have 2022.2b1 installed so I'll give it a test run. But for now, ill do like you said using SourceGenerators v1, if I can find it

drifting galleon
grave bear
drifting galleon
sage radish
# drifting galleon i'm not sure if unity already doesn't use cecil *at all*, but i know that a lot ...

Unity.Entities is still using IL Post Processing according to this
https://github.com/needle-mirror/com.unity.entities/tree/master/Unity.Entities.CodeGen

GitHub

[Mirrored from UPM, not affiliated with Unity Technologies.] ๐Ÿ“ฆ The Entities package provides a modern Entity Component System (ECS) implementation with a basic set of systems and components made fo...

#

Not everything that can be done with IL processing can be done with source generators. You can't modify existing source code with generators.

drifting galleon
#

and actually, you could do it with source generators

#

or rather the roslyn api

sage radish
#

Of course you shouldn't be modifying the user's source code. But IL processing doesn't do that.

grave bear
drifting galleon
sage radish
drifting galleon
#

it's not so much replacement as it is addition

subtle shell
#

Hello guys !
OnPreCull is not running in URP ( i think its because of the URP )

grave bear
drifting galleon
sage radish
subtle shell
#

i really need this event

drifting galleon
subtle shell
#

can i use the same code ?

drifting galleon
#

look at the docs

drifting galleon
subtle shell
#

oof

drifting galleon
#

they work fundamentally different

drifting galleon
#

and microsoft thought so too

#

or like, not 'bad' but rather a last resort

subtle shell
grave bear
drifting galleon
#

just a sec. i'll check which version my project uses

grave bear
#

im hoping I can use something newer, because 6+ years is a loooong time in terms of updates/features

drifting galleon
#
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.2" PrivateAssets="all" />
#

these work

grave bear
#

awesome thank you

drifting galleon
subtle shell
# drifting galleon ``` <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version...

cant i just use this ? :

using UnityEngine;
using UnityEngine.Rendering;

public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
    }

    void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
    {
        // Put the code that you want to execute before the camera renders here
        // If you are using URP or HDRP, Unity calls this method automatically
        // If you are writing a custom SRP, you must call RenderPipeline.BeginCameraRendering
    }

    void OnDestroy()
    {
        RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
    }
}

and do the same thing ?

drifting galleon
#

no

subtle shell
#

why ? ๐Ÿ˜ฆ

drifting galleon
#

because they work FUNDAMENTALLY different

subtle shell
#

in the docs it said they have similar functionality

grave bear
drifting galleon
drifting galleon
grave bear
#

yeah haha

grave bear
#

Thats for the inc generator

#

now to see which ver of unity 2021/22 supports...

drifting galleon
#

you should also read this: https://stevetalkscode.co.uk/debug-source-generators-with-vs2019-1610
to be able to debug your source generators efficiently. (because you can look at any docs or anywhere on the internet and there's not a single thing written about what debug possibilities there are. [because at first there weren't any and i guess they didn't bother to update the docs when they improved on that])

#

@grave bear

grave bear
vivid night
#

Hello, I am having a bit of trouble with Sin and Cos not outputting correctly. So I have code where an object goes towards its parent and switches its state to its Idle state, where it is to then orbit around it parent, but when it enters Idle, it jumps a bit to a new position. So when I checked it out, using the calculated angle of 180, I found that both the Sin/Cos of 180 equal a decimal, which is not what my calculator says.

angle = Vector3.Angle(animator.transform.parent.position, animator.transform.position);
        Debug.Log("Initial angle: " + angle);
        Debug.Log("Sin " + Mathf.Sin(angle));
        Debug.Log("Cos " + Mathf.Cos(angle)); //angle = 180

Results:

Initial angle: 180
Sin -0.8011526
Cos -0.5984601

Ideally, my goal is to make it so my object would start orbiting from where it is in relation to its parent rather than having to jump like it does.

drifting galleon
#

i think

valid token
#

I want to download a plugin in code from a URL, unfortunately it creates the jar incorrectly and is only recognized as a ZIP by the compiler. I download the jar with Commons IO

FileUtils.copyURLToFile(new URL(fromUrl), new File(localFileName),10000, 10000); 

Does anyone have an idea how I could integrate the plugin.yml, or what I could change from scratch?

drifting galleon
vivid night
grave bear
#

@drifting galleon Last question (hopefully) is regarding the creation of the the actual code. Can it overwrite dlls/modify existing code? from the looks of it you can only generate new code and not overwrite existing code.

austere jewel
acoustic tinsel
#

sorry

drifting galleon
grave bear
drifting galleon
grave bear
sage radish
#

Source generators don't solve the same problems as IL processing. They have different uses.

grave bear
#

likely harder because now I have to make an extension class that calls the relevant code collected from reflection

drifting galleon
grave bear
drifting galleon
grave bear
drifting galleon
grave bear
rugged radish
#

hello guys
have anyone tried scheduling a unity job from inside an async task ? Is that allowed ?

drifting galleon
#

Probably

rugged radish
#

while (!job.IsCompleted) await Task.Delay(delayMs);

if delay is very small it throws an exception when I try to read from the job result after that line
but otherwise It looks like it's working fine

what am I missing here ?

#

the job is quite fast. other, slower jobs have the same check and don't have any issues

drifting galleon
rugged radish
#

and I can see that it produces the mesh just fine

#

I thought that Complete() forces the controlling thread to wait on the job

drifting galleon
rugged radish
#

I'm getting all the results from all the jobs, and I don't use Complete() on either of them
I mean, I'll double check again, but seems like Schedule is enough to start a job, pretty sure it says the same in the docs

drifting galleon
rugged radish
#

I can tell it's working just by how the game runs now
moved the mesh-gen routines into the job system to avoid framerate drops on chunk transitions
and those transitions are finally silky smooth

rugged radish
agile yoke
#

Complete is not necessary for a job to run, but it is necessary to e.g. be able to access native collections you passed to the job again without the safety system complaining

drifting galleon
drifting galleon
agile yoke
#

Well, I don't know how you came to that conclusion, but it's easy to show that it's not true ^^'

drifting galleon
agile yoke
#
public class JobScheduleTest : MonoBehaviour {
  [ContextMenu("Schedule")]
  public void Schedule() {
    new Job().Schedule();
  }

  private struct Job : IJob {
    public void Execute() {
      Debug.Log("The job ran!");
    }
  }
}

I can throw this on an empty object in an otherwise empty scene, run schedule, and the log will print after a moment.

#

It's entirely possible that there's no guarantee that a job will run absent any Complete or ScheduleBatchedJobs calls, but it's definitely not true that they never will.

drifting galleon
agile yoke
#

works too

drifting galleon
#

I can't check it currently but then they have reworked the job system because this is definitely how it used to work

agile yoke
#

Nevertheless, the pattern to use jobs is:

  • Schedule them as early as possible, and either
  • Complete them when you need their result; or
  • call ScheduleBatchedJobs if you never really need access to their result and just want to make sure they execute.
rugged radish
#

from what I'm seeing in the docs and in my code Complete() ensures that you can safely access the results
but you don't need it for job to start running
and you can even get the results if you're lucky (which seems to have correlation with the frequency of your polling)

that being said, seems like Complete() is the correct method to wait for the result, I'll try using that instead of a while(!IsCompeted) and see it causes main thread to freeze

drifting galleon
agile yoke
#

agreed, Complete is preferable I think

austere jewel
#

Unity's subsystems will call JobHandle.ScheduleBatchedJobs on their own in the background so the above test is not a good measure of whether jobs will start without it

drifting galleon
#

Interesting. That must be a new addition of a recent version then

agile yoke
#

I guess that depends on what you mean "without it". "Unity does the equivalent at appropriate times automatically in a normal project" still means "your job will run without you calling it"

austere jewel
#

I think the SheduleBatchedJobs docs is pretty clear about it being the thing that actually kicks it off:

By default jobs are only put on a local queue when using Job Schedule functions, this actually makes them available to the worker threads to execute them.

The job system intentionally delays job execution until you call ScheduleBatchedJobs manually because the cost of actually waking up worker threads can be expensive. Thus a good default is to delay the actual kick until a few jobs have been scheduled. Generally if you are scheduling a bunch of jobs in a loop, wait with kicking the jobs until the end of the loop. If you do significant amounts of work on the main thread between scheduling jobs, then it can make sense to ScheduleBatchedJobs between each job.

drifting galleon
#

And when does the subsystem call SBJ?

austere jewel
#

No idea, there are many packages and other shit that use jobs

#

Any one of them in a project could do it at whatever point they run

rugged radish
#

so, Complete() does freeze the main thread
but

jobHandle.Complete()```
doesn't, and also doesn't cause the safety exception
drifting galleon
#

So yeah, the jobs won't run. They may run if you use other packages.

rugged radish
#

yeah, I'll put the ScheduleBatchedJobs at the end of the loop

agile yoke
#

huh, those docs are surprisingly clear/specific, especially around "you" being supposed to call it at appropriate times. The "C# Job System" docs make it sound a lot more like "call it if you really need to, be careful with it performance-wise, Complete is better"... but that advice really only makes sense if you're going to need the job results immediately, not e.g. next frame, if there are no implicit schedule calls :/

rugged radish
#

thanks for the clearing things out guys, really great help โค๏ธ

drifting galleon
#

It just doesn't work over multiple frames

agile yoke
#

Only when relying on an implicit SBJ call somewhere. If I schedule a job and complete it next frame, I want it to actually run in the background while the main thread is progressing through the frame (assuming worker thread availability), not only start when I call Complete next frame.

#

So I definitely would've expected Unity to insert some amount of automatic SBJ at appropriate times, even if it's just at frame boundaries.

drifting galleon
austere jewel
#

I have jobs which run until they are done, and then I call Complete to get the data

#

Just use SBJ as appropriate, sometimes the earlier you start the jobs the better for your setup

drifting galleon
drifting galleon
agile yoke
agile yoke
drifting galleon
#

And presentations too iirc

undone coral
#

they are really complicated

#

i wish someone would just take the language and interface of Tasks

drifting galleon
#

they aren't. you just need to get into them

undone coral
#

and just... rename this stuff

#

yeah i mean you're right they're not complicated

#

maybe the word i'm looking for is arcane

drifting galleon
#

not even that

undone coral
#

hmm

#

well help me out

drifting galleon
#

what do you need help with

undone coral
#

nevermind no i don't have an urgent issue wiht jobs at the moment

#

i haven't really gotten into it yet. i use a native plugin that unity communicates with via a plugin rendering event from the render event. i have an obstacle where that causes the render thread to wait until the native method returns, which is expected but undesired - it has no side effects on rendering

#

and i've been exploring if it is possibly to wrap that somehow in a job, so that i can communicate to the render thread that there are no dependencies on the result

#

i don't think i need it to actually run in the background

#

it is work done to the render texture a camera is rendering to. an expert recommended that i get the unity source and work with the finished frame buffer directly, or potentially using a custom pass

daring pelican
#

Some weird issue... So my code recompilation in the editor either takes 1 second or 90 seconds, seems very random. That's in a clean project. Anyone had anything like that? It just started happenning out of the blue

left mauve
#

Does it reimport stuff, when it takes 90 secs?

white seal
#

Does anyone know if code inside a #UNITY_EDITOR preprocessor directive will run when unity is in --batchmode

#

sorry to be more specific

#

also with the nographics flag

sly grove
#

or batch mode player?

#

( i don't remember if the latter even exists)

undone coral
#

in the editor?

#

yes

#

batchmode does two things - honestly i don't know why they haven't written this

#

it turns off the render loop, and a side effect of that is the render loop has a dependency on the platform's presentation approach, which on windows is... a window, and it will not create that window

#

that's it

white seal
#

Interesting I thought that was what the -nographics flag was for

undone coral
#

there is a player loop subsystem called RenderLoop or WillPresentFrame or whatever

#

-nographics initializes a graphics device called a "NullDevice"

#

that's it, that's all it does

white seal
#

ah got yeah

undone coral
#

the net effect is that command buffers, i.e. requests to render, will be no-ops

white seal
#

sweet

#

thanks so much

undone coral
#

they should document this stuff!!

white seal
#

Having a strange issue where an asset is causing issues with my unit tests due to a welcome window appearing on first startup

white seal
#

yup

undone coral
#

batchmode does NOT prevent that

#

you will see in various unity code

#

checking if it's in batchmode

white seal
#

looks like lol

undone coral
#

Find Usages on batchmode

white seal
#

yup took the words right out of my mouth

undone coral
#

input system for example suppresses exactly such a window

#

onyl if it's in batchmode

white seal
#

Application.isBatchMode looks like this is what i'm looking for

undone coral
#

that's what you'll use to patch the pckage yes

white seal
#

sweet

#

thanks so much for the help

#

really appreciate it!

undone coral
#

i tweaked my answer to be more accurate @white seal

#

is there a pre-existing method that copies PointerEventData ?

#

why is pointer event data so ill thought out ๐Ÿ˜ฆ

#

why couldn'/t they just copy the DOM model verbatim

#

why did they copy the DOM model like they were a non english speaking external contractor team under a punishing and illogical deadline that knew it was not going to get hired to do anything else again but was in denial?

left mauve
#

I hope its okay to ask this here: We are having problems with the Quest2 (not in Editor) that we suddenly get what seems to be random crashes on mutliple devices...
From the tombstone i get:
backtrace: /apex/com.android.runtime/lib64/bionic/libc.so (je_malloc_tsd_boot0+496)
Is the Unity Version 2022.1.9f1 still so buggy that we have to go back to 2020? We have upgraded because of the XR Interactions and URP stuff.
Does someone else have problems with the 2022 versions?

undone coral
#

you should use whatever version facebook tells you to use

#

to best develop for the quest

left mauve
#

Well we are not sure if it is us or the engine ๐Ÿ˜„

undone coral
left mauve
#

Okay i will check what facebook thinks is good.

undone coral
#

you should use 2020.3.18f1

#

@left mauve that is the version facebook uses internally

#

i think the latest i see is 2020.3.22f1

left mauve
#

And i cannot report a bug anyway as the application is rather big and we are surely not sharing any of that with Unity. Apart from the fact i am also not their QA-Guy.

#

okay, thanks for the Info

hot sand
#

whenevr i try to make an avatar for vrchat it says "FileNotFoundException: C:/Users/COHAD~1/AppData/Local/Temp/DefaultCompany/My projectihih/prefab-id-v1_avtr_30f61086-4bdb-4dfa-b77e-cf1d4801c7d3_1548093427.prefab.unity3d does not exist
System.IO.File.Copy (System.String sourceFileName, System.String destFileName, System.Boolean overwrite) (at <eae584ce26bc40229c1b1aa476bfa589>:0)
VRC.SDK3.Builder.VRCAvatarBuilder.ExportCurrentAvatarResource" does anyone know how to fix it?

left mauve
#

Well, first thing is - does the file really exist?

#

(path and file in this case)

#

I see my stuff normally in the AppData/LocalLow Folders

daring pelican
left mauve
#

That does sound a bit strange... i never experienced that. When i had long times like that it was doing something with the MipMaps... but that was also only like 1 in 50 times that it took very long.

hot sand
wintry wind
#

Hi everyone, Iโ€™m building a spaceship game, where the camera is in the cockpit. I want the camera to move with the movement of the ships (example: lean back when accelerating). Anyone knows how to do this? Iโ€™ve googled this hard but canโ€™t find anything (wrong term maybe)

regal olive
#

using lerp

#

for smoothnes

fast pagoda
#

have your camera inside a parent, you move your parent for obvious stuff (like mouse movement or stuff) and move the camera itself for small "animations" like headbob and what you said
for acceleration i would also use camerafov animation for more immersive effect

wintry wind
#

I tried using some lerps and move the head on acceleration but it wasnโ€™t very natural

regal olive
#

Do what VisionElf recommended then, sounds like it will work

inland delta
#

i would use a remap function based on the spaceship velocity given 0f and its maximum velocity and lean back based on that

#

but idk how it would feel

#
public static class Helpers
{
    public static float Map(float value, float inputStart, float inputStop, float outputStart, float outputStop)
    {
        return outputStart + (outputStop - outputStart) * ((value - inputStart) / (inputStop - inputStart));
    }
}

then something like

float leanAmount;

void Update()
{
  leanAmount = Map(rigidbody.velocity.magnitude, 0f, spaceShipMaxVelocity, 0f, 1f);

  // do the lean
}
wintry wind
#

Thanks, will try these tips

wanton bronze
#

Is IL2CPP a good option for โ€œrewritingโ€ C code into Unity

sly grove
wanton bronze
#

What does it do

sly grove
#

It turns your C# code into C++

wanton bronze
#

Oh

hollow garden
regal olive
sly grove
regal olive
#

Damn alright lol

drifting galleon
#

'default way' is pretty hard to say. there's still plenty that use mono and the now updated mono version is a lot closer to il2cpp performance as well.
i personally can't wait to be able to build to native .net

sly grove
#

When I say "default" I mean if you don't go into settings to change it, you're getting IL2CPP

#

for most target platforms

drifting galleon
small latch
#

Same here (I have to manually swap to IL2CPP)

undone coral
#

is there a way to get stacktraces in mono windows release builds?

#

with line numbers*

grave bear
# drifting galleon ``` <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version...

Sorry to bother you again, but for whatever reason I'm not able to add the DLLs to my project without some assemblies unable to be resolved:

Assembly 'Assets/UnityStateNetworking/Runtime/Plugins/microsoft.codeanalysis.csharp.workspaces/Microsoft.CodeAnalysis.CSharp.Workspaces.dll' will not be loaded due to errors:
Unable to resolve reference 'Microsoft.CodeAnalysis.Workspaces'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
...
#

I looked at the unity docs for source generators, but it seems kinda pointless if the source generator is just generating a class from a normal cs project, and then compiling it for unity to utilize like a normal plugin.

#

maybe im missing something?

drifting galleon
daring pelican
grave bear
#

wait

#

This is based off of the assumption that the generator is compiled outside of unity. I think I need to assign the same process described in the unity docs to the nuget packages

#

hold on

drifting galleon
#

The source generator is always compiled outside of unity

#

You can't write it 'inside' unity

grave bear
#

lmao now I need to make a tool that makes it more IL-like haha

grave bear
# drifting galleon ?

well, it depends if Visual Studio allows me to debug the generated code without having to compile every time haha.

#

It would basically be just a simple helper class that does string building like AddUsingNamespace(nameof(MyNamespace)); etc

#

after adding a namespace, you can do: AddClassDefinition ("SomeClassName", ClassFlag.Static | ClassFlag.Public);

#

eventually, you will call a method that compacts it all into a single string for the Source Generator to work with

drifting galleon
grave bear
#

very similar to how cecil works, but way easier to interpret what everything does

drifting galleon
#

Ah. So thats not code you will generate, but code of the generator itself

grave bear
#

yes exactly

#

sorry I should of made that a bit more clear lol

#

off to testing haha

minor cloud
grave bear
minor cloud
#

Fair enough

drifting galleon
#

Source generators don't emit il

grave bear
minor cloud
#

I'm aware of this, However whenever I've seen people mention dynamic code and or reflection IL Emitting often comes into play

minor cloud
grave bear
grave bear
minor cloud
#

I'm not entirely sure to be honest, haven't needed to dive into it that deep, Using CodeDom here and there to generate scripts is enough of a nightmare lmfao and ah yeah I know that, I ain't that new

#

Just was trying to point out that IL2CPP does have those limitations, I've seen people struggle with it before is all

knotty silo
#

is there a way to script a trigger to set an item into the inventory slot position?

#

like when I press a button it can set an item into the inventory slot

grave bear
#

each button would have a script that keeps track of its inventory index

#

have an inventory script that holds all your inventory items and inventory buttons

#

so when you click on a button, the item will be added to that slot (or dropped, swapped, removed, inspected... lots of options) and assigned to the slot in the inventory script's list/array

#

Example:

InventoryScript
    |-- InventorySlotScript 0
    |-- InventorySlotScript 1
    |-- InventorySlotScript 2
    |-- InventorySlotScript 3

Clicking on one of those InventorySlotScripts which is also a button, will tell the InventoryScript to move it to that index. What I do is use a GridLayoutGroup and instantiate a InventorySlot prefab that has a InventorySlotBehaviour script attached so I dont have to do it all manually.

knotty silo
#

thank you for the advice I will try to work on that direction

compact ingot
#

at a certain point (of proficiency) it becomes impossible to make any more tutorials/courses and you are expected to teach yourself "the rest" (this is where a CS degree comes in handy), the most complete resource is MSDN or one of the respected C# books.

grave bear
#

The beginner courses are all you need, really. After that you need to do research on your own to determine the right course of action during a projects development. Learning the language is the easy part. You get to a point where you want new or improved language features. The hard part is figuring out how to construct your project, the logic flow, what you can and cannot do (don't be surprised if you have to scrap an entire project because of one small detail).

grave bear
#

Looking for an easier way to write logs to console. Any ideas? Right now I just create a txt file and write to that and then log the info into the unity debug console

tender light
tender light
grave bear
compact ingot
grave bear
compact ingot
#

You can just expose a ILogger from the library and pipe that into Debug.Log

grave bear
#

Well see that's the thing, I don't actually have access to anything related to my Source Generator

#

because you literally cant

compact ingot
#

and the source generator does not expose its logger and just dumps it to console?

#

thats a terrible library

grave bear
#

...

#

no

compact ingot
#

maybe explain again what you want to achieve

grave bear
#

The source generator in question is a .net library that is not compatible with the current Unity roslyn compiler

#

so what I have to do is compile it in a standard library project that targets the netstandard 2.0 runtime

#

What I'm trying to do is make it easier to log to the Unity console. So far the only solution was to create a text file every time the source generator runs after compilation

#

Specifically, I want exception info

compact ingot
#

if you compile it to standard2.0 why can't you use it from unity directly?

grave bear
#

I could do some string magic and structure my file to make it look like it has exception info

grave bear
#

Unity doesnt actually support compiling source generators yet

#

their docs specifically specify to make a seperate project outside of unity to work

compact ingot
#

what do you actually mean by "source generator"? you can generate code in a unity project just fine, have unity import those files and use them on the next import.

#

do you want to compile a DLL from a unity project?

grave bear
#

In my use case, it's to resolve type-convergence

compact ingot
#

that is compile time source generation

#

you need to specify that to avoid confusion

grave bear
#

I thought "Source Generator" was obvious enough

compact ingot
#

that could mean anything, its a concept not a tech

#

anyway, can't help with roslyn source generators

grave bear
#

np, think im just going to stick with the file logging anyways

grave bear
# tender light > (don't be surprised if you have to scrap an entire project because of one smal...

a) It absolutely is true. Entire projects can get scraped if the designers overlook an aspect of their core project, that was my point. When I was still a beginner lots of projects were scrapped because I realized the scope of the project would be too much for me to handle, required complex changes to resolve some prototype design flaws, only looked at steps 1, 2, 3 and no further, and many other similar reasons.

b) If they lack critical thinking skills to evaluate the scope of learning a subject, that's on them. Programming/CS isn't something that has a small skill set that you can practice over-and-over again and get good at it in just a few short months. Every time you work on a project I guarantee you learn something new, because every project will have some sort of different challenge you need to overcome that may or may not be possible, but that can only be determined by knowing how to overcome design challenges.

drifting galleon
# grave bear np, think im just going to stick with the file logging anyways

Sorry to respond this late but I was sleeping.
Ive already sent you a source that tells you how to activate debugging previously.
A source generator runs inside Roslyn, not unity, so even when unity eventually supports the better workflow you will never be able to use any unity specific apis like debug.log to 'debug' your source generator.
The file approach was the first thing I worked with as well, but it's just pain. What you want is read the source I've already linked you.
If there ever comes a point where you require unity specific types to test your source generator, the way to do it is to write a mockup of those in an extra file and use these 'fake' versions to test your source generator.

drifting galleon
drifting galleon
#

@grave bear helped?

grave bear
# drifting galleon <@209095082735960064> helped?

Yeah the debugger is nice. I like being able to preview it. Buuut... I was hoping to get some sort of feedback during compilation. Its wacky tho, sometimes a log file will be created, sometimes it wont. Im not going to worry too much about it right now, just glad things are working better

drifting galleon
grave bear
#

wait

drifting galleon
#

Whenever it generates any file

grave bear
#

huh, didn't know you could do that

drifting galleon
#

I personally don't use it often but it's possible

round pawn
#

I spent hours trying to troubleshoot this yesterday but to no end. The issue is that the velocity vector rotates with the first person player controller, so I can move forward, release the forward key and turn 180, and the player will still be moving forward, as if the velocity was rotated as well. I tried a number of different things, from removing the relation to the input vector while it's magnitude is close to 0, I tried Lerp and adding an opposing force instead of writing to velocity. This issue is making no sense to me, as I cannot find the root of a problem that doesn't look like it should exist.

https://pastebin.com/qXK6X4iF

Move() Line 134, called on lines 79 and 90
Inputs set on line 240

#

Thanks in advance!

#

Additional info:
It's the only script in the project
Rigidbody and capsule collider are the only other components on the player object
Mass = 1
Drag = 0

undone coral
#

make a first person parkour game?

#

this is a very hard thing to do in a general way

#

because in the real world, you can't do general parkour - you obviously can't just run on a vertical wall forever like you do in video games

#

but it seems like that is your plan here, to let you run infinitely on any wall

#

removing gravity isn't going to achieve that

#

there are real life creatures that can do that, like spiders and salamanders and whatever. the problem is they can also walk on ceilings.

#

i would separate the problems of locomotion and the camera

#

or do not do something so general

grave bear
undone coral
#

in my opinion almost 100% of the code written here is "wrong" in the sense of going down a losing path

#

like there isn't a way to rescue this approach really

#

the game might not be a general parkour game. it sounds like it could be an infinite runner, really, where sometimes you go onto walls. totally different problem

grave bear
#

It doesnt

round pawn
grave bear
round pawn
#

Yesterday I even commented on how people will find endless irrelevant things to nitpick when you share code, lmao

round pawn
#

Other than that the code functions well

undone coral
#

the game sounds fun

grave bear
#

@round pawn I think I understand the issue you're experiencing

round pawn
grave bear
#

Does that look about right?

#

@round pawn

round pawn
#

Are you trying to reproduce the bug? If so I can walk you through it

gray pulsar
#

Rigidbody.MoveRotation or AddTorque?

#

or Rigidbody.rotation?

grave bear
#

Vector3 wasd = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")).normalized; @round pawn

#

one of these wasnt the same

round pawn
grave bear
#

GetAxis is interpolated. GetAxisRaw is not

flint geyser
#

I'm creating an EditorWindow to aid in placing Camera right in front of the inspected character's head. So I've created a Camera which renders to a RenderTexture and I've placed an Image with the RenderTexture inside the EditorWindow and the EditorWindow shows up when I'm starting to change the supposed location for the Camera. But the Camera created to assist in choosing the appropriate location for the in-game Camera captures real (in-game) space instead of prefab mode space where it is used. How do I make it capture prefab mode space instead?

round pawn
#

Much appreciation

#

I feel dumb

grave bear
grave bear
flint geyser
gray pulsar
undone coral
#

it looks really really good

#

if i were doing this i would study how it is put together

#

you don't have to use it but you could at least research it

flint geyser
gray pulsar
flint geyser
#

No, which scene is used for rendering, seems like people in your link provided Camera.scene hint, I'll try to use it

hazy epoch
#

Why did my Debug.Log messages suddenly start showing up with a weird prefix? 0x0000xxxxxxxxxxxx ...where "x" are characters that always change.

flint geyser
hazy epoch
#

Got it...but that prefix never existed before on any Debug.Log. I'm just wondering where it suddenly came from.

sly grove
hazy epoch
#

It's literally just a Debug.Log with a string in it.

#

It's not like a NullRef error or anything. Just a log I put in the code.

And it's never done this before. Not in the 2 years this project has been going.

undone coral
#

does odin inspector support quickly making a bool? serializable and editable in inspector?

glass mica
#

I need some help. I have a 6 object with the same script added to them and I'm trying to edit all of their private variable when one of the collided to an collider

drifting galleon
glass mica
sly grove
#

iterate over the list to change them

glass mica
#

What I'm trying to accomplish is each of them will have a seperate value

glass mica
outer kite
#

try try again

sly grove
hoary pendant
obsidian glade
glass mica
#

private void OnTriggerEnter(Collider other)
{
rabbits = GameObject.FindGameObjectsWithTag("rabbit");

    foreach(GameObject rabbit in rabbits)
    {
        rabbit.GetComponent<Rabbit1>.moveForce += Random.Range(1, 5);
    }
    
}
#

This is attached on a trigger

sly grove
#

is that the issue you're having?

glass mica
#

No

sly grove
#

also you should not crosspost

tough knoll
glass mica
#

How to make players see same view like they are watching the same

glass mica
#

Multiplayer game

regal olive
#

Hey, so, can someone code this? I have no idea what to do reading this but I'll get a better understanding if I'm reading the code

shadow seal
#

You actually want someone to write it for you and hand you the code

undone coral
#

there are also CSG assets. you can use Poseidon at runtime. works well and fast

#

you would make your level mesh, then subtract away with a big ol' cube in Poseidon. that's it

hollow garden
fresh salmon
#

It's probably less expensive to buy these assets and let them do it all for you, than hiring someone that will program it for you (don't expect people to work for free).

hollow garden
#

or (get this) you could spend some time and figure it out and code it yourself CB_thonk_overload

fresh salmon
#

Nah, they were sent here to ensure we feed our overlord the Aฬดฬฬบsฬถอ ฬงsฬทฬฟฬžeฬธฬพฬฑtฬดอฬฐ ฬทออ•Sฬตฬอ‡tฬตอฬฐoฬทฬ†อrฬธอŠฬ™eฬทอ›อ…

undone coral
#

poseidon csg is pretty good

#

if the user can figure out how to make a bunch of cubes together,

#

poseidon can solve the problem of getting the cross section

#

whaddya think @regal olive ?

fresh salmon
#

I don't doubt the efficiency of the asset, for something paid I would expect the features to be at least decent anyway
But it would be good to link the page directly, or mention that it's a paid asset in the original message

#

A matter of principle, so they don't waste time dreaming on something if they can't afford it in the end

regal olive
#

I made a shader, I guess it works

undone coral
#

great

mortal orchid
#

There is a player and a blue mech robot behind it. The blue mech is following the player like looking in the direction of where the player is looking so they shoot simultaneously. Technically the object it follows is the empty object called a shooting point attached to the gun's tip so that the mech is aiming where the player gun is aiming so that they can look aligned. But the problem is when the player animation is playing like the player moving forward and backward or player rolling etc I don't want these actions to be copied by the mech robot it looks weird but unable to find a solution to stop the mech rotation when the player's animations are running it should remain calm when player doing it's animation action just follow the player look not follow any other action.

This is the line in the image where the mech follows the player's shooting point in the shooting function this function has been called in Update.

The full script of the player controller.

https://pastebin.com/3TTYN1cR

woven kettle
#

hey,

I'm trying to add a force to an object with riggidbody in the right direction, the force is supposed to force the objcet to leap in the direction of the force (like a push from an explosion)

to determine if the object was hit or not i used (transform.position, radius,new Vector3(0,0,1),0) (*the vector3 is direction, the float at the end is the maxDistance *)

the problem is, when I tested that, RaycastHit.point is always Vector3.zero ... so the force is also always = ZERO

why is the Hitpoint = V3.zero?????

drifting galleon
#

if you want explosion force, there is a method for that already

woven kettle
sly grove
sly grove
#

but...

#

wdym

#

is it a raycast?

#

overlapSphere?

woven kettle
#

Physics.SphereCastAll(), sorry, i forgot to mention that.

sly grove
#

use OverlapSphere

#

a spherecast that doens't move will never detect anything

#

because they don't detect things that the spherecast starts inside

woven kettle
#

I want to take advantage of the hitpoint property of the Physics.SphereCastAll()

sly grove
#

but it doesn't make sense

#

it won't work the way you want

#

there is no hit point if the sphere is not actually being cast

woven kettle
sly grove
woven kettle
sly grove
#

You may want to read the docs:

Notes: For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point. You might want to check whether this is the case in your particular query and perform additional queries to refine the result. Passing a zero radius results in undefined output and doesn't always behave the same as Physics.Raycast.

#

it explains why your point is the zero vector, it says it right there

sly grove
#

anyway all you need to do is add a force from the center of the "explosion" towards the object

#
hitObjectPosition - explosionCenter```
woven kettle
sly grove
#

then yes

#

if not, no

#

maybe you want the opposite?

#

a - b gives you the direction from b to a

woven kettle
#

and that happens quite often :S

#

as if the object being thrown backwards!

jolly berry
#

Not sure where to ask this so sorry if this isn't the write forum...but does anyone know of this trick where you place your different menu screens and panels outside of the camera view so they're easier to see and manage in the editor? (Instead of having all of them layered on top of one another and clicking hide and unhide constantly.) Thought I'd ask the advanced coders since this might be a trick you use. I remember seeing a tutorial that used this trick but for the life of me I can't remember which one it was, because I want to use it but don't remember the details.

#

Just knowing what this tip is called would help me google it.

ember temple
sly grove
jolly berry
# ember temple Do you mean rearranging the editor windows?

no, it's like a trick you use if you have, let's say, a lot of different menus. instead of having them all layered on top of one another in the game space, you have them moved outside of the gamespace so when you zoom out, you see the gamespace in the middle, and all the menus laid around it. and then when you run the game, all the menus somehow magically align into the gamespace where they should.

#

sorry, i'm still learning unity so not sure what the terminology is to describe this

#

it just makes it easier to edit different menus, since you don't have to click them on and off all the time

#

to get them out of the way

#

The guy in the tutorial I was watching did #1, but I can't for the life of me remember how he did this.

woven kettle
drifting galleon
jolly berry
dire lake
# jolly berry Not sure where to ask this so sorry if this isn't the write forum...but does any...

Do you want to learn how to create a sliding UI in Unity?

Then check out this unity tutorial in which we will be creating a Sliding UI with DoTween.

If you don't know what is DoTween? Then let me tell you that DoTween is a object-oriented animation engine, optimized for C#.

ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...

โ–ถ Play video
quaint geyser
#

Hi! I am facing a really strange issue here. I have my game witch does work perfectly on the editor, but when I build it, everything works just fine except the texts on the UI do not update!, they just show the default values they had in the editor.
I am updating the texts by code using "myText.text = value;"
Also, I am not getting any errors, I made a development build but there is nothing...
Is this a known issue? I've been searching online but couldn't find anything helpfull

kind bison
#

ok!

amber silo
quaint geyser
#

I didnt know you could debug your build! I will check it out and see if i find anything

whole quest
#

Is there a way to get current position on a spline(I am using Dreamteck Splines)

rotund kestrel
#

How do you usually approach figuring out what a native crash is from when is just unity libraries? We have logs in firebase but we can't make much sense out of it even if it is symbolicated for android.
It seems to be all over the place and can't find any patterns, the crash itself in crashlytics shows like:
libil2cpp.so
Dictionary_2_System_Collections_IDictionary_Remove_m5CF5FF8BC1B8AE9BD8293CCF405213119E71D432_gshared

azure meteor
#

I need some serious help

#

nobody in the beginner channel

#

or unity forums can help me

#

my terrain editor is completely broken

#

I just cant progress in my project any more

#

Ill send a video

regal olive
azure meteor
#

oh ok cool

regal olive
azure meteor
#

ty

fresh salmon
#

"nobody in the beginner code channel"
looks at terrain channel
at most 3 messages per day
lmao

compact ingot
#

best way to make a channel lively is to post interesting questions there... "fix my broken app" questions are very uninteresting to most people

mortal orchid
placid nest
#

Hello, I'm currently creating my own networking tool because no other solution really fits my project. To keep everything simple and clean for other developers who have no knowledge about networking I want to send network messages by just calling a method with an attribute on there. Example:

void Test(){
 // Executed on client
 DoThis();
} 

[Server]
void DoThis(){
 // executed on server
}

Basically when the client executes this method I only want him to tell the server to execute it and send parameters through if needed and on the server actually execute what should happen in the method. I've been searching alot on this topic on google, but couldn't find anything at all

#

I know how to create a new attribute, I just don't know how to change the behaviour of things when I've created a new attribute

austere jewel
#

Don't cross-post.
Also, if you just post massive systems nobody can help you, debug it with the debugger so you at least have smaller problems to present.

novel plinth
placid nest
#

i know about the existence of reflection

jolly berry
thick cloak
#

Anybody expert on Perlin noise? I have this super simple script that generate mesh. But I want to apply Perlin noise to the up vector, but every time I try, I doesn't apply for the individual vertices, but instead for the whole plane's height.

sly grove
#

the 0th

#

vertices[i] = but i is always 0

#

oh wait sorry missed the i++

#

Your code is a bit hard to read though due to the weird indentation

hoary pendant
#

Also you haven't posted your perlin noise implementation

sly grove
#

oh yeah - don't see any perlin noise haha

thick cloak
#

This was my solution, which didnt work

sly grove
#

try Mathf.PerlinNoise((float)x / size.x, (float)y / size.y)

#

the noise function will always return the same value for integral inputs

thick cloak
#

OMG!! It worked

#

Thank you so so much!

spare elbow
#

i am saving my SaveState class with xml serialization

#

when i add a new list attribute to the class the serializer has problems deserializing the old savestate class into the new one

#

this is what is gonna happen when the players update their game

#

so what is the best way to handle this issue

compact ingot
spare elbow
#

ok

#

i guess ill have to learn much more about xml to do that

#

simple youtube tutorials wont do it this time ๐Ÿ˜„

compact ingot
#

its not in the XML; its something you code yourself and inject/add to the serialization library you are using

spare elbow
#

so this is how i load for example

#

        if (File.Exists(path))
        {
            saveState = SaveHelper.DeserializeFile<SaveState>(path);
            Debug.Log("loaded save file");
            load_completed = true;
        }
        else
        {
            saveState = new SaveState();
            saveState.Init();
            Save();
            Debug.Log("initiated save file");
            load_completed = true;
        }```
#

i have to change this right?

compact ingot
#

depends on what SaveHelper does

spare elbow
#
    {
        
        var serializer = new XmlSerializer(typeof(T));
        var stream = new FileStream(path, FileMode.Open);
        var container = (T)serializer.Deserialize(stream);
        stream.Close();
        return container;
    }```
compact ingot
#

any particular reason you are using XML btw?

spare elbow
#

not really

#

thats kinda what popped up when i looked up how to save

compact ingot
#

its probably less work to do this with JSON

spare elbow
#

does json also have this issue im gonna have to deal with

compact ingot
#

yes

spare elbow
#

hmm

compact ingot
#

but its quite simple to write a custom serializer that can handle the migration

spare elbow
#

ok ill look into it

#

thanks

compact ingot
#

and just based on the fact that XML is a massively overengineered piece of tech, you might have an easier time doing it with a simpler format like json

spare elbow
#

alright

regal olive
#

Anyone know anything about the performance difference between having a ton of .JSON files VS having one very long .JSON file? Specifically, if I need to serialize the positions of every character and their inventory for instance.

My thoughts are that if you have multiple each one contains the data for only that one NPC then the serializer will have to look through less lines to find what it needs. But I'm not aware of any game that saves hundreds of .JSON's, one for each NPC, so wondering if that's not the case?

EDIT: I suppose you only serialize from once and then its stored into memory through the in-application properties. So maybe it doesn't matter?

sly grove
#

most of the time save files are not big enough for it to be a huge concern

#

if you have enough data where that's a concern you'd probably look into a different approach like using a database instead

regal olive
compact ingot
inland delta
#

like i did in my game

calm ocean
#

Does anyone know the difference between scriptable object's create instance and instantiate?

hoary pendant
gray pulsar
#

both of them make runtime instances

#

and if you want to save an asset file you need to save it out with AssetDatabase

calm ocean
#

So it's like the difference between creating a new game object and filling it with data and instantiating a prefab?

gray pulsar
#

CreateInstance will create it with all its default values

#

while you can pass an instance into Instantiate and the new copy will have the values of that instance instead

hoary pendant
#

Ah okay, forgot you had to make an asset after CreateInstance. Usually never use that method anyways as they are not what SO was intended for

calm ocean
#

I see, thanks for the help

hoary pendant
# calm ocean Why not?

Hmm I suppose you could save a new asset during runtime if you wanted for persistent data. But usually you use it as data created thru inspector

calm ocean
#

I haven't had a chance to create a new asset during runtime as well. I have just been experimenting with different ways of working with scriptable objects

#

But I suppose it could be useful for things like inventory management

hoary pendant
#

Like generating a brand new item or an ingame editor

calm ocean
#

Yeah, and you can save the items in your inventory

#

Just a thought, not sure how practical it is though

#

As opposed to just keeping a list of regular classes

gray pulsar
#

yeah, it adds a bit of editor functionality, but no real benefit to game code over regular classes

calm ocean
#

Would the draw backs be large? Say, performance or memory wise?

#

If the benefit of editor functionality is free, I see no reason to make everything a scriptable object

hoary pendant
#

Not really SO is a simple data container, but organization is probably inefficient

undone coral
#

is it possible to ask a unity camera to render to some other native texture? for example, can i somehow set the native texture pointer on a unity render texture?

calm ocean
gray pulsar
# calm ocean Why not?

the CreateInstance => AssetDatabase path is useful for custom inspectors for constructing SOs, though. Like if you want to make a wizard for setting up a complex object and save it out or w/e.

hoary pendant
calm ocean
hoary pendant
gray pulsar
calm ocean
undone coral
#

can i ask unity to render a camera to a texture2d created via a plugin instead of a render texture?

#

or, is it possible to back a render texture with a different native texture whose lifetime i manage?

keen cloud
#
{
    static void Main(string[] args)
    {
        string[] inputCases = {"test1", "test2"};
        string userOutput = "";
        string gameOutput = "";
        System.Threading.Tasks.Task taskGame = System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            foreach (var inCase in inputCases)
            {
                gameOutput = gameOutput + HelloWorldFormatCompare(inCase) + "\n";

            }
        });

        System.Threading.Tasks.Task taskUser = System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            float elapsedTime;
            int i = 0;
            foreach (var inCase in inputCases)
            {
                System.Console.WriteLine("Testcase " + i);
                stopWatch.Start();
                userOutput = userOutput + HelloWorldFormat(inCase) + "\n";
                elapsedTime = (float)stopWatch.ElapsedTicks / 10000000;
                System.Console.WriteLine("Execution time " + elapsedTime.ToString("0.############") + "\n");
                i++;
    }
        });

Anyone know why this code is giving me this error?

error CS0841: A local variable 'stopWatch' cannot be used before it is declared
error CS0841: A local variable 'stopWatch' cannot be used before it is declared```
fresh salmon
#

You'll have more luck and a faster answer asking this in a C# server instead.

keen cloud
#

i mean its part of my game lol idk i just asked here first

fresh salmon
#

Unity does not use the static Main entry point

compact ingot
keen cloud
keen cloud
compact ingot
#

and what do you do to get those errors?

median cosmos
#

hey I'm kinda stuck with this issue. I'm trying to spawn tree (in 2D) with a random z rotation between -10 and 10 so it feels more organic but I can't figure out how to calculate how much to move the sprite down so there won't be any space between it and the ground. the ground and the bottom of the sprite are both perfectly horizontal (no slopes etc.)

#

does anybody know how to do this?

sly grove
#

so you don't have to think about it

median cosmos
#

no the issue is that I already placed the trees everywhere and that I also spawn them with a random size and position them via code after so they also lign up on the ground

#

I can't figure out though how to do the same with z rotation

sly grove
#

yeah sounds like making the bottom of the tree the pivot would be fine and work perfectly with that

#

you can just set the position to the ground's y position and it'd work fine

#

it'll make your other code simpler too

median cosmos
#

okay but that wouldn't help me with the problem would it? I spawn them with a random rotation

#

so I would still need to reposition the trees after

sly grove
#

why would you need to reposition anything

median cosmos
#

also, the sprite's middle perfectly works as the pivot

sly grove
median cosmos
#

I spawn them with a random z rotation in Start()

sly grove
#

if you have the bottom as the pivot

median cosmos
#

no

sly grove
#

this is a before/after rotation

#

easy

median cosmos
#

I will send you a photo

#

it works in the middle but not on the right side

sly grove
#

set the pivot a little above the bottom then.
Or do the trigonometry

median cosmos
#

but they spawn with a random rotation so that would mean the pivot would be different for every rotation

#

yeah I've already tried the trigonometry solution but I'm not good at it so it didn't work

sly grove
#

trigonometry will give you the value of d

placid violet
#

Math ๐Ÿ˜ฑ

sly grove
#

given that distance T (half the width of the tree trunk) and the angle theta (which you chose randomly)

median cosmos
#

sorry I think I didn't explain my issue enough: every tree spawns with their own random rotation

sly grove
#

then it's just SOH CAH TOA

median cosmos
#

ah thank you

median cosmos
#

oh ok

sly grove
#

you have sin(theta) = opposite/ hypotenuse

#

so sin(theta) = d / T from the diagram

#

You should have the value of T (it's half the width of your tree trunk), and theta(you chose it randomly), so you can solve for d

#

which is how far down you need to move the tree into the ground

#

d = sin(theta) * T

median cosmos
#

thanks so much!

sly grove
#

just make sure you express theta in terms of radians if you want to use Math.Sin

median cosmos
#

yep did that already

#

hmm

#

still doesn't work correct

#

I did this

#

wait wut

#

so I'm kinda confused what do to with Math.Sin() so if I should put Rad or Deg in it

#

it says it uses an angle

#

doesn't this mean it's already an angle?

#

so I don't need to do anything?

#

hmm no doesn't do anything

#

ups I think I found the issue

sly grove
median cosmos
#

omg

#

I'm so dum you're right

#

I also used the x scale and not half the x scale

#

so do I need to use Mathf.Deg2Rad since I already have the rot as an angle?

#

ahhhh wait a sec

#

nope still doesn't work

#

you can ignore the scale thing and first position offset since I tried that and it works alright

sly grove
median cosmos
#

I tried that as well already

#

didn't work either

sly grove
#

also are we sure that localScale.x is the width the tree trunk?

median cosmos
#

hmm you're right once again

#

imma do it correct once again

#

still doesn't work

#

the 100 smth - 99 smth is the exact width of the tree trunk

sly grove
#

what's it doing?

median cosmos
#

wdym?

sly grove
#

you said it's not working

#

it's doing something right?

median cosmos
#

it's still like this

#

it does something, but the difference between the trees is really small

#

this one for example works better

sly grove
#

do the trees have a parent object?

median cosmos
#

nope

#

no child objects either

#

and only a sprite renderer

#

and only one script each which I just showed you

sly grove
#

hmmm, not sure really what's missing here, other than possibly that tunk width being wrong

#

or my math being wrong ๐Ÿ˜›

#

Or your original height adjustment could be slightly off too

median cosmos
#

well I can test once again

#

nope it works perfectly fine

#

you did notice that the rotation I generate is already in angles and not in rad?

hoary pendant
median cosmos
hoary pendant
median cosmos
#

or if he didn't see it and thought they were actual rad numbers

#

yep well thanks for the help!

sly grove
#

they need to be radians for sin

#

so you need to convert degrees to rad to use sin

torpid blaze
dim vault
#

Is there any way to make Unity Poll for event data faster that is not based on FPS?

timber flame
#

Simple task scheduler
Do you know any better maybe more efficient way to raise an event periodically for some tasks?

 public class TaskScheduler
    {
        private readonly int _fixedRate;
        private readonly List<TaskData> _tasks = new List<TaskData>();
        private CancellationTokenSource _cts = new CancellationTokenSource();

        public event Action<int> Raised;

        public TaskScheduler(int fixedRate = 1)
        {
            _fixedRate = fixedRate;
        }

        public void Add(TaskData data)
        {
            _tasks.Add(data);
        }

        public void Remove(int id)
        {
            var index = _tasks.FindIndex(task => task.Id == id);
            if (index >= 0)
            {
                _tasks.RemoveAt(index);
            }
        }

        public async void Run()
        {
            try
            {
                while (true)
                {
                    await Task.Delay(1000 * _fixedRate, _cts.Token);
                    foreach (var taskData in _tasks)
                    {
                        taskData.RemainingTime -= _fixedRate;
                        if (taskData.RemainingTime > 0) continue;
                        Raised?.Invoke(taskData.Id);
                        if (taskData.IsRecurring)
                        {
                            taskData.ResetRemainingTime();
                        }
                        else
                        {
                            Remove(taskData.Id);
                        }
                    }
                }
            }
            catch (TaskCanceledException e)
            {
            }
            catch (OperationCanceledException e)
            {
            }
        }

        public void Cancel()
        {
            CancellationTokenGenerator.CancelAndCreateNew(ref _cts);
        }
    }
#

For example, in city building games, there are many buildings generating some stuff (food, wood, meral, etc. every n seconds)

undone coral
#

can canvases be baked? instanced? if i make no changes to the hierarchy of a UGUI canvas, in world space for example, it is not rerendered correct? is there an asset that does this?

sly grove
# timber flame Simple task scheduler Do you know any better maybe more efficient way to raise a...

I see two problems here for that type of game, both linked to the same kind of issue:
1 - Unity's async implementation relies on checking in on things once per frame. This means that your await Task.Delay is going to have some error introduced to it by that process. the await time will be the minimum time to wait, and then it will resume on the next frame after that minimum. Meaning if you ask to wait for 1 second, you may actually wait 1.05 seconds for example. This error will accumulate over time. So your tick system will already not be very consistent.

2 - similarly, the way you are doing this is slightly problematic too:

if (taskData.IsRecurring)
{
    taskData.ResetRemainingTime();
}```
If the recurring task is supposed to recur every n seconds, and your fixed rate doesn't divide evenly into n, you are throwing away some time there, and the recurring task won't recur perfectly over time
#

The net result of all this is that your "fixed" timers are all subject to small but cumulative error over time. This may or may not bother you, and may not even be immediately noticeable. But if your game were ever to become popular with, for example, speedrunners or build up any kind of enthusiast community, It would be an issue.

undone coral
#

you should use it as your async solution

#

i think unity plans to adopt it first class

#

if you want a recurring task that would seemingly be part of the task itself

#

you also can't really delay on the main thread like that. if you are in a threadpool, you should use unitask

tender light
novel plinth
#

Pool those token sources somewhere, and dispose them on scene changes and OnDisable..

Depends on your Unity version, in 2022 we now have MonoBehavior.destroyCancellationToken which makes asyncs make more sense to use now

magic reef
#

Im trying to have unity read a file, ill i want to ask is what the difference is between these two directories, because for some reason unity accepts the second one, but not the first one, im pulling the first one from a textmeshpro.text string but it doesnt matter since even putting it into unity through note pad wont work

#

im not shitting you when i say unity takes these two seperate file paths differently and chooses one over the other

sly grove
#

Look at them in a hex editor or do a character by character comparison in code if you want to know for sure

tough knoll
#

Hey I got a code question

#

It's more like a math question but

#

I'm generating a procedural train track by using a sort of spherical coordinate conversion kind of thing

#

To generate the curved line, I give it a length and angle and then use this function:

#

Vector3 theta = new Vector3( Mathf.Sin( angle * t * Mathf.Deg2Rad ) * length, 0f, Mathf.Cos( angle * t * Mathf.Deg2Rad ) * length );

#

It gives me vectors along a circle, then I add those together to make the curve

#

So that works great on one axis, to do the other axis it would be like:

#

Vector3 phi = new Vector3( 0f, Mathf.Sin( angleY * t * Mathf.Deg2Rad ) * length, Mathf.Cos( angleY * t * Mathf.Deg2Rad ) * length );

#

How the hell do I combine the Z components to make it a 3d curve?

#

(t is the point along the curve from 0 to 1, this is like an evaluation function)

#

Not sure what even to google

undone coral
#

they specifically called out either unirx or unitask

#

i forget which

grave bear
#

For the life of me, I cant seem to get ILPostProcessor to work correctly with Mono.Cecil. It works perfectly fine in my console apps compiled by VS. For reference, this is all I'm doing as a test in unity and a console app:

#

if you dont want to compile it yourself, use Dotpeek or something similar to inspect this .dll

undone coral
#

i think unity forums discusses this exact issue

grave bear
#

@undone coral I'm currently diagnosing the issue further as I managed to actually write to the assembly without issues using the above code in similar context. Rewriting everything atm

undone coral
grave bear
undone coral
tough knoll
undone coral
grave bear
undone coral
#

Quaternion.AngleAxis(deltaPhi, Vector3.up)*Vector3.right

#

do you see what i am doing?

tough knoll
#

Yeah, and then just combine the quarternions I guess

#

I thought of turning them into quaternions for the add but I was trying to figure out how to do it mathematically so I could understand

undone coral
#

to draw it out

tough knoll
#

I just kind of want to understand how to combine spherical coordinates

undone coral
#

angle axis is a great way to do spherical coordinates

#

it will illuminate that an orientation is related to spherical coordinates by choosing a canonical value for what theta=0, phi=0 is, which i believe is Vector3.right

#

i.e. (1,0,0)

#

then you rotate about the axes (0,1,0) and (0,0,1)

tough knoll
#

I guess I should just read up on what happens when you have a quaternion multiply

grave bear
tough knoll
#

I understand the concept. Just not sure on how this translates to combining spherical coordinates when translating them to cartesian

grave bear
tough knoll
#

So like

#

to calculate theta and phi in cartesian coordinates

#

Vector3 theta = new Vector3( Mathf.Sin( angleX * t * Mathf.Deg2Rad ) * length, 0f, Mathf.Cos( angleX * t * Mathf.Deg2Rad ) * length );

#

Vector3 phi = new Vector3( 0f, Mathf.Sin( angleY * t * Mathf.Deg2Rad ) * length, Mathf.Cos( angleY * t * Mathf.Deg2Rad ) * length );

#

But then how does on combine the cosines into the Z component for a 3d arc instead of a 2d arc

grave bear
#

What's the end goal?

tough knoll
#

I'm generating a track for a procedural corridor background to follow for a train level. I'm aware there's like 9 million other ways to generate this curve, this is just the way that I picked and it made me aware that I don't really understand spherical coordinate conversion

#

I have a working solution for the actual project already, I was just curious if someone with a higher math education could illuminate me

grave bear
#

Is the corridor suppose to align to a fixed axis?

tough knoll
#

It doesn't have to, to actually generate the walls I sample a "center" position on the track and then sample other points for the walls in both directions and I get those vectors in the local space of the center

#

so it could really be facing upside down for all I care, it's just the relative curve from the center to the further walls that matters

grave bear
#

The further walls would be the walls in say a tunnel right?

tough knoll
#

Yeah

#

like this

#

But the code I posted just has to do with the generation of the track, this is all other unrelated stuff

grave bear
#

and those need to be aligned to what relative rotation? world space?

tough knoll
#

The blue vectors I'm getting in the local space of the green vector, and then I'm transforming the walls of the tunnel relative to where the player is standing to follow the same curve

#

so it looks like you're on a train car moving through the curve of the track

grave bear
#

the train car is in a fixed position? this is all "faked" to make it look like you're going through a tunnel?

tough knoll
#

Yup

grave bear
#

ah gotcha

tough knoll
#

To simplify physics and pathfinding inside the train xD

grave bear
#

makes sense

tough knoll
#

And also that way the player always exists in the relative direction of motion of the train, so it's less disorienting

grave bear
#

do the train do any sort of unnatural bends like loops or hard turns?

tough knoll
#

My generator has an angle limit of 15-45 deg. for turns right now, so not really

#

but I guess it could

#

Sometimes it loops over itself... Kind of silly but hard to tell since you're not seeing it from top down

#

and since the generated segments cease to exist when they're further than draw distance away from you, haha

#

I'm using mesh skinning to bend the walls to follow the curve, it looks really neat

grave bear
#

you can use the curve anchor to determine rotation. the larger the relative position delta (left or right) will determine a "pull" to the left or right respectively

tough knoll
#

Well, that part is easy, my question regarding coordinate conversions had to do with my method of track generation

grave bear
#

using an actual curve library would most-likely give you better results and make it easier to implement features

#

I have a few curve functions you can use if you want

tough knoll
#

But this track looks so good!

#

Could you show me an example?

#

of a curve function

#

My requirements were that they rotate smoothly along the selected distance for that track section and look mostly spherical

tough knoll
#

This is the output of my current one

#

Wouldn't I end up having more work if I use a parametric curve? because to make it perfectly spherical I then have to figure out where to put the control points to create that type of curve, right?

grave bear
#

the tunnel is perfectly spherical?

tough knoll
#

No, I mean the curvature of the turns

#

here look

grave bear
#

oh, you mean the the handles

#

yeah, a little extra work

tough knoll
#

But doesn't that put me back in the same problem of using trigonometry to convert a spherical coord to cartesian

grave bear
#

likely not because you can easily determine the mirror of the handle using just the coordinate system

timber flame
grave bear
tough knoll
#

Would the correct control point always be just the intersection of the two lines?

#

like so

timber flame
grave bear
#

but you dont need to do that if you want more chaotic curves that are not uniform

tough knoll
#

It kind of seems like my solution is less complicated if only uniform curves are required

#

I mean it is literally like one line right

grave bear
#

wait you want perfectly spherical turns between points?

tough knoll
#

Yeah

#

Basically like, I'm getting a series spherical coordinates forming the angle of the turn, translating them into cartesian coordinates to make them a bunch of direction vectors and then the sum of those is the track's line

grave bear
#

oh I thought you wanted some "natural" turns like when driving on a road in the mountains

tough knoll
#

I just don't know how to properly combine the multiple axes. I did in fact read a book but I think I'm looking up the wrong stuff because the normal method of converting spherical to cartesian doesn't seem to work with my code

stuck onyx
#

anybody using Unitask? I'd like to know which one of these is the right one to indicate to continue in the next frame:

#

"await UniTask.Yield();
or await UniTask.NextFrame():"

#

or are they just the same ?

untold moth
#

you could use the plain C# Task.Yield() in that case

thin mesa
stuck onyx
#

thanks humans

median cosmos
stuck onyx
#

I'm having a bottleneck on a script i created to transform my 3d map in 16 different textures... capturing, rendering, copying to texture all works fine and i was able to distribute it well in different frames so its done in 'background' seamlessly....
But when it gets the moment to encode the texture to png the game lags, (it takes 70-90ms) aprox... I tried setting

await UniTask.NextFrame();
await UniTask.WaitForEndOfFrame();````
#

before and after the encoding but still the game lags when the operation is being done

#

is there any way around this?

regal olive
#

im trying to make moving mesh reparenting script for a very complex mesh with climbing, and with big moving parts. I have a script for it but i have to make a trigger box above it
and that does not work very well
any ideas?

rugged radish
#

pretty sure compute shaders can help there too, never used them tho, so I don't know for sure

stuck onyx
rugged radish
stuck onyx
#

thanks a lot

sly grove
#
float timer;

void Update() {
  timer += Timer.deltaTime;
  while (timer >= fixedInterval) {
    timer -= fixedInterval;
    Tick();
  }
}```
obsidian glade
#

plenty of resources available that explain the concepts & how you could go about implementing one

grave bear
#

OK lmao I figured out why Mono.Cecil wasn't "working" as expected. Do not read the symbols when reading the compiledAssembly. From what I can tell, cecil reads them as a template for underlying types and methods. HOWEVER, it will include new types added (which explains why adding a type worked, but adding a method to an existing type, didnt.) The actual compiled assembly worked as far as I can tell, but dotpeek wasnt actually able to detect changes in the actual assembly. @undone coral since he took interest.

#

now, depending on use-case, using the existing pdb might be desired as it maintains the original layout of the assembly, with the exception of added types.

#

However, for debugging purposes, using the generated pdb from cecil is much better imo

undone coral
grave bear
#

dotpeek refreshed, it's just that the underlying types didnt change. Only changes that took place were the addition of types.

grave bear
#

I manage my own StateMachine library that behaves very similar to a BT. Start with understand the StateMachine logic first, as it will make understanding a BT much easier

obsidian glade
grave bear
#

basically yes. My FSM however is much simpler than a lot already out there with the added benefit of having a deterministic state pattern (basically a simplified BT)

calm ocean
#

Is it possible to iterate through a set, for each item, do something to it, and remove it from the set, in an efficient way? A foreach loop wouldn't work because I would be modifying the set as I am iterating through it. I thought of using a list instead of set so that I can do a counted for loop backwards, but then when I remove from the list, I am afraid that it would be inefficient. Any thoughts?

grave bear
calm ocean
#

Oh I see, so calling .remove() from the list is inevitable?

grave bear
#

no

#

there are collections out there that implement a RemoveAtSwapBack method that removes the element at index and replaces it with the last element in the array. Do note that the order of items will be scrambled when you do this

calm ocean
#

Oh I see, so if I don't care about order that would be the solution I am looking for

grave bear
#

yes

calm ocean
#

Awesome, thanks

grave bear
#

also, if you need to maintain order, using a list and RemoveAt will be faster than Remove since Remove has to compare each element in the list @calm ocean

calm ocean
grave bear
minor nexus
#

I have a script in unity which makes a linecast between two points over potentially thousands of iterations. Would this be a good candidate for multithreading using the job system and if so how would I perform the linecast inside of the job

tender light
compact ingot
minor nexus
minor nexus
compact ingot
#

well, actually no, it depends how you define a linecast

#

i guess a Physics.Linecast is just what you described, a ray with a length equal to the distance between the points

minor nexus
compact ingot
#

similar to a box/sphere/capsule cast

#

where you cast a line along a ray

#

but a linecast in that sense would be a capsule cast with radius 0

minor nexus
#

Hmm

bold slate
#

No need to rebuild the wheel. I use the free version of PandaBT and it's pretty good.

distant pivot
#

Hello everybody, I'm trying to understand something that I'm missing
So I've created some ScriptableObjects defining units in my game
1 ScriptableObject "Unit" that has 3 definitions, "Unit1", "Unit2" and "Unit3"
Unit contains stuff like a link to a prefab for the unit itself, and also a prefab for the gui object linked to it
I want to use the observer pattern, so i have an EventController that contains the delegate and a method that invokes the attached delegates
Can I use the scriptable object in the observer pattern and so, use the "Unit" representation ?
Because I want in my subscribers to use the prefabs

public class UnitEventManager : MonoBehaviour
{
    public delegate void CreateUnit<Unit>();
    public static event CreateUnit<Unit> OnCreateUnit;

    public void AddUnit(Unit unit)
    {
        OnCreateUnit?.Invoke();
    }
}

public class UnitListCanvas : MonoBehaviour
{

    private void OnEnable()
    {
        UnitEventManager.OnCreateUnit += AddUnitInfo();
    }

    private void OnDisable()
    {
        UnitEventManager.OnCreateUnit -= AddUnitInfo();
    }

    private UnitEventManager.CreateUnit<Unit> AddUnitInfo()
    {
        // How to get the unit type here so I can get the prefab ?
    }
}

[CreateAssetMenu(fileName = "New Unit", menuName = "Asset/New Unit")]
public class Unit : ScriptableObject
{
    public string unitName;
    public float speed;
    public float maxSpeed = 10f;
    public GameObject unitPrefab;
    public GameObject unitInfoPrefab;
    public CinemachineVirtualCamera unitCamera;
    public GameObject unitInfoName;

}
gaunt spoke
distant pivot
compact ingot
distant pivot
#

Thanks guys ๐Ÿ™‚

distant pivot
#

Still having an issue to comprehend something ..
So I'm using this to add a unit :

public class UnitEventManager : MonoBehaviour
{
    public delegate void CreateUnit(Unit unit);
    public event CreateUnit OnCreateUnit;

    public void AddUnit(Unit unit)
    {
        OnCreateUnit?.Invoke(unit);
        
    }
}```

This will be received by two objects : the unit manager, and the canvas manager
when receiving the event in my canvas manager, i need to know the reference of the gameObject created by the unit manager
is there a fancy way of doing it ?
hallow turtle
#

anyone good with photon can help me get my cameras to work

sly grove
#

unit?

heady bane
#

For unity web requests is it possible to put a body in a get request?

#

The person making the apis made a get request that requires a body parameter to determine what to return

fast pagoda
#

usually GET requests doesnt contains a body, but you can try using the data field that is used for POST requests

heady bane
#

How do I use datafield?

fast pagoda
#

after some verification, i'm pretty sure you can't, using a GET request

#

but as I said, I'm pretty sure that's the API problem, not yours

heady bane
#

okay

#

ill talk to the person working on the api

#

hopefully they can adjust. the api

undone coral
#

but i am pretty sure unity web request can be finagled

heady bane
#

I cant see how though

#

like where I could add in a body with a get request

undone coral
#

you can also use httpclient on mono on PC

heady bane
#

needs to work on ios

umbral trail
heady bane
#

Thank you,ill have a look intothis

untold moth
#

Anyone accustomed with the jump flooding algorithm can explain why is run in reverse order? Checking the farthest pixels first. Is it a a crucial part of the algorithm?

leaden trellis
#

Hello, I've already looked this up and cant find an answer. So in my script I have a variable
public List<turnOrder> RoundOrder;
that references inside this script

    public class turnOrder
    {
        public List<GameObject> TurnOrder = new List<GameObject>(); 

        public void addTurn(GameObject whosTurn)
        {
            TurnOrder.Add(whosTurn);
        }
    }```

At the same time I want to be able to add to the RoundOrder List by making a TurnOrder List that holds a game object so that way I can go back and keep adding to my TurnOrder lists all separately. I hope that made sense and if you need more info just ask
untold moth
#

Not sure what the question is. You should be able to access either of the lists without a problem.

leaden trellis
#

Yeah I can see them in the Inspector but I cant edit it via code. I hope this adds context

    {
        playerClone.GetComponent<Target>().unitStats.SPD_stats.current_speed = (playerClone.GetComponent<Target>().unitStats.SPD_stats.max_speed / 5) * 5;
        if (playerClone.GetComponent<Target>().unitStats.SPD_stats.current_speed < 5)
        {
            playerClone.GetComponent<Target>().unitStats.SPD_stats.current_speed = 5;
        }
        int playerTurns = playerClone.GetComponent<Target>().unitStats.SPD_stats.current_speed;
        while(playerTurns != 0)
        {
            RoundOrder.Add(new turnOrder.TurnOrder.add(playerClone));
        }

        foreach (GameObject enemy in enemyClone)
        {
            UnitEdited enemies = enemy.GetComponent<Target>().unitStats;
            enemies.SPD_stats.current_speed = (enemies.SPD_stats.max_speed / 5) * 5;
            if (enemies.SPD_stats.current_speed < 5)
            {
                enemies.SPD_stats.current_speed = 5;
            }
        }

    }```
#

I get this

untold moth
#

Why can't you edit it via code? Should be as simple as creating a new turn order object and adding it to the list.

#

Okay

leaden trellis
untold moth
#

Are you sure that's the correct type?

leaden trellis
untold moth
#

It saya Battle_Script.turnOrder. Is turnOrder a nested class?

leaden trellis
#

yeah its a class inside the main script that holds RoundOrder

#

@untold moth does it being a nested class ruin anything?

tough knoll
#

Wow

#

camelCase types and PascalCase members

#

truly now I have seen it all