#archived-code-advanced
1 messages ยท Page 203 of 1
I couldn't do much except a try catch, which was somewhat slower
also I am not a he
checking a type with magic strings were never a good thing.. just saying
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
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
show the stack trace
proly just missed the declaringtype flag
nevermind it seems it has fixed itself
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);
}
}
}
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-
It really doesn't lol
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 ๐
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
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
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
Can someone help me make a toon shader in URP shadergraph?
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
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
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
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
I've not used cecil for anything unfortunately, what do the editor logs show?
I'd say they would be the first place to check
Hopefully it is a unity problem and not some obscure cecil issue
It crashes, straight to desktop. The crash log screen says it couldn't get a stack trace, and actual log file is vague on the source of the issue.
I know .net has a source generator, but since Unity uses Mono.Cecil I went with that
I figured there were some internal difference in the mono runtime that require its own source generator since Unity is backed by mono. Is it possible any conflicts could arise using the .net source generator with Mono?
You should be aware that ILPostProcessors are executed in parallel in separate .NET Core processes, and don't have access to Unity's runtime. It might crash if you try to access something you shouldn't.
Yeah good point. Going to double check and make sure it's all thread-safe
unity uses source generators now
no
Curious, since when? Also, I looked into .net source generators and it looks a lot easier. Instead of Instructions, it's literally just strings.
Granted you have to jump through a few hoops, but that's the gist
i'm not sure if unity already doesn't use cecil at all, but i know that a lot of recent cecil work, like in the entity package got immediately migrated to source generators
The dll still exists yes, but if it's used is beyond me. Likely will stay there because some projects directly reference them instead of a package or something
they build on the roslyn api, which takes a a bit of time to get into, but is extremely powerful and good when you get the hang of it
I think one major factor in switching is the fact the code generated can be previewed in Visual Studio
Which I think is really helpful
and it's normal readable c# code
also, it undergoes syntax parsing and therefore makes it relatively error resilliant unlike cecil
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
first, what unity version are you working with?
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
What version do I need for IncrementalGenerators ?
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
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
which means you will need to use an api version compatible with the older roslyn of 2021. else they will not work
do you have any sources I can follow? I only have this one to go off of right now: https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview
it's not changed much, especially not the v1 ones (which these docs use) on the bottom you can find a link to samples and a cookbook
Unity.Entities is still using IL Post Processing according to this
https://github.com/needle-mirror/com.unity.entities/tree/master/Unity.Entities.CodeGen
Not everything that can be done with IL processing can be done with source generators. You can't modify existing source code with generators.
yes, but that's also something you should not do
and actually, you could do it with source generators
or rather the roslyn api
Of course you shouldn't be modifying the user's source code. But IL processing doesn't do that.
Yeah the example on the docs shows a virtual method getting replaced with actual code
ok, maybe they still use it for a tiny amount. but most has been reworked into source generators which is great. and maybe the rest at some point too
That still requires the user to define their class as partial
it's not so much replacement as it is addition
Hello guys !
OnPreCull is not running in URP ( i think its because of the URP )
Isn't ILPostProcess just an entry point to modify the current compiled assembly?
any unity messages about camera stages do not get called in any SRP
Yes, and in a performant way by running them in parallel with assembly compilation
so how to do that ?
i really need this event
you have to write a custom render feature
can i use the same code ?
look at the docs
no
oof
they work fundamentally different
black box magic
== bad imo
and microsoft thought so too
or like, not 'bad' but rather a last resort
tysm
https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/4.3.0-2.final#versions-body-tab so I uhh need literally v1?
just a sec. i'll check which version my project uses
im hoping I can use something newer, because 6+ years is a loooong time in terms of updates/features
<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
awesome thank you
i'm not talking about roslyn api v1. 6+ years ago source generators didn't even exist.
i am talking about SourceGenerator base class (referred to as source generators v1 in docs) and IncrementalGenerator base class (referred to as v2 in docs)
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 ?
no
why ? ๐ฆ
because they work FUNDAMENTALLY different
in the docs it said they have similar functionality
oh ok lmao that makes more sense. I was confused on the v1 thing thinking unity was behind on updates ๐
sorry, looked like legacy code at a glance so didn't read it at first.
i mean....maybe? i've not seen this anywhere. if yes, then that's definitely something newer than last time i checked
i mean....unity is....but not that much XD
yeah haha
oh tysm
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
Wow that will be helpful, thank you. Also, for context if anyone else is curious I found this: https://docs.unity3d.com/Manual/roslyn-analyzers.html
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.
they work with radians, not degrees
i think
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?
this question doesn't seem to be related to unity
Thanks, that seems to have given me the direction I needed
@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.
There is no job or collab posting here. See #๐โcode-of-conduct
sorry
Primary purpose is addition not deletion
Ok understandable.
That's not a limitation. It's a design choice
It may or may not be harder to design the codegen around addition, not deletion haha
Source generators don't solve the same problems as IL processing. They have different uses.
likely harder because now I have to make an extension class that calls the relevant code collected from reflection
They share a huge part of problems that are solvable either way
Im not "deleting" anything but I am modifying the class Im interested in, which just amounts to adding a few methods and some attributes
Most reflection stuff can be substituted by source generators
yes, but at runtime I have to use reflection. this is for an auto-serializer
That's easily doable. Just make it partial
yes, that is what I think I will eventually do
hello guys
have anyone tried scheduling a unity job from inside an async task ? Is that allowed ?
Probably
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
Job.iscompleted will never be true until you call .complete() on the job
it would hang indefinitely in that case and wouldn't produce any results
and I can see that it produces the mesh just fine
I thought that Complete() forces the controlling thread to wait on the job
It does. But a job does not get executed before .complete() is called
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
No. You may be calling ExecuteScheduledJobs or ScheduleQueuedJobs somewhere (I'm don't know the correct name of the method right now)
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
I don't, because this is the only place where I use the job system
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
I have no knowledge of your code. But I know that jobs don't run without .complete() or the ExecuteSchedulwdJobs()
We had a long discussion on jobs in #archived-dots months ago and we all came to the conclusion that jobs need 1 of the 2 criteria or they won't be run at all
Well, I don't know how you came to that conclusion, but it's easy to show that it's not true ^^'
We have waited seconds on the job completion of a simple job and it would never complete.
And it even makes sense how it works
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.
Put it into Start() instead and try
works too
I can't check it currently but then they have reworked the job system because this is definitely how it used to work
Nevertheless, the pattern to use jobs is:
Schedulethem as early as possible, and eitherCompletethem when you need their result; or- call
ScheduleBatchedJobsif you never really need access to their result and just want to make sure they execute.
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
And use SBJ extremely sparsely
agreed, Complete is preferable I think
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
Interesting. That must be a new addition of a recent version then
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"
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.
And when does the subsystem call SBJ?
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
so, Complete() does freeze the main thread
but
jobHandle.Complete()```
doesn't, and also doesn't cause the safety exception
So yeah, the jobs won't run. They may run if you use other packages.
yeah, I'll put the ScheduleBatchedJobs at the end of the loop
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 :/
thanks for the clearing things out guys, really great help โค๏ธ
You can just call .complete() the next frame as recommended.
It just doesn't work over multiple frames
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.
When you .complete on the very start of the frame it has all the time
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
That wouldn't be great for performance
For most jobs a simple .complete without an sbj call is enough in my experience, but you are correct for more heavy jobs
what "all the time" are you meaning? If it only starts when I call Complete, the main thread will then proceed to be blocked and do nothing until the job has finished.
Apparently so, definitely learned something new here regarding the scheduling behaviour. Thanks for weighing in!
It just passed a frame to the GPU, now you have a quick sync point and then you can move on to the next frame. That is the recommended approach in the docs
And presentations too iirc
i review the hdrp source to get a grip on jobs
they are really complicated
i wish someone would just take the language and interface of Tasks
they aren't. you just need to get into them
and just... rename this stuff
yeah i mean you're right they're not complicated
maybe the word i'm looking for is arcane
not even that
what do you need help with
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
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
Does it reimport stuff, when it takes 90 secs?
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
Should - it's the batch mode editor, right?
or batch mode player?
( i don't remember if the latter even exists)
you mean
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
Interesting I thought that was what the -nographics flag was for
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
ah got yeah
the net effect is that command buffers, i.e. requests to render, will be no-ops
they should document this stuff!!
Having a strange issue where an asset is causing issues with my unit tests due to a welcome window appearing on first startup
that is package specific
yup
batchmode does NOT prevent that
you will see in various unity code
checking if it's in batchmode
looks like lol
Find Usages on batchmode
yup took the words right out of my mouth
input system for example suppresses exactly such a window
onyl if it's in batchmode
Application.isBatchMode looks like this is what i'm looking for
that's what you'll use to patch the pckage yes
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?
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?
if you need to use 2022 you should report bugs, but i know that's useless because it will literally take them months to get back to you
you should use whatever version facebook tells you to use
to best develop for the quest
Well we are not sure if it is us or the engine ๐
i don't think it's you
Okay i will check what facebook thinks is good.
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
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
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?
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
nope, it kinda looks the same
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.
I searched and itโs not there and idk how to get it back
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)
rotate the head when accelerating
using lerp
for smoothnes
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
I tried using some lerps and move the head on acceleration but it wasnโt very natural
Do what VisionElf recommended then, sounds like it will work
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
}
Thanks, will try these tips
Is IL2CPP a good option for โrewritingโ C code into Unity
No? it doesn't do anything of the sort
What does it do
It turns your C# code into C++
Oh
leanAmount = rigidbody.velocity.magnitude / spaceShipMaxVelocity;
Oh wtf thatโs possible
not only is it possible it's the default way of building a unity game nowadays
Damn alright lol
'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
When I say "default" I mean if you don't go into settings to change it, you're getting IL2CPP
for most target platforms
strange. when i create a new project for default windows, mono is still the default one selected
Same here (I have to manually swap to IL2CPP)
is there a way to get stacktraces in mono windows release builds?
with line numbers*
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?
Its not pointless.
Make sure to look at the unity docs for Roslyn analyzers. You have to disable any platform inclusion inside unity and add the RoslynAnalyzer label to the dll
it turned out it was either SteelSeries or Razer software that was slowing it down
Yeah I got it to work following the unity docs exactly however, maybe I'm not understanding exactly what is going on here. From the looks of it, the source generator in the unity docs example creates source code that isn't dynamic (ie, cant use reflection to get attributes to create extension classes/wrappers/etc)
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
The source generator is always compiled outside of unity
You can't write it 'inside' unity
oh lmao I understand now
lmao now I need to make a tool that makes it more IL-like haha
?
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
I have no idea what you're trying to do anymore
String builder that is specific to making it easier when writing Source Generator strings
very similar to how cecil works, but way easier to interpret what everything does
Ah. So thats not code you will generate, but code of the generator itself
I'm not sure ifthis is relevant to you, but you should know if you're attempting to use anything to do with IL Emitting or any dynamic stuff, IL2CPP will not support it as far as I'm aware, but it'd be fine for editor stuff
Source generators are "editor-only" so it doesn't matter
Fair enough
Source generators don't emit il
Also, just because the source generator isn't directly tied to the unity project, doesnt mean you can bypass what your unity project is limited to (example: C# v9 API in a C# v8 project cannot be "forced" by using a source generator)
I'm aware of this, However whenever I've seen people mention dynamic code and or reflection IL Emitting often comes into play
As for this I'm honestly struggling to make the connection, it's a bit late lmfao
I think how .net source generators work is by creating an actual source .cs file the compiler will read and include in the compilation.
I edited it for clarity. But basically, you can't write code in the source generator using Python syntax and expect the compiler to just magically understand wtf you're doing lmao. Same with forcing newer syntax on a project that is using an older version of the language syntax.
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
Noted
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
You can listen for a button event and assign it contextually based off of some parameters (like your next empty slot, if space is available, etc)
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.
thank you for the advice I will try to work on that direction
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.
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).
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
(don't be surprised if you have to scrap an entire project because of one small detail)
Cmon man. Don't scare people with that.
a) its not true
b) even if it were you are just adding to their paralysis and indecisiveness.
what kind of logs?
So you are writing to your own separate file and then after you exit play mode you dump that into the editor?
I think thats a bit backwards if I understand it correctly.
What about Application.logMessageRecieved delegate? Why not use that and write to the log file after writing to console instead?
just, simple message logs from a source generator
why can't you use Debug.Log?
usage of the UnityEngine api isn't permitted
You can just expose a ILogger from the library and pipe that into Debug.Log
Well see that's the thing, I don't actually have access to anything related to my Source Generator
because you literally cant
and the source generator does not expose its logger and just dumps it to console?
thats a terrible library
maybe explain again what you want to achieve
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
if you compile it to standard2.0 why can't you use it from unity directly?
I could do some string magic and structure my file to make it look like it has exception info
Because that's the resulting target, not the project environment
Unity doesnt actually support compiling source generators yet
their docs specifically specify to make a seperate project outside of unity to work
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?
In my use case, it's to resolve type-convergence
that is compile time source generation
you need to specify that to avoid confusion
I thought "Source Generator" was obvious enough
that could mean anything, its a concept not a tech
anyway, can't help with roslyn source generators
np, think im just going to stick with the file logging anyways
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.
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.
I think it is reasonable to make the link to Roslyn source generators when someone talks about source generators in .net nowadays.
@grave bear 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
You can output the generated file as a debug option
In VS or unity?
wait
Whenever it generates any file
huh, didn't know you could do that
I personally don't use it often but it's possible
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.
Move() Line 134, called on lines 79 and 90
Inputs set on line 240
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
what's your objective?
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
None of that even helps him
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
How does any of this help him
It doesnt
Exactly
To summarize, when you push forward and let got, the velocity should maintain that heading regardless of orientation. But for you, it's "following" the forward direction of the player? Does this sound about right?
Yesterday I even commented on how people will find endless irrelevant things to nitpick when you share code, lmao
Yep, exactly
Other than that the code functions well
sorry about that, good luck on your journey
the game sounds fun
@round pawn I think I understand the issue you're experiencing
What's your take? So far all my diagnoses have failed
Uuuhm, not sure what you're trying to show me
Are you trying to reproduce the bug? If so I can walk you through it
have you tried using the rigidbody rotation methods instead of rotating the transform?
Rigidbody.MoveRotation or AddTorque?
or Rigidbody.rotation?
I could! I'll try it
Vector3 wasd = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")).normalized; @round pawn
one of these wasnt the same
Ok, fixed that
GetAxis is interpolated. GetAxisRaw is not
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?
Welp, you just fixed my issue. I had thought I tried using GetAxisRaw, but I had forgotten to change both input checks
Much appreciation
I feel dumb
yep np! In the future, always presume the error starts from the input and work your way down ๐
I've done worse lmao
prefab mode space...
have you looked at this asset store asset? https://assetstore.unity.com/packages/templates/packs/first-person-parkour-system-v2-0-for-playmaker-168546
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
They are discussing a different aspect of their problem and don't seem to have problems with rendering active scene space instead of prefab mode space
ah, your problem is which coordinate system the camera is using for positioning, not which scene the camera is rendering?
No, which scene is used for rendering, seems like people in your link provided Camera.scene hint, I'll try to use it
Why did my Debug.Log messages suddenly start showing up with a weird prefix? 0x0000xxxxxxxxxxxx ...where "x" are characters that always change.
Solved with Camera.scene = PrefabStageUtility.GetCurrentPrefabStage().scene;
Got it...but that prefix never existed before on any Debug.Log. I'm just wondering where it suddenly came from.
something's broken with like... debugging symbols?
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.
does odin inspector support quickly making a bool? serializable and editable in inspector?
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
try private static
not sure, but doubtful i think. but you can create an inspector for that easily
Static will change all of them with the same value
Keep track of all of them in a list
iterate over the list to change them
What I'm trying to accomplish is each of them will have a seperate value
I'm doing it. But nothing is happening
try try again
maybe show what you're trying to do, how you're trying to do it, and how the results differ from your expectations
sounded like that's what you wanted from the description - it's not clear what you're trying to do in that case
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
this won't compile
is that the issue you're having?
No
This is a bad solution. Using Find is always mega slow. Instead, create a static list and subscribe/unsubscribe to it in OnEnable/OnDisable
How to make players see same view like they are watching the same
Stop crossposting #854851968446365696
Multiplayer game
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
You actually want someone to write it for you and hand you the code
you can create a prototype using MudBun. the cross section would be a big box subtraction
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
Links if needed:
MudBun - $67 https://assetstore.unity.com/packages/tools/particles-effects/mudbun-volumetric-vfx-modeling-177891
Poseidon CSG - $45 https://assetstore.unity.com/packages/tools/level-design/poseidon-csg-dynamic-level-design-159427

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).
or (get this) you could spend some time and figure it out and code it yourself 
Nah, they were sent here to ensure we feed our overlord the Aฬดฬฬบsฬถอ ฬงsฬทฬฟฬeฬธฬพฬฑtฬดอฬฐ ฬทออSฬตฬอtฬตอฬฐoฬทฬอrฬธอฬeฬทออ
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 ?
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
great
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?????
if you want explosion force, there is a method for that already
its more than a punch than 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)
You used that... where?
on update
Physics.SphereCastAll(), sorry, i forgot to mention that.
Why use Spherecast if the sphere isn't moving
use OverlapSphere
a spherecast that doens't move will never detect anything
because they don't detect things that the spherecast starts inside
I want to take advantage of the hitpoint property of the Physics.SphereCastAll()
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
?? how its not casted ? its being casted in place on update
because you set the distance to 0
so it should be casted at zero point all the time
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
:S yeah
anyway all you need to do is add a force from the center of the "explosion" towards the object
hitObjectPosition - explosionCenter```
this script runs on the hammer script, i was thinking something like that
Vector3 dir = (transform.position - objTransform.position).normalized;
would that work ?
assuming the script is on the object you want to be pushed and objTransform is the center of the explosion
then yes
if not, no
maybe you want the opposite?
a - b gives you the direction from b to a
I'm having an unexpected results, not sure what is causing it, but when I move the hammer forward a little bit fast, the object flys in the direction of the hammer instead of hit :S
and that happens quite often :S
as if the object being thrown backwards!
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.
Do you mean rearranging the editor windows?
show the code? Did you reverse the positions?
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
https://forum.unity.com/threads/best-practices-for-editing-positioning-multiple-menus.434230/ This person describes the problem
The guy in the tutorial I was watching did #1, but I can't for the life of me remember how he did this.
yes that helped a lot, although sometimes it makes an awkward and unrealistic results but not as common as it were before.
thanks a lot ๐
well just as he says. write a script that moves the elements on demand.
another thing i would recommend: use UI Toolkit
thanks, i'll take a look at the toolkit!
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#.
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...
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
ok!
Try doing script debugging on the build to see if something weird is happening?
I didnt know you could debug your build! I will check it out and see if i find anything
Is there a way to get current position on a spline(I am using Dreamteck Splines)
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
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
Itโs not a coding question, go to #โฐ๏ธโterrain-3d
oh ok cool
ty
"nobody in the beginner code channel"
looks at terrain channel
at most 3 messages per day
lmao
best way to make a channel lively is to post interesting questions there... "fix my broken app" questions are very uninteresting to most people
I have tried this solution. It kind of works but is not that effective. I access the blend animation float parameter and see of the animation is running or not
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
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.
uh.. knowing how to make custom attribute without knowing the existence of Reflection is just.. uh...
i know about the existence of reflection
thanks for this! i don't think this is what i originally saw but it has what i need to do the job. much appreciated ๐
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.
you're only setting one vertex
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
Also you haven't posted your perlin noise implementation
Also #854851968446365696 for how to post code
oh yeah - don't see any perlin noise haha
This was my solution, which didnt work
the problem is you're using integers as the inputs to the noise function
try Mathf.PerlinNoise((float)x / size.x, (float)y / size.y)
the noise function will always return the same value for integral inputs
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
custom serializer that understands the migration from the old to the new type
ok
i guess ill have to learn much more about xml to do that
simple youtube tutorials wont do it this time ๐
its not in the XML; its something you code yourself and inject/add to the serialization library you are using
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?
depends on what SaveHelper does
{
var serializer = new XmlSerializer(typeof(T));
var stream = new FileStream(path, FileMode.Open);
var container = (T)serializer.Deserialize(stream);
stream.Close();
return container;
}```
any particular reason you are using XML btw?
its probably less work to do this with JSON
does json also have this issue im gonna have to deal with
yes
hmm
but its quite simple to write a custom serializer that can handle the migration
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
alright
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?
Managing multiple files seems like a nightmare. Why would you want to subject yourself to that
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
Actually it would be easier to do one for each but it would be bloated
If you have complex persistent data to save, query and update incrementally, use a single-file database like SQLite or liteDB
i would split separate things into separate json
like i did in my game
Does anyone know the difference between scriptable object's create instance and instantiate?
One makes an asset file, one makes an object
CreateInstance is like a constructor, while Instantiate is like a Clone method
both of them make runtime instances
and if you want to save an asset file you need to save it out with AssetDatabase
So it's like the difference between creating a new game object and filling it with data and instantiating a prefab?
yeah, similar
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
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
I see, thanks for the help
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
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
Like generating a brand new item or an ingame editor
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
yeah, it adds a bit of editor functionality, but no real benefit to game code over regular classes
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
Not really SO is a simple data container, but organization is probably inefficient
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?
Not really to the editor functionality part or to the draw back part?
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.
Read/write to SO at runtime and finding the files after creation
So performance wise that's not an issue?
Shouldn't be, but the organization may be messy
probably not 100% free, but definitely not large overhead
I did something like that be for a dialogue system. A class would read a file and convert each line to an instruction, and store the instructions as a list to a scriptable object.
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?
{
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```
You'll have more luck and a faster answer asking this in a C# server instead.
i mean its part of my game lol idk i just asked here first
Unity does not use the static Main entry point
show your using statements?
im making my game make this program to execute it
there are none im just doing it manually
and what do you do to get those errors?
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?
just make the bottom of the tree the pivot
so you don't have to think about it
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
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
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
why would you need to reposition anything
also, the sprite's middle perfectly works as the pivot
I spawn them with a random z rotation in Start()
if you have the bottom as the pivot
no
set the pivot a little above the bottom then.
Or do the trigonometry
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
Math ๐ฑ
given that distance T (half the width of the tree trunk) and the angle theta (which you chose randomly)
sorry I think I didn't explain my issue enough: every tree spawns with their own random rotation
then it's just SOH CAH TOA
ah thank you
that is understood
oh ok
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
thanks so much!
just make sure you express theta in terms of radians if you want to use Math.Sin
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
looks like you're moving the object on the z axis?
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
it should be Mathf.Sin(rot * Mathf.Deg2Rad)
also are we sure that localScale.x is the width the tree trunk?
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
what's it doing?
wdym?
it's still like this
it does something, but the difference between the trees is really small
this one for example works better
do the trees have a parent object?
nope
no child objects either
and only a sprite renderer
and only one script each which I just showed you
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
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?
I mean he already gave you the general pseudocode for how to solve it, since this is #archived-code-advanced , you be able to should find a way to achieve that feat
yeah I'm just wondering if he noticed this
regardless of semantics, the concept is there and you can see if it was right or wrong thru the docs
or if he didn't see it and thought they were actual rad numbers
yep well thanks for the help!
yes exactly
they need to be radians for sin
so you need to convert degrees to rad to use sin
Hey peeps, basically I want my script to have editable rotation values and not to follow the cursor (my position values are editable in the inspector so I want the rotation values to be editable too) please help me!
https://pastebin.com/cCtaLcdj
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Is there any way to make Unity Poll for event data faster that is not based on FPS?
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)
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?
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.
you can look at UniTask, which has an optimal task scheduler
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
Wait what?!?
Thats awesome. Where did you hear that? When is that happening?
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
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
Probably some invisible character difference
Look at them in a hex editor or do a character by character comparison in code if you want to know for sure
Not that the trig is not a good solution, but has it occurred to you to just inset all the trees by a small amount which is enough to make even the most rotated tree look good xD.
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
it was in a blog post of theirs
they specifically called out either unirx or unitask
i forget which
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
i felt like i just read a forum post about specifically this
i think unity forums discusses this exact issue
what's the objective?
@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
there apparently is an official unity splines package that may help you. bezier lines like it can perfectly produce a semicircle. it's not super clear what you are trying to do. you can use a quaternion to rotate a vector small amounts - it would point to the track.
serializer
like to emit IL for optimized serialization routines?
Splines are a bit overkill for this use case : p Just trying to draw an arc
okay the simplest way is
yes. I already have a plan in that regard. The difficult part is just getting cecil (unity?) to actually do what it is designed to do
Quaternion.AngleAxis(deltaPhi, Vector3.up)*Vector3.right
do you see what i am doing?
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
you're basically pointing at the arc, then rotating where you are pointing little by little
to draw it out
I just kind of want to understand how to combine spherical coordinates
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)
I guess I should just read up on what happens when you have a quaternion multiply
think of it as "adding" to a rotation
I understand the concept. Just not sure on how this translates to combining spherical coordinates when translating them to cartesian
What was your original question?
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
What's the end goal?
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
Is the corridor suppose to align to a fixed axis?
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
The further walls would be the walls in say a tunnel right?
Yeah
like this
But the code I posted just has to do with the generation of the track, this is all other unrelated stuff
and those need to be aligned to what relative rotation? world space?
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
the train car is in a fixed position? this is all "faked" to make it look like you're going through a tunnel?
Yup
ah gotcha
To simplify physics and pathfinding inside the train xD
makes sense
And also that way the player always exists in the relative direction of motion of the train, so it's less disorienting
do the train do any sort of unnatural bends like loops or hard turns?
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
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
Well, that part is easy, my question regarding coordinate conversions had to do with my method of track generation
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
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
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?
the tunnel is perfectly spherical?
But doesn't that put me back in the same problem of using trigonometry to convert a spherical coord to cartesian
likely not because you can easily determine the mirror of the handle using just the coordinate system
Absolutely true, my second question after that. Yes. Accumulated error.
To solve it, I should use for example Time.time or DateTime and according to it, accumulate these small values?
also, you would want to use an actual bezier curve, like the CatmullRomCurve function I got.
Would the correct control point always be just the intersection of the two lines?
like so
Thanks but what do you mean? delay on the main thread
you mean it is better to dedicate another thread instead of awaiting on the main thread?
for a perfect curve, then yes
but you dont need to do that if you want more chaotic curves that are not uniform
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
wait you want perfectly spherical turns between points?
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
oh I thought you wanted some "natural" turns like when driving on a road in the mountains
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
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 ?
you could use the plain C# Task.Yield() in that case
Similar as UniTask.Yield but guaranteed run on next frame.
thanks humans
yep that's exactly what I did after that, not a perfect solution but it seema to be working at least
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?
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?
I'm using the Job system to solve a similar problem, worked really well
pretty sure compute shaders can help there too, never used them tho, so I don't know for sure
could you give me some hint to what to google for?
"unity job system"
the documentation is pretty good as is, only encountered one unclear moment that people from this channel helped me to clear
I'm also using it with async calls, so should be easy to plug it in for you
thanks a lot
float timer;
void Update() {
timer += Timer.deltaTime;
while (timer >= fixedInterval) {
timer -= fixedInterval;
Tick();
}
}```
plenty of resources available that explain the concepts & how you could go about implementing one
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
sounds like it needs to be asked to re-read or refresh its view of an assembly's types
Dotpeek?
dotpeek refreshed, it's just that the underlying types didnt change. Only changes that took place were the addition of types.
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
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)
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?
best solution for pattern removal is to use a reverse for loop
Oh I see, so calling .remove() from the list is inevitable?
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
Oh I see, so if I don't care about order that would be the solution I am looking for
yes
Awesome, thanks
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
When you say there are collections out there that implement RemoveAtSwapBack, do you mean not native to c# and other people's implementations? I can't seem to find any collections native to C# that have remove at swap back.
I personally dont know of any native .net collection that implements RemoveAtSwapBack. I have a little collection library you can use that has the same functionality: https://github.com/Extevious/Collections/blob/main/Runtime/SimpleList.cs
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
Meaning that iteration 2 depends on the results of iteration 1?
If so than no. Multithreading is useful for independant tasks as synchronizing threads is problematic.
you need to benchmark your single and multithreaded implementation and decide which performs better, if you do not have a performance issue with it right now, its not worth it making a multihreaded variation
you do raycasts during a Job via https://docs.unity3d.com/ScriptReference/RaycastCommand.html
No sorry, as in I have 1000 instances of a class that I iterate over and in each iteration I am doing a linecast in one of those classes
Thank you
For a linecast the best solution is just raycast in the direction of the second point with length equal to the distance between the two points?
yes
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
What other definition might there be
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
Hmm
No need to rebuild the wheel. I use the free version of PandaBT and it's pretty good.
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;
}
Just add a unit parameter to your delegate and pass the unit instance when invoking the event, I don't really see why your delegate has a generic parameter of type Unit too ?
I tried stuff, yeah I just found how to pass the parameter ๐ thanks, but am I using the ScriptableObject correctly ?
there is no correct way, just ways that solve a problem and ways that create problems, you need to figure out which one you have there
You are, looks fine to me
Thanks guys ๐
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 ?
anyone good with photon can help me get my cameras to work
isn't that what the parameter for your event is?
unit?
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
usually GET requests doesnt contains a body, but you can try using the data field that is used for POST requests
How do I use datafield?
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
you can use better http if you need to deal with weird stuff like this
but i am pretty sure unity web request can be finagled
What is better http?
it's an asset store asset
you can also use httpclient on mono on PC
create and attach an upload handler to the WebRequest: https://docs.unity3d.com/ScriptReference/Networking.UploadHandler.html
Thank you,ill have a look intothis
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?
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
Not sure what the question is. You should be able to access either of the lists without a problem.
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
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
I'm not understanding what you are saying
Are you sure that's the correct type?
@untold moth as stated above It should be correct class and list inside that class
It saya Battle_Script.turnOrder. Is turnOrder a nested class?