#archived-code-advanced
1 messages · Page 20 of 1
Or will they need to create a new table themselves
if it's in streaming Assets it will be included in all downloads
Kk, thanks again
if we want code to execute while in prefab edit mode, is there an event we can subscribe to? currently using OnDrawGizmo 😂
I want to find a way that when I grab a corner I can move but only what can my arm allow me to. What I mean what this is how can I make my character attached but still able to do some small movements
Hey, I am sorry to be desperate on a Sunday, but I am on a deadline and I can no longer bake reflection probes. I get this error. Googling this error has not been helpful.
I have restarted unity several times. Only solution that works currently is duplicating the probe and rebaking the new probe, but this breaks all of the reflection probe overrides in the scene.
that only updates on cursor move
do you use source control?
and is this built in pipeline?
did the size of reflection probes change since they were baked?
:/
No. And rebaking them does not fix it.
This is Built in pipeline. Yes, we use source control.
I did find another workaround: I deleted every reflection probe exr file in the project and rebaked everything. This seemed to solve the issue for now. I am wondering if I need to submit a bug report, though.
Anyone have any clue why this could be happening? Whopping 10ms self for Director.PrepareFrame. On latest 2021 LTS.
It does not happen in an older project with the same setup as far as I can tell.
Here's a deep-profiled frame.
Is there anyone here that knows something about smooth Camera movement, im kinda having a problem with it (i don't want any yt links or smth)
Let me know if u can help
for (int x = 0; x < terrain.terrainData.alphamapWidth; x++)
{
for (int y = 0; y < terrain.terrainData.alphamapHeight; y++)
{
float height = noise[x, y] * 10;
float steepness = terrain.terrainData.GetSteepness((float)(x / terrain.terrainData.alphamapWidth - 1), (float)(y / terrain.terrainData.alphamapHeight-1));
if(steepness > 1)
{
Debug.Log(steepness);
}
for (int i = 0; i < Textures.Length; i++)
{
bool IsValid = height < Textures[i].MaxHeight & height > Textures[i].MinHeight & steepness < Textures[i].MaxSteepness & steepness > Textures[i].MinSteepness;
float a = alpha[x, y, i];
a = IsValid ? 1000f : 0f;
alpha[x, y, i] = a;
}
}
}
terrain.terrainData.SetAlphamaps(0,0,alpha);
``` Hello, I am making a terrain generation script however for some reason TerrainData.GetSteepness always returns 0 and nothing else.
I have this problem with my SmoothCameraFollow Script for my platformer game:
For now it works, but i want to implement a functionality that the camera only moves when the player is moving out of the jump range (the jump range is the distance of the players jump height) But, the jump range can also get lower if the player moves to a lower platform.
How can i make a functionality in this script where the camera doesn't move when the player is jumping, but does move when the player is moving in the y axis (not by jumping)
This isn't an advanced question, and try and post in only one thread.
Drop a breakoint.
UpdateHandAnimation(InputDevices.GetDeviceAtXRNode(XRNode.leftHand),leftHandAnimator); UpdateHandAnimation(InputDevices.GetDeviceAtXRNode(XRNode.rightHand),rightHandAnimator); (the error is XRNode does not contain a definition for "right hand" and "XRNode does not contain a definition for "left hand")
im a noob
but it seems
to be advanced
(following tutorial)
There's no lefthand enum
enum?
f12 XRNode.rightHand
i think a setting changed, which you'd be maybe able to find in source control, and then since probes are visible to each other it glitched out
protected override void OnSelectEntered()
{
rigidbodyObj.isKinematic = true;
and rigidbodyObj.detectCollisions = false;
}
protected override void OnSelectExited()
{
rigidbodyObj.isKinematic = false;
and rigidbodyObj.detectCollisions = true;
}
} ```
is this correct
because I got 4 errors,
if someone could help me with this
this would be great
this is the last thing to do
on the code; for context I'm following a youtube video and there is a comment (for something I need to fix)
found a comment on youtube
it just said
FOR FIX:
"private Rigidbody rigidbodyObj;
void start - rigidbodyObj = GetComponent<Rigidbody>();
OnSelectEntered - rigidbodyObj.isKinematic = true;
and rigidbodyObj.detectCollisions = false;
OnSelectExited - rigidbodyObj.isKinematic = false;
and rigidbodyObj.detectCollisions = true;" ```
and I assumed it meant (I assumed on select entered meant "protected override void OnselectEntered"
{
rigidbodyObj.isKinematic = true;
and rigidbodyObj.detectCollisions = false;
}
protected override void OnSelectExited()
{
rigidbodyObj.isKinematic = false;
and rigidbodyObj.detectCollisions = true;
}
so lets hope I did it right
I know what they meant by void start
please, use ` to parse your code,
example :
```cs
void Start()
{
Debug.log("hello world");
}
```
will give you :
void Start()
{
Debug.log("hello world");
}
it will be easier to understand
thanks
huge help
I forogt how to do that
k done
uh does anybody know how 2 fix
Fix what? If it's the code you posted you need to learn some basic C#
exactly
IM A NOOB
So why did you pick #archived-code-advanced ?
uh cuz it looks advanced
I might be wrong
You are entirely wrong
ok good
Do some tutorials pinned in #💻┃code-beginner
duh
So go and learn it first
...
then rewrite what the youtube comment said?
If it said that, ignore it
o
I'm sorry but this is the most cursed thing I have ever seen in my life.
I know right???
just ignore this
please
buttttttttt It would help if someone knew how 2 fix
because the comment doesn't give much of an explenation
on how
No, you need to put some effort into learning the language
Only then can you understand the issue
but were 2 start
I believe he is trolling
NO I SWEAR
k
You'd be surprised
damn
now I kinda feel
sad
about my stupidity
:((((((((((((((((((((((((((((((((
It's not stupidity, it's just a lack of knowledge
Not knowing something doesn't make you dumb
I guess that's true
k thx I guess
Ill come back to this code
when I have the right knowlege
and ill see what I did wrong
ill prob be laughing about it or smth
like a wow I can't believe I did that
k off to learn
how c# works
In the future, you belong in #💻┃code-beginner. Use that channel.
okayyyyyyyy I get ittt
he alr told me that
That's what happens when you bury your own conversation. 🤷♂️
💀
Sometimes I feel like this server could really use an enforced thread system, so many people spam channels it's nuts
At least for #💻┃code-beginner or something, it would make it much easier to follow conversations...
Yeah There is also new forum channel system in discord, it might be better for Q&A channels like that..
Yep, I saw that on another programming oriented server and thought it was really neat
Especially since it makes finding archived threads easier imo
I think threads are not used because it is hard to 'bump' and easily forgotten when scrolled up
Yes, that's why the forum system is cool, because it just uses normal threads, but adds an overview and a search functionality
Now I hope admins hear us pray 🙏
Hi I'm having an error "IndexOutOfRangeException: Index was outside the bounds of the array "
I think I'm missing something
Do you know how to use breakpoint?
yup
I think the problem is in Color[] pixels = _templateDirtMask.GetPixels();
I think it reach its maximum size?
You should put breakpoint and see the each variables are same as you expected
I think its not variable problem but more of array color
So you should inspect what size is the array, and which access to index that fails
what is the maximum size of array? I tried checking it using pixels.Length
it's max value of int so I doubt that, again, check which index fails.
will do thank you
hi guys, wondering if anyone could guide me on something
i have units which have stats example:
"unitName": "AdminUnit",
"statValues":[
{
"statName": "armor",
"statValue": 5
},
"passives":[
"orc"
]
but i also have the concept of passives
"passiveName": "Orc",
"statValues":[
{
"statName": "armorBonus",
"statValue": 2
}
]
wondering how i can map armor to armorBonus in code?
i thought i could call them the same thing and do it that way?
wondering if anyone had soe advice for me
The structure is totally up to you, I would treat stats as enum
How do you bake normals of a Mesh.MeshData inside a job?
Also how do I remove elements from a NativeArray, I'd use a NativeList but GetVertexData<Vector3> only returns nativearrays
{
float3 va = Vertices[a];
float3 vb = Vertices[b];
float3 vc = Vertices[c];
float3 vab = math.normalize( vb - va );
float3 vac = math.normalize( vc - va );
return math.cross( vab , vac );
}``` something like this. Also you dont remove elements from an array. You copy over what you want to a new smaller array for example
yeah, calling them the same is fine, but you'll also need to figure out how you combine each stat. you might have additive or multiplicative stats, like if it's armor, it's additive presumably, if it's damage multiplier, it would me multiplicative. for some stats you'd also probably need to introduce a cap
There are a million ways to do that, so we can't feed you any proper answer
If they have relevance, you make a Dictionary of relevant items, and put armor as a key and the armorBonus as value
If there is more to it, it obviously becomes much more, because a Dictionary like this isn't scalable
You can also make a class that holds one value (armor), and a reference to the same class with a difference instance (armorBonus) as reference 🤷
#854851968446365696 on how to post code
Can I ask why you are pointing me to the readme when I clearly wrapped the sample code I provided correctly? Since it was just a sample I did not feel the need to put a exact syntax highlight on it.
Plus, it wasn't C# but shader
it wasnt a shader just a function to calc Normals that can be used in a job
so it is c# but the specific highlight is not need
since it's JUST a sample
¯_(ツ)_/¯
thanks for all the tips guys! i will do some thinking
public async Task MakeRequest<T>(VRCloudRequestBase vrCloudrequest, UnityEvent<VRCloudResponseBase> callback) where T : VRCloudResponseBase, new()
{
var baseURL = _vrCloudSettings.BaseUrl.Value;
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
if (vrCloudrequest is IPost)
{```
Hello,
is there any way to fınd out whıch class is this that comes as a vrCloudRequest Base class? So I have to cast from baseclass to derived class. But do not want to use is keywrod since there might be thousands of subclasses.
.GetType();?
though it does suggest there may be a flaw in the structure or architecture of your code if you need to do this
You can make it a generic type that implements that VRCloudRequestBase class, and use typeof() I believe
Might not even have to be generic, but I assume the type is harder to retrieve if it's passed as a derived type
public class EnduserSendOTP : VRCloudRequestBase, IPost
{
public string PhoneNumber { get; set; }
}```
This is a derived class. Like PhoneNumberthere will be different attributes. These attributes will be the payload of the HTTP request in the MakeRequestgeneric function.
in order to reach those attribues in the EndUserSendOTP I have to downcast the coming VRCloudRequestBase how can it be done?
@random dust @obsidian glade
Can you make the method generic?
what method are you talking about
Sorry, I mean can you make the vrCloudRequest parameter in that MakeRequest method generic?
If you want to read those attributes, you can use typeof() on the generic parameter, and get all properties. Don't take my word for it though
hmm.
you mean I might change VRCloudRequestBase by a T
rıght?
@random dust
that is brilliant
why not is not it? @obsidian glade
public async Task MakeRequest<T,G>(VRCloudRequestBase vrCloudrequest, UnityE```
so the G will be what the VRCludRequestBase is
I suggest you make it
public async Task MakeRequest<TRequest, TResponse>(TRequest vrCloudrequest, UnityEvent<VRCloudResponseBase> callback) where TResponse : VRCloudResponseBase, new()
It is common practice to start generic types with T
Also, what you just wrote won't work since you need to make the actual type the generic type
Also, I assume you want to return Task<TResponse>
Unless you use the callback as the return value, which I don't see the use of if you use async-await lol
yes I'll use common practice,
I'll return both async or event, so people will choose what they want to use
Thank you @random dust
Ehhhh
Well that works, but I auggest seperating them and creating an overloaded method that accepts the callback
That one would be async void, and the other one without the callback is async Task<TResponse>
yes, sounds reasonable
But async void will prevent any exception from being thrown, so doing this requires you to wrap it all around a big try-catch block
I do not like it
And you will have to add a second callback in case an error exists, with the exception as parameter
I return a IResult
Otherwise you will never handle the error
So I suggest you just remove the callback, or you need to make sure the errors are handled
I can cast the errors through OnErrorOccured event as well. So all subscribers to this event will get informed if that happens. But overloading makes sense to me. Let me implement it asap.
Thanks again!!!
Anyone know how to create a TextMeshPro FontIcons file via script? like supplying the json and texture file then calling a function to generate the fonticons? I'm seeking to automate creation instead of going through window > textmeshpro > sprite importer. I've worked around it by opening the importer window automatically but I'd like to remove that step and just have the editor script make it for me. Any help would be appreciated. Thank you
There is a follow up, you are right, it is a scripting bug, but it happens because of Unity Version Update:
We uses steam sdk for basic DRM protection, and it depends on libsteamsdk(steamapi64.dll), for validating the dll itself is unmodified, we compare the file byte counts to a hard-coded uint in script, and the size of the libsteamsdk on mac end has changed after build, and thus failed the genuine check, if I choose to build to both Apple Silicon & Intel 64, the file itself disappears as well.
Any way, it's solved
Strangely, we use Application.Quit(); for quiting if the file is altered, but it turns to a Crash in Mac build.... weird
it's better to create overloads of MakeRequest
or to use reflection for serialization
what kind of backend API is it? a REST api?
clients can be generated from Interface Description Language. a common one is OpenAPI
rest api
what is the point of using async operations in Unity since everything in unity does not block other operations.
why? did you put that emoji
where am I missing
Because if you do a blocking operation on the main thread you will most certainly block the entire game engine
See what happens if you write Thread.Sleep(5000); in your code.
but for example playing with a character does not block anything at all?
wdym "playing with a character"?
play with a fps character in the play mode for example
All code you write is blocking
weirdly specific example but when you make a character controller, or any code, you only write code that will run very quickly otherwise your game will freeze and your framerate will suffer.
is there already an OpenAPI file specifying the API?
it's okay @mint sleet it looks like you have a lot of experience there's idiosyncratic unity stuff to learn
that resembles developing visual basic apps in the late 90s
Everything blocks
It takes time to process code
C# is just really fast at doing it
The point of Async is providing a solution for those pieces of code that block longer than you want to wait for on a main thread
Because main thread blocking is bad when it's noticeable
Also, even though Unity does not do multithreading, it still isn't blocking if you use async, since it works the same as coroutines
Has anyone done any work on scripting additions/modifications to the unity asset input pipeline?
yeah what's your objective
then i can point you to a specific example maybe
I'm looking to do some auto preprocessing for models as they get fed into Unity to do some kind of auto-rigging/ik setup for non-humanoid models
lots of resources for humanoids, but struggling to find much for generic/non humanoid models
ultimately I guess it wouldn't NEED to be done in the asset pipeline, and could just be a triggered function, but ideally it would be as simple as drag-and-drop
probably something like this
Ok I'll look in the HDRP repo some, I haven't mostly stuck to using the URP so far, so haven't checked that out, thanks for the reply
hmm ok yeah I'll have to dig around that example some more
thanks
yeah definitely at least gives me a jumping off point for exploring some of the pre/postprocessing stuff for the asset pipeline
do you also possibly have any experience with what class object models/meshes are typically imported as?
more examples:
https://grep.app/search?q=OnPostprocessModel(GameObject go)
Search across a half million git repos. Search by regular expression.
I've been trying to find good information on this and haven't been able to, but they aren't just Mesh objects
hmm
I've explored all the Mesh classes, and SkinnedRenderers
to try and figure out "what" they are, the inspector isn't super helpful in that regard either
is this helpful?
@undone coral Hopefully, will check it out thanks!
I'm hitting an intermittent access violation crash here in unity 2019.4 - any suggestions on how to track it down?
[Inline Frame] UnityPlayer.dll!atomic_compare_exchange_strong_explicit(volatile atomic_word2 *) Line 324 C++
[Inline Frame] UnityPlayer.dll!atomic_load_explicit(const volatile atomic_word2 *) Line 349 C++
UnityPlayer.dll!AtomicList::Load(__int64 & tag) Line 1142 C++
UnityPlayer.dll!JobQueue::WaitForJobGroupID(JobGroupID groupID, JobQueue::JobQueueWorkStealMode workStealMode) Line 1568 C++
UnityPlayer.dll!CompleteFenceInternal(JobFence & fence, WorkStealMode workStealMode) Line 32 C++
[Inline Frame] UnityPlayer.dll!SyncFence(JobFence &) Line 289 C++
> UnityPlayer.dll!GeometryJobTasks::EndGeometryJobFrame(GfxDevice & device) Line 63 C++
UnityPlayer.dll!GfxDeviceWorker::RunCommand(ThreadedStreamBuffer & stream) Line 775 C++
[Inline Frame] UnityPlayer.dll!ProcessGfxCommands(GfxDeviceWorker &) Line 161 C++
UnityPlayer.dll!GfxDeviceWorker::RunExt(ThreadedStreamBuffer & stream) Line 423 C++
[Inline Frame] UnityPlayer.dll!GfxDeviceWorker::Run() Line 407 C++
UnityPlayer.dll!GfxDeviceWorker::RunGfxDeviceWorker(void * data) Line 386 C++
UnityPlayer.dll!Thread::RunThreadWrapper(void * ptr) Line 78 C++
I'm trying to decimate triangles that are not facing up or down but I'm getting scrambled eggs instead. Probably linked to how triangles are encoded. I thought a triangle = 3 indices but it doesn't look that way, maybe they're composed of strips so one triangle index = 1 vertex index and the 2 previous ones in the array form the 2 other vertices. What's the fix?
triangles in Unity meshes are indeed 3 indices each
0, 1, 2 is the first triangle, 3, 4, 5 is the second, and so on.
mmm so i need to set all 3 indices to -1 to nuke a facet?
no you need to remove the triangle entirely
as in - create a new triangles array which doesn't include it
simplest way is probably something like:
List<int> newTriangles = new();
for(int i = 0; i * 3 < triangles.Length; i++) {
int t0 = triangles[i * 3];
int t1 = triangles[i * 3 + 1];
int t2 = triangles[i * 3 + 2];
if (TriangleIsOk(t0, t1, t2)) {
newTriangles.Add(t0);
newTriangles.Add(t1);
newTriangles.Add(t2);
}
}```
then do a ToArray() on the new triangles list at the end
ok I'll do that, out of curiosity, why does the list need to be rebuilt, don't triangle index set to -1 remove it? I see the facets get nuked
Is there a way to build a list and still benefiting from the new MeshData api perf wise? I'm working in a IJobParallel
It just leaves an invalid triangle in the data
like this? still getting triangles crossing the void
what is vStart
also what mesh are you starting with and what are you trying to do exactly
alright, switched to tStart, ur wirght
starting mesh on the left, trying to remove all facets that are pointing down
hmmm
update your video card drivers. also these are unusual stacks
what's unusual about it?
2 or 3 other people are also getting similar crashes with different card manufacturers
Is anyone familiar with creating dynamic instantiations of non-humanoid mesh objects without using prefabs?
Or does every animated asset need to be a prefab?
your normal calculation doesn't really seem correct....
for (int x = 0; x < terrain.terrainData.alphamapWidth; x++)
{
for (int y = 0; y < terrain.terrainData.alphamapHeight; y++)
{
float height = noise[x, y] * 10;
float steepness = terrain.terrainData.GetSteepness((float)(x / terrain.terrainData.alphamapWidth - 1), (float)(y / terrain.terrainData.alphamapHeight-1));
if(steepness > 1)
{
Debug.Log(steepness);
}
for (int i = 0; i < Textures.Length; i++)
{
bool IsValid = height < Textures[i].MaxHeight & height > Textures[i].MinHeight & steepness < Textures[i].MaxSteepness & steepness > Textures[i].MinSteepness;
float a = alpha[x, y, i];
a = IsValid ? 1000f : 0f;
alpha[x, y, i] = a;
}
}
}
terrain.terrainData.SetAlphamaps(0,0,alpha);
``` Hello, I am making a terrain generation script however for some reason TerrainData.GetSteepness always returns 0 and nothing else.
then you probably need to look at the GetSteepness function instead of that code
also not sure if this qualifies as code-advanced
That doesn't mean it isn't the problem
is it part of some copied and pasted code?
The code I sent?
prefabs are never completely necessary but it would be a huge pain the in the ass not to use one.
instead of doing just Debug.Log(steepness) you should add in the values being passed to GetSteepness
Yeah that's what I'm discovering... I was really hoping to be able to instantiate mesh objects without needing to make a prefab for every single model
you don't have to make a prefab for every single model
just make one prefab and assign the mesh at runtime to the renderer
You would need to make a prefab per animated mesh though, correct?
It is just weird how it doesn't return the correct value seeing as the heightmap is correct.
due to the bone/constraint differences
Not if they use the same skeleton
and in either case no
you can use a base prefab and prefab variants at worst
Ah interesting, I thought prefabs were a bit more static than that...
I would check the whole value, maybe check the x and y values too
I'm trying to create some dynamic non-humanoid "wildlife" style basic assets, that require different skeletons and IK rigs, but was hoping to create a bit more dynamic pipeline process to handle it
The X and Y are fine as I create an alpha map in the same method. TerrainData.GetHeight also seemed like it wasn't working as intended, as in it was returning the incorrect values.
then maybe it's your TerrainData itself
@sly grove have any good resources on reading up on how to use prefab variants for dynamic instantiations using different mesh/skeletons?
Any recommendations for this use-case then?
just try to make everythign the same on the prefab (base prefab) and the only differences on the variants to be the mesh/armature/animator state machine
Ok, but even doing so still is essentially creating a prefab per mesh/model though, just with inheritance from a base model correct? No way to dynamically set the mesh/skeleton through code alone?
you can set the mesh
it's simple - mySkinnedRenderer.mesh = myMesh;
but if the skeletons are different you need to also have different hierarchies
so it's a pain
mmm
it's easier to do this in the editor via prefab variants than through code
yeah seeming that way, is that what folks normally do for large number of animated assets then?
just create an object/prefab of every entity
Basically yeah, why not?
if you have a lot of assets you have a lot of art work to do
that's how it is
the things that are common like the AI code etc you make common
you're doing integer division where I assume you want floats
but the art and animation part if it needs to be different for each thing... it needs to be different
well honestly seems like the artwork is faster in that regard, depending on the artwork style of course
this is doing integer division and casting the result to float:
(float)(x / terrain.terrainData.alphamapWidth - 1)
I could churn out 2-3 rigged/animated low poly meshes in an afternoon for non player characters, but I guess the time spent is more of a "where the experience lies" sort of thing here
oh good catch! He should be casting x or alphamapWidth to a float
GetSteepness still seems to return 0;
subtracting 1 there is also suspect. I'm not familiar with the function but I'd expect you need to pass it a number between 0 and 1?
Yes
check your order of operations
x/width - 1 is not the same as x/(width-1)
x/width - 1 will always be negative if x < width
Thanks, this was the issue.
doesn't seem like it
Can you use assetPath property to get GUID?
testing this now but im not seeing expected resultis
do i use AssetDatabase.TryGetGUIDAndLocalFileIdentifier
or
var guid = AssetDatabase.AssetPathToGUID(assetPath, AssetPathToGUIDOptions.OnlyExistingAssets);
i doubt this will work because these objects are temporary objects that exist before the asset is saved
https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessModel.html
This function is called before the final Prefab is created and before it is written to disk, thus you have full control over the generated game objects and components.
Any references to game objects or meshes will become invalid after the import has been completed
So there isn't really an asset yet.
Yeah I suppose GUID might not even exist at that point
ok 😦
is there an Update even that doesn't get affected by Time.timeScale = 0 ?
you can use Time.unscaledDeltaTime. Update still runs even if timeScale is 0.
Update doesn't get affected by time scale.
FIxedUpdate does.
thanks, any way to get a rigidbody not be affected by timescale=0?
Not really no.
A specific Rigidbody?
You trying to make Braid?
yeah the camera uses that to avoid going through world
no, just your usualy RTS freeze build
Recommend switching to a CharacterController instead
Does anyone know if LeanTouch offers multi select and drag individual bodies? When I select multiple objects I want to be able to control each ones position separately with fingers.
I'll do that 👍
it's weird that mecanim doesn't get timescaled, it should freeze up
it has options for scaled/unscaled time I believe
it does... might be something else
CharacterController freezes on timescale = 0... mmmm... might have to make one myself
Even in Update? I guess it might still since it's part of the physics engine. What if you do Physics.SyncTransforms(); each time you move it?
Oh I never used that for this purpose, lemme try
nope
i wonder if one rigidbody can be forced to update
definitely not
You can force the whole physics scene to update with Physics.Simulate
It should be simple enough to just make a spherecast-based movement script for your camera
come on rider, auto write the files!
yes, working on it
oh SmoothDamp is affected by timeScale, let's see if they added a flag to ignore
nope, no problemo
oh that's interesting, if a kinematic is in interpolate continuous speculative, it behaves like a non kinematic and takes over direct movement, not so with a none-discrete
alright done!
2021.3 iteration time is abysmal, far cry from Ante's target of 100ms
you can pass a manual deltaTime value into SmoothDamp. Pass in Time.unscaledDeltaTime and it'll ignore timescale.
cool, thx. i didn't see that, just copied the unity implementation and replaced
why you always read the docs
public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime, float maxSpeed = Mathf.Infinity, float deltaTime = Time.deltaTime);
can see it default to Time.deltaTime, but you can feed it what ever you want
Hello people 🙂
Does anybody know whether Unity does or does not support proxy authentification when using WebRequests and Addressables?
I'm looking at migrating from JsonUtility to com.unity.nuget.newtonsoft-json, but I'm worried about performance since JSON de/serialization is used everywhere in my game
Specifically GC allocations because JsonUtility has zero GC.
com.unity.nuget.newtonsoft-json has special AOT handling for IL2Cpp which my project does use, so I'm wondering what's the best way to profile it, because I'm under the impression that editor profiling will not be accurate in this case.
Best case scenario, you have a single shared function you can edit to add ProfilerMarkers
https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerMarker.html
Guess I'll be making a separate project to profile this in isolation.
Working with IL2Cpp is kind of annoying that all performance related things have to be taken with a grain of salt
I also wish com.unity.nuget.newtonsoft-json had more documentation.
Hello!
How can I deserialize a JSON file that is wrapped in a result class?
{
"data": {
"token": "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQzZmdkcmZnIiwiZW1haWwiOiJmdXJrYW5rdXJ0QG1zbi5jb20iLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiRnVya2FuIEt1cnQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOlsidXNlci5kZWZhdWx0IiwiY291cnNlLmdldCJdLCJPcmdJZCI6IjY2NiIsIm1haWwiOiJmdXJrYW5rdXJ0QG1zbi5jb20iLCJuYmYiOjE2NjQ4ODYzNzksImV4cCI6MTY2NDkyMjM3OSwiaXNzIjoiZnVya2FuQG1ha2luZ3ZpZXcuY29tIiwiYXVkIjoiZnVya2FuQG1ha2luZ3ZpZXcuY29tIn0.06KUzrMH3x9ODv5ySrdv5gC41L-YjWXS4yoZphoWb3g",
"expiration": "2022-10-05T00:26:19.5198119+02:00"
},
"success": true,
"message": null
}```
data, sucess and message is a wrapper classs's elements.
token and expiration is "AccessToken" class.
I have more than just "access token" class .that means it is not smart to make c# classess for each response.
is there any way?
this is #archived-code-general stuff
it's literally just creating classes that match the structure of your json
ahhhh. my problem is literally overthinking. You'd laughed if I explain what I had thought! Anyways' thaks ``
I have already started the question here, I'd like to continue if you don't mind for this time.
[Serializable] public class Result : VRCloudResponseBase
{
public AccessToken data;
public bool success;
public string message;
}
[Serializable] public class AccessToken
{
public string token;
public DateTime expiration;
}
[Serializable] public class User
{
public string name;
public string surname;
}```
The Resultclass has AccessToken field. But this field differs from response to response.
I do not want to make the Result class multiple times.
What would you recommend? Thank you!
in what way
so I have for example User class instead of AccessToken
and in User class I have different properties. So if I replace the AccessToken field in the Result object then the User works, but not the AccessToken
is it under the same data key?
but with a different structure?
yes. I changed the Unıty Object Class examples above.
the Result must be a wrapper object over all responses. Not belong to only AccessToken
@sly grove
Without some kind of other marker for the data, you'll need to just make one class that has all the fields of both objects
What I trıed: I derieved both User and AccessToken from a base class and referenced that in place of AccessToken field. did not work.
[Serializable] public class Data
{
public string token;
public DateTime expiration;
public string name;
public string surname;
}```
then figure out what it is after by checking which fields exist and which don't
something like that
I wanted to have them in structure. But I do not know if it does worth to make it.
the problem is there's no indication in your data about which object it is
this could be done with some custom json deserialization logic, but you don't have that luxury if you're using JsonUtility
you should describe your API using OpenAPI, then generate a C# client for it. it will give you typed, blocking and async versions of all your method calls, named and strongly typed. you should also not login on the server - you shouldn't have a /login method that, on the server, calls AD FS, which is what you are doing right now
carefully review these examples on AD FS: https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/overview/ad-fs-openid-connect-oauth-flows-scenarios
you can use an OIDC (openid connect) asset for unity. unity also makes a package
good luck out there
MagicOnion also does this, if you do not want to author an IDL. it is compatible with unity and the M$ backend frameworks
Anyone seen an error like this before? TypeLoadException: Could not resolve type with token 01000149
I use my custom user authentication and authorization system.
in addition to this, the app is not single-sign on, but a VR application.
token coming from callback does not work in VR since headsets does not have deeplink. I looked over all third party sytems none of them provided OAuth2.0 system for VR
I have an array of Vector3 points. These point each have a corresponding bucket number 0,1,2,3,4,5,6,7. I need to sort these points based off its bucket number. I need to do this all within the Vector3 points array. What would be the most efficient way of doing this?
What is bucket number?
for me it is a which child of the tree it is going to go into. 8 Children total for each node.
Do you want to sort them in this order, for example: 000,001,002 ?
No the order within the bucket doesnt matter. Only that all the 0s or 1s or 2s are together
do you want to aggregate them into groups right?
correct
if so, just take a look into "linq with groups"
I will check it out
do you have any reccomendation for this JSON utility
I have to find a decent library and stick to it
Use Json.NET if you need anything advanced
JsonUtility is bare minimum
I just so happened to go down a rabbit hole to test Json.NET (using com.unity.nuget.newtonsoft-json) vs JsonUtility, in IL2Cpp
For the type of data I'm deserializing (~40 KB in size, up to 7 nested layers, strings floats ints arrays) Json.NET takes about twice as long, and trice as much GC.
JsonUtility is probably faster and less GC yes
it's optimized for that
People choose newtonsoft for the richness of its feature set
Yes which is the reason I'm looking into it in the first place, it would simplify a lot of my code.
It's unfortunate that the performance isn't acceptable for my game.
Maybe I should look into SG based libraries.
what's the use case for this serialization?
Deserialization, my game hits a lot of server endpoints, it's like death by a thousand cuts kind of deal.
deserialization of network responses?
Yeah.
Are you deserializing on the main thread?
Yeah
Should be able to deserialize on the background thread
before passing the data to the main
Not sure, I don't think each individual deserialization is big enough to warrant that.
you just said you do a lot of networking
surely that's worth a dedicated thread to do network requests and deserialization
if not a thread pool
Network requests are done with UWR
might have to change that
Oh, why so?
Tbh, the current performance with deserializing is fine, I'm just not satisfied with the ugly code because of JsonUtility, so I thought if Json.NET had comparable performance I'll just switch over
Because I don't think UWR gives you hooks to read the data from a thread that is not the main thread
Yeah the whole point of this investigation is to see if I can just drop in replace JsonUtility with Json.NET to clean up my code
If I have to rewrite a ton of stuffs to force Json.NET in, then I'm fine sticking with JsonUtility.
What I'm talking about has nothing to do with JsonUtility vs Json.NET
you can replace it either way
I'm talking about how to get your deserialization to happen on a background thread
so that it doesn't freeze your game
It doesn't already, the current performance is fine
It might if I switch over to Json.NET because it's slower.
as I understood there are three ways to do so;
- Async operations
- Coroutines
- Threads.
Event though Async operations are done the job in my project, the deserialized response should be cast through the application. And async opearations is eliminated.
- coroutines only help if you can break the work up somehow into small chunks, which can't be done for the deserialization techniques under discussion
- async operations only help if the work being waited for is being done in another thread
so it all kinda boils down to threading
when we use coroutine does the unity not create a new thread for it?
coroutines block the main thread
the magic of a coroutine is its ability to pause its work and resume later
you can only do that if the work you're doing can be broken up into small chunks
hmm. what about async operations. is that the same as acoroutines in terms of thread usege
noi
most async things you're thinking of use a thread pool to do whatever IO operation they're usually doing
if you do normal "coroutine replacement" async, that's just the same as a coroutine
what about creating new thread? Would I choose either of them in a new thread? (coroutines, async) Can I follow the process of the thread?
i don't really know what you mean
I have some .net Web APIs that my application is being interacted with. My workflow is, for example getting a data from server and deserializing it and casting through the events. So all subscribers can get the deserialized data.
and I am not sure what happens if I use coroutine, so it blocks the main thread!
Or is it possible to use "async" operations in case I want them to be casted by events.
@sly grove
what are "events" in this context and what does "casting through the events" mean?
and what does that have to do with threading and async operations
I made "triggers" and "receivers". So a "trigger" makes an API request (coroutine or async) and the incoming JSON file is deserialized and is sent to UnityEvents. All subsribers of the particular event get the deserialized unity game object.
none of the event stuff is really relevant to the discussion
it is actually
that's what happens after deserialization
yes but you can not deserialize a "Task" right?
is it possible?
i don't even know what it means
A Task is a handle for an asynchronous operation
what does deserializing it mean
converting Json to unity object
but the thing is do we not have to wait until the task is completed before we deserialize it?
it just my understanding.
let me give you an example just let me open the IDE
to be honest I don't understand what this discussion is about anymore
I'll summarize it in a minute.
this is another discussion, that is what approach should I use for my interaction with the backend and deserializing the response.
I made a TriggerManager, that uses UnityGameObject to make API request.
The response coming is a JSON. So I have to deserialize and use delegates to send the response object to all the subscribers.
If I use async operations before the operations is finished, I can not use delegates, right?
if I use coroutines it blocks the mainthread
if I use new thread, what should I use?
@sly grove
putting this here because I was told that this is handled by jit in C# but since unity compiles C# to C++ I'm pretty sure that means there is no jit because there is no runtime in the C# realm
is there a way to define methods (or something similar) that will be compiled inline? E.g. if I need to round to an int with MidpointRounding.AwayFromZero a lot I feel like it would be inefficient to do something likecsharp public static int Round(float num) { return (int)Math.Round(num, MidpointRounding.AwayFromZero); }I asked in a general coding server and was told that the C# jit will compile it to be inlined if it sees fit
with this example, if I'm doing something like rasterizing an image there could be hundreds of thousands to millions of jumps if it's not inlined
if you are using IL2CPP then yes there will be no JIT because that is AOT, if you are using mono then it will not be cross compiled to c++
but you can give the compiler help knowing you want that inlined with the attribute [MethodImpl(MethodImplOptions.AggressiveInlining)]
thanks
Is there a way to create a view over some mesh data that already exists in a native array somewhere? I have some mesh data I manage in native code and I would like to integrate it with the physics system, but I want to avoid the memory overhead of maintaining a copy on the scripting side.
Does anyone have experience running play mode tests from the command line for tests which also use InputSystem? I have a couple tests with mouse and keyboard input automated that are failing in a Jenkins build. Running in the local Unity editor is fine.
InputSystem testing stuff for reference: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.1/api/UnityEngine.InputSystem.InputTestFixture.html
is there an easy way to find particle system physics cost in the profiler
Hello i have a problem regarding web gl and the unity editor basically when I play my game in the editor everthing goes smoothly however when i play it in chrome there is one line of code that is not activating the line is checking if a list contains a certain variable and if it does it will play a particle system this is the line of code: if(newList.Contains(Song.timeSamples))
{
shotPS.Play();
Invoke("ChangeParticleSysPos", .2f);
}
Is there a reason you have to invoke?
But also make sure you're songs are in a resource folder or accessible to the build.
Look into addressables if you need to.
the song is still playing even though its not in resources is that normal?
A build will not contain random files unless you build them with the process.
just read that unity web gl doesent support timesamples 😦
spent a quarter of the day trying to figure this out too :/
so uGUI anchor don't compensate for parent scale :/ if your parent happens to have a scale of 10 then screen resized gets amplified by 10x so your UI stuff shoots off to space
You should not scale UI unless for temporary animation, that's what sizeDelta is there for
I'm not animating
Then you should never scale UI
this isn't really #archived-code-advanced
you are reinventing unirx
and unitask
@mint sleet
var subject = new Subject<Response>();
async UniTask<Response> RemoteGet() {
await UniTask.SwitchToThreadPool();
// whatever blocking api call you're doing without unitywebrequest
var responseJsonString = restClient.Get("some/url");
var typedResponse = JsonConvert.DeserializeObject<Response>(responseJsonString);
await UniTask.SwitchToMainThread();
subject.OnNext(typedResponse);
return typedResponse;
}
subject.Subscribe(response => Debug.Log(response)).AddTo(this);
RemoteGet().Forget();
// etc. etc.
does this make sense?
it makes sense but have not had an experience with that.
@undone coral
this Subject behaves like delegate?
the restClient object is a dummy right?
can I use UWR here for the request?
Never in my life have I seen c# code just switch to another thread
Does this inject code where you call that?
Why doesn't he just await the call?
Welcome to the magical world of unitask
So I've got a question regarding class design for more experienced c# developers. What cases would a property be better than a method for getting data? Take the following simple example:
private Rigidbody m_rigidbody;
// Option 1
public Vector3 Velocity
{
get { return m_rigidbody.velocity; }
}
// Option 2
public Vector3 GetVelocity()
{
return m_rigidbody.velocity;
}
What are the fundamental differences between these two, especially in a unity context. Most discussions found online are for regular c# development
They are the same thing, almost literally
"Unity context" doesn't change anything in this regard. You can just read the general C# discourse.
So if they are the same in that sense, from a design perspective, what do you think are their respective usecases?
They're the same thing so use cases are also the same
If the method literally just returns a value then a property is generally used more often.
Also I would write both like:
public Vector3 Velocity => m_rigidbody.velocity;
public Vector3 GetVelocity() => m_rigidbody.velocity;
As they are single-line
The benefit of a property would be that you could easily add a setter and the API wouldn't then have SetVelocity and GetVelocity methods, which would seem silly
They're the same
c# lowers properties into methods
So the getter of a property becomes GetValue(), and the setter becomes SetValue()
Small correction: they're not lowered into them, but somewhere whilst compiling it happens I believe
Only benefit of manually defining a set method would be that you have more freedom over the return value, properties and/or whether it's async or not
Same with the get method
But how does it work?
Does it inject code on spots where it is called?
though the difference between a property with a get and a method i find i sometimes will choose based on how much work it does
feel if something is a property it should not be doing very much logic in the getter, and be safe to get often. If it was a expensive call i would make it a method and expect the caller to cache the result
yes
restclient would be something out of the C# ecosystem
Subject is a term of art, it is what it is. it is a mailbox. it is both a thing you can send messages to and a thing you can listen to
the actual class exists
no
tasks are not threads
tasks aren't state machines
tasks are a method and a promise
they are a javascript Promise . they are a Runnable + CompletableFuture in java
its just a handle to keep track of work that may or may not have happened yet
use methods when there are side effects
property setters tend to have side effects. for example text in a textmeshpro component
yes but you wouldn't switch threads. you don't need to touch threads for UWR
Why would it inject code, awaiting Task can change thread by the C# spec.
Only in Unity, they override SynchronizationContext, and it forces Tasks to run at main thread by default.
It does not force any task to run on the main thread, it just makes it more explicit where it runs. A Task.Run will always run on the threadpool even with unitask
Yeah that's why I said 'by default'
I think it's more of using Task.Run is explicitly specifying that it will use threadpool?
semantic wise
If you want to run on threadpool with unitask you can make it super explicit with UniTask.RunOnThreadPool
That’s just the default task launcher and semantic wise does not specify where it runs (does not have to be the thread pool but is generally expected to not be the main thread)
the danger with unitask is in doing worker tasks on the main thread, those should be avoided
Hello there, our Unity Game always shows unity crash handler when calling Application.Quit(), and it is always very slow to exit (In standalone build), it's there something we need to manually dispose before calling the method?
Calling Application.Quit() two time reduces the overall time for closing the application, but the crash handler persist.
We are using IL2CPP
Unity version is 2021.3.5 f1 LTS
it sounds like you have a real exception
you should not be doing anything in OnApplicationQuit
I didn't
then it soundsl ike one of your libraries is making a real exception
The thing is, the Dialog with your game icon and red "!" shows, but there is not follow up window(the one that shows that actual crash info)
Let me check the log
okay
i think you can googl ehow to find the exception it is throwing
you can also disable fast exceptions in il2cpp
and maybe see it that way
you can also build for mono - it will probably reproduce in mono, and you can easily see the issue with the debugger
it has nothing to do with libraries or whatever
you just have a bug in your code
Is there a way just "KILL" the whole game process?
System.Diagnostics.Process.GetCurrentProcess().Kill();
Just froze the game
what is your objective?
you used the word "just" so you are in trouble
is this your project? someone else's project?
This is my product... when I call application.quit() all i want is to kill the game
TMP raise the exception....
I see
you should build to mono
a development mono build
and see the line numbers
you have a lot of bugs
What do you mean by bugs
hmm
I mean, I understand the bug definition
Is there a way to close the game no matter what exception it raises?
yes
Process.GetCurrentProcess().Kill();
I tried that, in mono this line close the game perfectly, but in IL2CPP it just froze the game
lol
I have addressed the exception... by setting up a huge try catch block
And the issue persists....
@trail cloak Don't post off-topic images
sry
how can i get a float to change from 0 to 1 in 2 seconds
0 to 1 in 2 seconds means : 0.5 per second
So t += Time.deltaTime * 0.5
Also don't cross-post + not an advanced code issue
how can i set starttime to time.time
convert?
oh sry change
No
oh
You need Clamp(n, 0, 3)
ok
More generally the formula to go from n to m in x seconds would be Clamp((m - n) / x, m, n)
In code that would be
Set start to n
Set speed to (m - n) / x
Increment start by speed until start equals m
just quick question if anybody did it, how to show list of Interface in inspector?
tried seriealizeReference but doesnt really work or i dont understand
Will try and dive into custom inspector as seems best choice but I also heard about GIT serializers as free version of odin
So if anybody did it, how?
Not sure where to put this, I have a click and drag puzzle game, I have this code where I click and drag an object to place it. The issue is SOMETIMES clicking on one of the pieces doesn't work. Meaning a piece can't be clicked on at all. it's a prefab and the other 2 pieces can be dragged. I put Debug.Log into the OnMouseDown even and the piece that cannot be dragged does not register the OnMouseDown event. The prefab has a polygon collider 2D. It starts at a random rotation of a factor of 60 degrees, but pieces have been unclickable at different rotations. I'm not sure what else would make clicking not register
When you encounter a piece that is unclickable, have you tried going into scene view while the game is running and investigating whether anything is in front of the object on the Z axis that could be blocking your click?
To be honest, instead of debugging this, it might just be faster and easier to replace your usage of OnMouseDown with a MonoBehaviour implementing IPointerClickHandler (and associated interfaces). Those are just going to be more reliable in general.
Z is always 0, there are not multiple on top of each other either, the clickable object is the only one with a collider
Yeah, without any visibility into your project, there's no way to tell what's going on. A lot of things come to mind as potential causes though. Is the collider and the object that is moving on the same GameObject? Is there some discrepancy there? Do you have a graphics raycaster 2D? Which Input System are you using? But again, if I were tackling this, I'd just use the EventSystem interfaces since they literally give you dragging functionality on a silver platter.
Ill look into the Ipointer stuff and see if that fixes it. Thanks
Good luck! I hope it does. There should be a plethora of examples of those interfaces available online but lmk if you run into any issues.
See what else you have on that item, you might have icon or other object or something with raycast on
in that case raycast can not come down to the object
for example if you have image, some icon on inventory cell, icon will block it
I only use a raycast to place the object onto its slot
Im dropping the pieces onto a board
what do you mean
problem is only on first try?
or works only when you first time pick it up
Either you can pick it up or not
well cant help like this, but consider that problem, maybe you have something blocking the object
mousedown still uses raycast to handle things
Can anyone help me? Im trying to add a force to a ragdoll and everything works. No errors or anything it just refuses to add any force of any kind. Losing my mind over this. (is kinematic is off too)
Hey, I am creating a square shape mesh from points on a wall. Everything works as far as creating the mesh goes but for some reason when I create the mesh and add a collider it adds it in the wrong place. Upon investigation, I found that the pivot of the Mesh I had generated was at Vector3.zero while the mesh was where I placed the points. Am I missing something
why are defining a function in another function
that's possible?
I added that method for organization purposes
@regal olive try putting debug.logs everywhere
HAve you tried without that nested method?
see if the logic is even executing
or maybe AddForce At Position?
Both without the method, every force type, and have determined the issue to be the hit body part just not accessing the rigid body
though it should
I just get no errors and the debug lines play. Its just refusing to add the force. It has to be accesssing it from the reason Im not even getting a object reference error
what if you wrap like this
if(TryGetComponent(out EnemyTrigger eTrigger))
{
Rigidbody rb = enemy.GetComponent<RigidBody>();
AddFrorce(rb);
}
else
{
Debug.Log("Enemy Not Found");
}
void AddForce(Rigidbody enemyRB)
{
rb..AddForce(transform.forward * fireForce);
}
Can someone who is experienced with unity and confident in their abilities please send me a DM... I have a huge question that has been really stuck on my mind and it would probably be simple for you to explain ❤️
if you want help with things you should ask publicly what it is. will expose it to more people that could possibly help
and its not putting someone on the hook
I tried in the beginner channel but no one knew and I don't want to bother advanced with something so simple D:
but I can if you think that would be okay?
okies well, I just want to know if it's possible to translate the language of an asset into english. I want to use a set of scripted assets in unity but it's in a language I can't read
Is there an easy way to implement a copy constructor for a custom struct?
The websites I've found are quite hard to read... terrible formatting
What is your goal? For deep copy?
does deep copy even make sense for structs?
structs always copy
you can't pass them by reference
they are values by nature
unless for some weird reason you have a reference in your struct
ref and in want to know your location.
That's good to know
well thanks for all the help. time to use google. lol
thats fair - let me rephrase
you shouldn't pass them by reference (normally)
i`m having this errors on a headless server build. Is it possible to disable shaders and rendering?
I see
I just assumed it injected code since that is possible too
Hello Unity devs!
I want to create an app that is going to work on background with only exception that a small icon will appear on the desktop/menu.
The idea is to create a bot who can talk to you like on a phone call, all you see is your regular desktop/menu, which is usable despite app running, and an icon that indicates that the app is running.
My question is, is it possible to do it using Unity?
If yes, could you please guide me on that?
How can I describe this in a few words so that I can google things myself? (instead of typing the whole story to the search bar)
I am open to any other ways of doing it, not limited to Unity.
@lyric dragon i think its a better option to do it in another way
Dont think unity is the best choice for that
Do you have any ideas how can I do that?
And also, why is unity not the best choice?
Unity is designed to render graphics and work on its own on device. Your app would require lots of plugins so majority of code would still be some form of java (if android).
Learn android studio (kotlin) with android API would be best option. iOS has its own version of swift i think.
Have a look at how to create a Windows service. They can run in the background and respond to requests from e.g. an icon in the taskbar.
Shit i thought talk was about mobile app :D, same applies.
So, what you want to say is that there is no possible way of doing that in Unity?
Hi, anyone know if cache-ing and reusing NativeArray with Allocator.Persistent and destroying OnDestroy is better than creating a Allocator.Temp Native array and disposing it every frame?
It is possible, for sure, but i think lots of it would be system API which requires for you to use some libraries or use your own.
I cant say how hard it would be, you need to do your own research but if its background app without much UI
Iam sure it would be easier to do C# application.
Thanks @flint wraith, I am going to take a deeper look at it
I just wanted to know if anyone did this before, if yes, what is the easiest/fastest way of doing it
You saying that it is possible gives a motivation to go in that direction somehow, appreciate it
After look into the dump file, we found out that the crash happens on the C++ side (IL2CPP VM)
which is inside the Thread.cpp file under 2021.3.5f1c1\Editor\Data\il2cpp\libil2cpp\vm
Change line 255 into exit(0); makes the game shutdown normally
@fresh salmon I'm a bit confused, im not very familiar with the clamp function
i want it to go from 0 to 3 in 1 second
Clamp returns the clamped value
ok
Mathf.Clamp(5, 0, 3) would return 3 because 5 > 3
You don't use the return value Clamp returns
like this?
What's inside the clamp is also wrong though
The speed, which is (m - n) / x itself, should only be computed once
Before you start moving / looping
hmm i see
what about this
Nope, the speed calculation makes no sense inside the clamp
Do it once, in Start or whatever
I have a question! Its not about a specific snipped of code, its more of a general concept that I would like to understand.
I would like to understand how to apply object oriented programming to unity. But I am not sure how to do it really?
Lets assume I want to create a class for playable characters. A character consists of more than just one script. My current prefabs for characters contains several scripts and components: health, melee combat, special skills, rigidbody, and so on.
How do I utilize object oriented programming in Unity for characters? or in general even
Then when you loop, increment the value of start like how you're doing right now, and clamp the result of that
then what should i clamp?
bro i think im not advanced enough for my code
Increment start by speed.
Clamp start so it stays between n and m
start, m, n, speed are all computed once. Then you only change the value of start
this shoud be fine right?
No
Assign the result of Clamp back to start
Then you'll see that start will gradually go from m to n
ok but then, i have my variable slowSpeed which is the actual speed then, what should i assign for this variable?
or should it just be start
Yeah that would be start, that's now badly named because after the first iteration it's not a start value anymore
Name it value or progress or anything else that makes sense
Yeah you're not reading what I write
oh it should go from m to n
speed = (n - m) / x
Where m is start value, n end value, x the number of seconds to cover that distance
Swap m, n in the speed calculation
You have it bacwards
And same thing for inside the Clamp, backwards too
is it correct that the clamp function to declare start should be in update?
Yes, that's what prevents your value to go below m or above n
the problem im having now is that its not working
And then rename to make the variables clearer on what they are
start => value
m => start
n => end
x => time
My goal here is to detect when player is touching a wall, without using oncollision events. I'm using a slightly bigger sphere than the radius of capsule collider and checking with spherecastall. Now, the strange thing is that it detects as it should, meaning when I get up close to a wall, it successfully finds the colliders of the walls as I can print out the name of the object that collider is on. The problem however, is that all raycasthit results has both a position of (0, 0, 0) and a normal value pointing straight up, even if the object is rotated. The code is nothing special, each and every debug print says that the point of hit is (0,0,0)
What you're describing is literally documented behavior. Read the docs.
https://docs.unity3d.com/ScriptReference/Physics.SphereCastAll.html
hi i wanna transfer data between two clients in photon
its my ui
and i want when i wrote any msg and send it it automatically shown to all the clients
in scroolbar i am using prefebs that are instantiate
I would like to repeat my question from earlier today because I got no answer yet
I have a question! Its not about a specific snipped of code, its more of a general concept that I would like to understand.
I would like to understand how to apply object oriented programming to unity. But I am not sure how to do it really?
Lets assume I want to create a class for playable characters. A character consists of more than just one script. My current prefabs for characters contains several scripts and components: health, melee combat, special skills, rigidbody, and so on.
How do I utilize object oriented programming in Unity for characters? or in general even
sounds like you're already doing it correctly
am I ?
I assumed if I want to use object oriented programming I would need to make something like a common character class and develop it further from there
You don’t have to. Composition is preferred over inheritance
Polymorphism is only one aspect of OOP
It is not the only, nor the most important aspect of it.
Not sure why people equate OOP with polymorphism
The main features are organization of data into objects which have data and behavior associated with them, encapsulation, and the single responsibility principle
So in case of unity or game development in general, it is not adviced to follow coding principles blindly?
It is never advised to follow coding principles blindly in any development. You do not need more abstraction than you need, you do not have to force your code to fit specific pattern. Programmers need to understand principles and patterns, then apply appropriately.
I see, thank you for the advice
I thought it might be the next step in which direction I could improve my code. I noticed yesterday that I use if and for loops for the most part, like a wall of it
That made me think to maybe consider preparing a list of functions somewhere in a common class and then use those
Principles also change and evolve and some ”generic best practices” are often pretty idealistic
Like inheritance and polymorphism used to be solution to everything looong time ago and nowadays everything is gazillion stages of abstraction, minimal classes and dependency injection… and the inheritance and polymorphism based design is almost frowned upon
Hey, how I can make Unity actually use the .used property of the event?
So that in the PointerClickHandler I can decide to ignore a specific event?
I've tried everything I could think of and even looked into the source code for the package and it looks like it's not used at all
It is depends on your case, you can implement interface instead of base class if you want to make your code less coupled. Then you could do something like GetComponent<IDamagable>() or GetComponents<ISkill>(). Not sure what kind of ifs and loops you are having, though.
interfaces are still not a silver bullet, but good tool to implement things with minimum coupling
call .Use()?
Nope, even if I don't call it, the event is stopped
On this screenshot, I've taken a bunch of triangles on my mesh that matches certain criteria.
From said triangles, I've extracted it's normal.
Out of the infinite rotations the Red (X) and Blue (Z) lines can be, how do I determine the one where the red line more closely points to the global right?
The triangles can also be perfectly vertical, in which case the red line can never point to the right, in which case I want it to point upwards
How do I even go about doing this? Currently I make the red line point to 'the rightmost point of the triangle'
So you want to go from:
three vertices of a triangle
to
a rotation wherein the "up" direction points towards the triangle's normal, and the "right" direction points along the global x axis as closely as possible?
exactly
Do you mean you want to let event to bubble up?
I think something like this should work?
Plane p = new Plane(p0, p1, p2); // plane from triangle points.
Vector3 normal = p.normal; // grab the normal
Quaternion q = Quaternion.identity; // x / y / z all aligned with world axes
Quaternion result = q * Quaternion.FromToRotation(Vector3.up, normal);```
Not exactly bubble up, but I would love for it to be ignored by the object and be passed to a next one in the line
as if it was never handled
You might want to disable raycast target itself
But then the object won't get the event
Turn it on only when you need it?
Seems to work perfectly for what I need, thanks
I basically want to:
public void OnPointerClick(PointerEventData eventData)
{
if (... some condition ...)
{
...
eventData.Use();
}
}
Ik, but your situation is more about what object the raycaster hit, than propagating event
Even if you 'ignore' the event, it only will bubble up, not finding another raycast target
Exactly, what I would want is for the event system to take a second item on the list of hit objects and to send the event to it
So your option is disable raycast target or playing with raycaster's blocking mask
Or creating own event
But I cannot do that from within the event itself
You cannot do much if event is already fired for the target
What I want exactly is to have a TMP text with links
If the link is hit, do stuff. If not, click element behind the text
But it's not possible as I would have to have the collider on the TMP text itself and then when the click happens I can check if the mouse is over the link
You could make TMP child of the object behind the text
Okay, but then how do I propagate the click up?
I remember doing it with SendMessageUpwards
Okay... ewwwwwwww
I would rather GetComponentInParent than SendMessageUpwards
Something like this should do it
ExecuteEvents.ExecuteHierarchy(transform.parent.gameObject, eventData, ExecuteEvents.pointerClickHandler);
Yeah, that sounds native
Okay, there is a sort of issue with this approach
It will work for this case tho
But if I have this:
Where Red is a child of Blue
I cannot differentiate between clicking both and clicking only red
But in this case it's fine
Yeaah. That case is more complex
Still, the lack of robustness of this system is astonishingly bad
I remember implementing somewhat similar thing to that case with CalculateRelativeRectTransformBounds/RectangleContainsScreenPoint , but it does make things complicated
It's annoying because the logic for it is not that hard when done in the system itself
Standalone Input Module already gets a sorter list of hits
So it should be as simple as
"Send event, if not consumed repeat for next object from the list"
Which one runs faster for speech recognition, PhraseRecognizer or DictationRecognizer
I'm talking about for simply wanting to pick up on 8 keywords
I'd imagine PhraseRecognizer is faster for that right
(And I think Godot has it, so no pressure... but)
Sadly I also doubt that Unity team monitor this discord 😂
They should, at least from time to time. It would point them at annoying details of the engine that turn it from a good engine into a fricking trap
unfortunately that is not implemented in ugui
you can extend it yourself and call .Use() and check used on the base event data in your scripts
you can also create an extension method for BaseEventData called PreventDefault() that un-uses, and in your event system subclass, always call Use()
The issue is that I would have to write an input module for the event system from scratch
you can extend an existing one
why from scratch
Well, not from scratch fully. As I can copy paste code
But I don't think I can just override
Hey y'all - I'm trying to do a WebGL build of my game, and I have a bunch of code that wouldn't ever work in WebGL. I have all of it inside
#if !UNITY_WEBGL
using Evil.DesktopOnly.Code;
// .. use evil desktop only code
#endif
but when I make a WebGL build, Unity still tries to compile all the code from the Evil.DesktopOnly.Code; namespace.
The build works fine if I literally remove the folder from my Unity project.
Any ideas on how to prevent the compiler from reading that directory when I'm making a WebGL build?
Maybe negate that #if condition?
sorry, bad example - it is negated in my real code 😅
I think it's more about assembly reference?
Your code is not compiled by each namespace. It's compiled by each assembly.
aha, those words are enough for me to google from. thanks 🙏
Yeah if you have asmdef for your desktop code, you can simply include/exclude platform from the inspector
it worked, you're a legend @jolly token
Hey ı just wanna ask how to ı make this splines and real-time texture painting in game like army commader referance : https://www.youtube.com/watch?v=6AO6TSes_0U
Army Commander - Gameplay Walkthrough Part 1 Tutorial (iOS, Android Gameplay)
Army Commander - Lion Studios
👍Join And Become My YouTube Member https://www.youtube.com/channel/UCRf4-iCB2SXg9OsuFauzlsw/join
If you enjoy the video, drop a like!
🔔Please Subscribe
Pryszard Gaming https://www.youtube.com/channel/UCRf4-iCB2SXg9OsuFauzlsw?sub_confirma...
Not sure if that is "real-time texture painting". Do you want something like this?
https://assetstore.unity.com/packages/tools/particles-effects/shapes-173167
how do ı use this asset for army commender splines and texturce changing in real time
You need to be more specific what part of that game you are referring as "splines" and "texture changing"
All I see is some vector graphic drawn on top of floor mesh
Sorry I am not native speaker
Me neither
in enemy section you can see there is some changes based on where are the enemies are
enemy area growing or decreasing
ı want this in my game basicly
i think this is it
Yeah with the asset I referenced, you can make vector graphic with your preferred position, shape and rounding
You can simply draw on top of floor, you don't have to change texture
oh ı see
is there a tutorial for this
ı watched the assets videos and some videos on youtube but i cant find anything about my problem
They have documentation, https://acegikmo.com/shapes/docs/
Basically the game is making vector graphic with the area enemy is occupying
So you would want to create polygon with that
Or polyline, whatever shape you are thinking
Does anyone know off-hand what unity does in terms of automatic management of textures on the GPU? Do I need to manage this myself by creating/destroying texture objects as-needed, or is this kind of taken care of in the background and I can just worry about CPU memory constraints?
For context, I'm working on a tile streaming system in which a practically unbounded number of textures might be created, but of course only a limited number are required at any given time.
public bool inProcess = false;
private void Press()
{
if (!IsActive() || !IsInteractable())
return;
UISystemProfilerApi.AddMarker("Button.onClick", this);
m_OnClick.Invoke();
}```
Hello this is Unity's own Button component.
I want to make the Button deactivated when it is clicked and it will wait for event response to be enabled again.
interestingly, I can not reference inProcess attribute in the Press function. it does not show up.
Do you have any idea why?
Can't reference how and doesn't show up where?
@devout hare
What does it say if you type it anyway?
just it leaves it white text.
but what's the error message
is this a coding question or editor configuration issue?
I mean it has to be valid anyway, like inProcess = false;
so editor configuration issue then
hmm what should I do?
configure the editor ¯_(ツ)_/¯
🙂 ok let me google it. have not done it before. Thanks
How about this.inProcess?
What if you rename to _inProcess?
Restarting Unity? 🤔
No there is another issue do not know why
I can not even extend with my custom interfaces. @random dust
is the Button protected or something?
Are you trying to change the base Button class of Unity?
If you're I'd really not do that, and just make a class that extends button
ButtonExtended : Button
Yes, I'm doing this. I realized after I thought a bit.
how can I override the interactable property then?
@tawny bear
Can't you just do an override of the original function in the inherited class?
Without taking the base
Ive discussed it with my collogue. Decided to sticik with very basic solution. We will use Actions.
Thanks Wumpie
I'm not sure how this solves your problem
I'm getting an error related to MagicLeap in my cdoe when building my AR application. Autoconnected Player "Autoconnected Player" A scripted object (probably UnityEngine.XR.MagicLeap.MagicLeapSettings?) has a different serialization layout when loading. (Read 52 bytes but expected 76 bytes) Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
Can I remove this framework without breaking the rest of AR Foundation (either ARCORE and ARFOUNDATION)
I'm also not sure what your problem even is kek
Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
Did you?
I cant find a single instance where I have.
ran a search operation over the entire project, im inclined to think its MagicLeap causing this. I do however find that extremely unlikely to believe
probably UnityEngine.XR.MagicLeap.MagicLeapSettings?
Check this object
Or thing
Not sure what it is
its part of the AR feature in unity
private Button _button;
void Start()
{
_button = GetComponent<Button>();
_button.onClick.AddListener(Deactivate);
}
private void Deactivate()
{
_button.interactable=false;
}
}```
And I send the button from my trigger class. when the API request is done. it just enables the attribute
Sometimes must think basic.
What happends when you try to access that interface's definition?
Does it just not load?
I would assume it's internal at best
it did not load, I'm mixed up why
You should unsubscribe the Action as well
private Button _button;
void Start()
{
_button = GetComponent<Button>();
_button.onClick.AddListener(Deactivate);
}
private void Deactivate()
{
_button.interactable=false;
_button.onClick.RemoveListener(Deactivate);
}
}
@mint sleet
This assumes you won't need to reuse it again though
Otherwise yeet it in the ondisable
Also, @mint sleet you can make an extension method for buttons
It saves it back to the original prefab?
Hi guys, I am having a bad issue and i don't really have how to solve it.
Basically I'm trying to retrieve some api requests on my game and on the editor it perfectly works, the problem is that in each builds of my game (iOS, Android, WEBGL) the raw json body of my request is encrypted not letting the api work as intended, do you have any clues on what is happening or any experiences on how to fix it?
Please let me know, thank you in advance
hello does anyonw know how to get the lobby type in steamworks?
Need some linear algebra help in #1027941647880814632
About an enemy mirroring a player for a VR game
You are literally trying to edit readonly IL code… which is just decompiled from Unity assembly for debug purpose only. It’s not about basic or advanced, you are not supposed to edit standard library code anyways.
What do you mean “encrypted”, did you try to log the response json and errors?
Thanks for the response but I fixed it.
It was an obuscator that i installed that for some reason decide to encrypt also the API call i just tun off the obfuscator
This might be more of a maths question, but maybe someone can help.
I have a Grid and want to convert any Vector3 to the exact Vector3 world position of the cell.
Currently, I simply just do CellToWorld(WorldToCell(vector)), but I can't help but think there might be a smarter way or a function I'm missing lol
If you were to write that call out (meaning copy paste the contents of those two functions together so they would do that in a single function) - I suspect you will see some steps that can be "canceled-out".
Question: In this constructor: public Texture2D(int width, int height, TextureFormat textureFormat = TextureFormat.RGBA32, bool mipChain = true, bool linear = false); what exactly does the mipChain parameter do? Is it creating mip-maps for this texture? When does that happen, is it every time I do texture.Apply()?
I dont know if anyone noticed that EditorGUI.changecheck does not catch mass populating arrays/lists in 2021+
so Instead you can use this:
I actually wrote this in 2020, so needs to be tested in 2021 😄
Tested it in 2021, it works!
hey it's glurth
i think it's platform specific
is there a CreateMipMaps method in unity?
