#archived-code-advanced

1 messages · Page 20 of 1

upbeat path
#

to access the DB use Application.streamingAssetsPath

arctic lake
#

Or will they need to create a new table themselves

upbeat path
#

if it's in streaming Assets it will be included in all downloads

arctic lake
#

Kk, thanks again

dapper cave
#

if we want code to execute while in prefab edit mode, is there an event we can subscribe to? currently using OnDrawGizmo 😂

regal olive
#

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

hallow elk
#

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.

dapper cave
undone coral
#

and is this built in pipeline?

undone coral
timber flame
#

:/

hallow elk
#

This is Built in pipeline. Yes, we use source control.

hallow elk
#

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.

topaz pond
#

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.

icy aspen
#

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

frank socket
#
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.
icy aspen
#

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)

chilly nymph
regal olive
#

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)

regal olive
#

enum?

regal olive
chilly nymph
regal olive
regal olive
#

confused

#

wait

#

fixed

undone coral
#

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

regal olive
#
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

quiet drum
#

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

regal olive
#

ok

#

ill use that

regal olive
#

huge help

#

I forogt how to do that

#

k done

#

uh does anybody know how 2 fix

shadow seal
shadow seal
regal olive
#

I might be wrong

shadow seal
#

You are entirely wrong

regal olive
#

ok good

shadow seal
regal olive
#

okok

#

but do u know how to 2

#

fix

shadow seal
#

Yes, delete it and start again

#

You clearly do not know any C# syntax

regal olive
shadow seal
#

So go and learn it first

regal olive
#

then rewrite what the youtube comment said?

shadow seal
#

If it said that, ignore it

regal olive
frank socket
regal olive
#

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

shadow seal
#

No, you need to put some effort into learning the language

shadow seal
#

Only then can you understand the issue

regal olive
#

but were 2 start

frank socket
regal olive
regal olive
#

k

shadow seal
regal olive
#

now I kinda feel

#

sad

#

about my stupidity

#

:((((((((((((((((((((((((((((((((

shadow seal
#

It's not stupidity, it's just a lack of knowledge

#

Not knowing something doesn't make you dumb

regal olive
#

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

humble leaf
regal olive
humble leaf
#

That's what happens when you bury your own conversation. 🤷‍♂️

regal olive
#

💀

west scarab
#

Sometimes I feel like this server could really use an enforced thread system, so many people spam channels it's nuts

jolly token
west scarab
#

Especially since it makes finding archived threads easier imo

jolly token
#

I think threads are not used because it is hard to 'bump' and easily forgotten when scrolled up

west scarab
#

Yes, that's why the forum system is cool, because it just uses normal threads, but adds an overview and a search functionality

jolly token
#

Now I hope admins hear us pray 🙏

shadow seal
young wraith
#

Hi I'm having an error "IndexOutOfRangeException: Index was outside the bounds of the array "

#

I think I'm missing something

jolly token
young wraith
#

I think the problem is in Color[] pixels = _templateDirtMask.GetPixels();

#

I think it reach its maximum size?

jolly token
# young wraith yup

You should put breakpoint and see the each variables are same as you expected

young wraith
jolly token
young wraith
jolly token
snow flint
#

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

jolly token
dapper cave
#

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

livid kraken
# dapper cave How do you bake normals of a Mesh.MeshData inside a job?
        {
            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
maiden turtle
random dust
#

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 🤷

livid kraken
fresh salmon
#

Plus, it wasn't C# but shader

tawny bear
#

Oh my bad

#

If it was C# just always put highlighting on it though

livid kraken
#

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

tawny bear
#

¯_(ツ)_/¯

snow flint
#

thanks for all the tips guys! i will do some thinking

mint sleet
#
     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.

obsidian glade
random dust
#

Might not even have to be generic, but I assume the type is harder to retrieve if it's passed as a derived type

mint sleet
#
        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

random dust
mint sleet
#

what method are you talking about

random dust
#

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

mint sleet
#

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

random dust
#

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

mint sleet
#

Thank you @random dust

random dust
#

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>

mint sleet
#

yes, sounds reasonable

random dust
#

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

mint sleet
#

I do not like it

random dust
#

And you will have to add a second callback in case an error exists, with the exception as parameter

mint sleet
#

I return a IResult

random dust
#

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

mint sleet
#

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

high gulch
#

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

trail cloak
#

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

undone coral
#

or to use reflection for serialization

undone coral
#

clients can be generated from Interface Description Language. a common one is OpenAPI

mint sleet
mint sleet
#

why? did you put that emoji

#

where am I missing

sly grove
#

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.

mint sleet
#

but for example playing with a character does not block anything at all?

sly grove
#

wdym "playing with a character"?

mint sleet
#

play with a fps character in the play mode for example

sly grove
#

All code you write is blocking

mint sleet
#

oh my boss calling me

#

I want to discuss with you this 😄

sly grove
undone coral
#

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

random dust
#

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

woeful remnant
#

Has anyone done any work on scripting additions/modifications to the unity asset input pipeline?

undone coral
#

then i can point you to a specific example maybe

woeful remnant
#

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

undone coral
#

got it

#

you can look at the HDRP repo for examples

woeful remnant
#

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

undone coral
#

probably something like this

woeful remnant
#

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

undone coral
#

is that helpful?

#

the unity api is pretty straightforward here i think

woeful remnant
#

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?

undone coral
woeful remnant
#

I've been trying to find good information on this and haven't been able to, but they aren't just Mesh objects

undone coral
#

hmm

woeful remnant
#

I've explored all the Mesh classes, and SkinnedRenderers

undone coral
woeful remnant
#

to try and figure out "what" they are, the inspector isn't super helpful in that regard either

undone coral
#

is this helpful?

dapper cave
woeful remnant
#

@undone coral Hopefully, will check it out thanks!

pastel wagon
#

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++
dapper cave
#

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?

sly grove
#

0, 1, 2 is the first triangle, 3, 4, 5 is the second, and so on.

dapper cave
sly grove
#

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

dapper cave
dapper cave
sly grove
dapper cave
sly grove
#

also what mesh are you starting with and what are you trying to do exactly

dapper cave
#

alright, switched to tStart, ur wirght

#

starting mesh on the left, trying to remove all facets that are pointing down

undone coral
pastel wagon
woeful remnant
#

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?

pastel wagon
frank socket
#
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.
woeful remnant
#

then you probably need to look at the GetSteepness function instead of that code

#

also not sure if this qualifies as code-advanced

frank socket
#

?

#

I didn't make GetSteepness if that was what you thought.

woeful remnant
#

That doesn't mean it isn't the problem

#

is it part of some copied and pasted code?

frank socket
#

The code I sent?

woeful remnant
#

ah ok GetSteepness is part of the base Unity for terrain specific objects

sly grove
woeful remnant
#

instead of doing just Debug.Log(steepness) you should add in the values being passed to GetSteepness

woeful remnant
sly grove
#

just make one prefab and assign the mesh at runtime to the renderer

woeful remnant
#

You would need to make a prefab per animated mesh though, correct?

frank socket
woeful remnant
#

due to the bone/constraint differences

sly grove
#

and in either case no

#

you can use a base prefab and prefab variants at worst

woeful remnant
woeful remnant
woeful remnant
frank socket
woeful remnant
#

@sly grove have any good resources on reading up on how to use prefab variants for dynamic instantiations using different mesh/skeletons?

sly grove
#

no

#

too bespoke

woeful remnant
sly grove
#

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

woeful remnant
sly grove
#

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

woeful remnant
#

mmm

sly grove
#

it's easier to do this in the editor via prefab variants than through code

woeful remnant
#

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

sly grove
#

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

pastel wagon
sly grove
#

but the art and animation part if it needs to be different for each thing... it needs to be different

woeful remnant
#

well honestly seems like the artwork is faster in that regard, depending on the artwork style of course

pastel wagon
woeful remnant
#

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

woeful remnant
frank socket
pastel wagon
pastel wagon
#

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

frank socket
brittle pumice
#

hello

#

is there a way to get the guid in OnPostprocessModel method

sly grove
jolly token
brittle pumice
#

do i use AssetDatabase.TryGetGUIDAndLocalFileIdentifier

#

or

#

var guid = AssetDatabase.AssetPathToGUID(assetPath, AssetPathToGUIDOptions.OnlyExistingAssets);

sly grove
#

Any references to game objects or meshes will become invalid after the import has been completed

#

So there isn't really an asset yet.

jolly token
#

Yeah I suppose GUID might not even exist at that point

brittle pumice
#

ok 😦

dapper cave
#

is there an Update even that doesn't get affected by Time.timeScale = 0 ?

gray pulsar
sly grove
#

FIxedUpdate does.

dapper cave
#

thanks, any way to get a rigidbody not be affected by timescale=0?

sly grove
#

A specific Rigidbody?

#

You trying to make Braid?

dapper cave
dapper cave
sly grove
chilly nymph
#

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.

dapper cave
#

it's weird that mecanim doesn't get timescaled, it should freeze up

sly grove
dapper cave
#

CharacterController freezes on timescale = 0... mmmm... might have to make one myself

sly grove
dapper cave
dapper cave
#

i wonder if one rigidbody can be forced to update

sly grove
#

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

dapper cave
#

come on rider, auto write the files!

dapper cave
#

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

gray pulsar
dapper cave
brisk pasture
#

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

lapis pond
#

Hello people 🙂

Does anybody know whether Unity does or does not support proxy authentification when using WebRequests and Addressables?

scenic forge
#

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.

sage radish
scenic forge
#

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.

mint sleet
#

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?

sly grove
#

it's literally just creating classes that match the structure of your json

mint sleet
#

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!

mint sleet
#

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

sly grove
#

but with a different structure?

mint sleet
#

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

sly grove
mint sleet
#

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.

sly grove
#
        [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

mint sleet
#

I wanted to have them in structure. But I do not know if it does worth to make it.

sly grove
#

this could be done with some custom json deserialization logic, but you don't have that luxury if you're using JsonUtility

undone coral
#

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

timber shadow
#

Anyone seen an error like this before? TypeLoadException: Could not resolve type with token 01000149

mint sleet
#

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

plain gate
#

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?

mint sleet
#

What is bucket number?

plain gate
#

for me it is a which child of the tree it is going to go into. 8 Children total for each node.

mint sleet
#

Do you want to sort them in this order, for example: 000,001,002 ?

plain gate
#

No the order within the bucket doesnt matter. Only that all the 0s or 1s or 2s are together

mint sleet
#

do you want to aggregate them into groups right?

plain gate
#

correct

mint sleet
#

if so, just take a look into "linq with groups"

plain gate
#

I will check it out

mint sleet
mint sleet
#

I have to find a decent library and stick to it

jolly token
#

JsonUtility is bare minimum

scenic forge
#

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.

sly grove
#

JsonUtility is probably faster and less GC yes

#

it's optimized for that

#

People choose newtonsoft for the richness of its feature set

scenic forge
#

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.

sly grove
scenic forge
#

Deserialization, my game hits a lot of server endpoints, it's like death by a thousand cuts kind of deal.

sly grove
#

deserialization of network responses?

scenic forge
#

Yeah.

sly grove
#

Are you deserializing on the main thread?

scenic forge
#

Yeah

sly grove
#

Should be able to deserialize on the background thread

#

before passing the data to the main

scenic forge
#

🤔

#

With jobs?

sly grove
#

no

#

normal C# threading

scenic forge
#

Not sure, I don't think each individual deserialization is big enough to warrant that.

sly grove
#

surely that's worth a dedicated thread to do network requests and deserialization

#

if not a thread pool

scenic forge
#

Network requests are done with UWR

sly grove
#

might have to change that

scenic forge
#

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

sly grove
scenic forge
#

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.

sly grove
#

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

scenic forge
#

It doesn't already, the current performance is fine

#

It might if I switch over to Json.NET because it's slower.

mint sleet
#

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.

sly grove
#

so it all kinda boils down to threading

mint sleet
#

when we use coroutine does the unity not create a new thread for it?

sly grove
#

no

#

coroutines use the main thread

mint sleet
#

but accomplish the same result, is not it?

#

in terms of not blocking the thread?

sly grove
#

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

mint sleet
#

hmm. what about async operations. is that the same as acoroutines in terms of thread usege

sly grove
#

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

mint sleet
#

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?

sly grove
#

i don't really know what you mean

mint sleet
#

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

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

mint sleet
#

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.

sly grove
mint sleet
#

it is actually

sly grove
#

that's what happens after deserialization

mint sleet
#

yes but you can not deserialize a "Task" right?

sly grove
#

i don't see why would need to?

#

who said anything about deserializing tasks?

mint sleet
#

is it possible?

sly grove
#

i don't even know what it means

#

A Task is a handle for an asynchronous operation

#

what does deserializing it mean

mint sleet
#

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

sly grove
#

to be honest I don't understand what this discussion is about anymore

mint sleet
#

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

atomic harbor
#

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

thin mesa
#

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

atomic harbor
#

thanks

verbal hare
#

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.

rigid dagger
undone coral
#

is there an easy way to find particle system physics cost in the profiler

idle prairie
#

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

   }
chilly nymph
#

But also make sure you're songs are in a resource folder or accessible to the build.

#

Look into addressables if you need to.

idle prairie
chilly nymph
idle prairie
#

spent a quarter of the day trying to figure this out too :/

dapper cave
#

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

jolly token
jolly token
undone coral
#

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?

mint sleet
#

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?

random dust
#

Does this inject code where you call that?

#

Why doesn't he just await the call?

compact ingot
dapper nest
#

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

austere jewel
#

They are the same thing, almost literally

devout hare
#

"Unity context" doesn't change anything in this regard. You can just read the general C# discourse.

dapper nest
#

So if they are the same in that sense, from a design perspective, what do you think are their respective usecases?

devout hare
#

They're the same thing so use cases are also the same

austere jewel
#

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

random dust
#

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

random dust
#

Does it inject code on spots where it is called?

brisk pasture
#

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

undone coral
undone coral
undone coral
#

the actual class exists

undone coral
#

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

brisk pasture
#

its just a handle to keep track of work that may or may not have happened yet

undone coral
#

property setters tend to have side effects. for example text in a textmeshpro component

undone coral
jolly token
compact ingot
jolly token
#

I think it's more of using Task.Run is explicitly specifying that it will use threadpool?

#

semantic wise

compact ingot
#

If you want to run on threadpool with unitask you can make it super explicit with UniTask.RunOnThreadPool

compact ingot
#

the danger with unitask is in doing worker tasks on the main thread, those should be avoided

trail cloak
#

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

undone coral
#

you should not be doing anything in OnApplicationQuit

trail cloak
#

I didn't

undone coral
#

then it soundsl ike one of your libraries is making a real exception

trail cloak
#

Librarys....

#

Steam SDK?

undone coral
#

have you looked at the report that crash handler is generating?

#

🤦‍♂️

trail cloak
#

Let me check the log

undone coral
#

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

trail cloak
#

Is there a way just "KILL" the whole game process?

#

System.Diagnostics.Process.GetCurrentProcess().Kill();

#

Just froze the game

undone coral
#

what is your objective?

#

you used the word "just" so you are in trouble

#

is this your project? someone else's project?

trail cloak
#

This is my product... when I call application.quit() all i want is to kill the game

#

TMP raise the exception....

#

I see

undone coral
#

you should build to mono

#

a development mono build

#

and see the line numbers

#

you have a lot of bugs

trail cloak
#

What do you mean by bugs

undone coral
#

hmm

trail cloak
#

I mean, I understand the bug definition

#

Is there a way to close the game no matter what exception it raises?

undone coral
#

yes

trail cloak
undone coral
#

Process.GetCurrentProcess().Kill();

trail cloak
#

I tried that, in mono this line close the game perfectly, but in IL2CPP it just froze the game

undone coral
#

so...

#

what can we conclude?

trail cloak
#

Is there another way?

#

Guess I have to deal with the exceptions

undone coral
#

lol

trail cloak
#

And the issue persists....

frozen imp
#

@trail cloak Don't post off-topic images

trail cloak
#

sry

icy aspen
#

how can i get a float to change from 0 to 1 in 2 seconds

fresh salmon
#

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

icy aspen
#

how can i set starttime to time.time

fresh salmon
#

convert?

icy aspen
#

oh sry change

fresh salmon
#

They said "set", so it's an assignment

#

float startTime = Time.time

icy aspen
#

set

#

oh

#

can clamp01 also be clamp03?

#

@hidden edge

fresh salmon
#

No

icy aspen
#

oh

fresh salmon
#

You need Clamp(n, 0, 3)

icy aspen
#

ok

fresh salmon
#

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

flint wraith
#

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?

rich storm
#

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

quartz stratus
#

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.

rich storm
#

Z is always 0, there are not multiple on top of each other either, the clickable object is the only one with a collider

quartz stratus
# rich storm Z is always 0, there are not multiple on top of each other either, the clickable...

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.

rich storm
#

Ill look into the Ipointer stuff and see if that fixes it. Thanks

quartz stratus
flint wraith
#

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

rich storm
#

I only use a raycast to place the object onto its slot

#

Im dropping the pieces onto a board

flint wraith
#

well yeah but does that happen when you place object on board?

#

when you drop it

rich storm
#

No i cant pick it up at all

#

It only happens on the initial attempt to pick it up

flint wraith
#

what do you mean

#

problem is only on first try?

#

or works only when you first time pick it up

rich storm
#

Either you can pick it up or not

flint wraith
#

well cant help like this, but consider that problem, maybe you have something blocking the object

#

mousedown still uses raycast to handle things

regal olive
#

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)

torn basalt
#

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

dense aspen
#

that's possible?

regal olive
dense aspen
#

@regal olive try putting debug.logs everywhere

torn basalt
#

HAve you tried without that nested method?

dense aspen
#

see if the logic is even executing

torn basalt
#

or maybe AddForce At Position?

regal olive
#

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

torn basalt
#

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

}
main fern
#

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

brisk pasture
#

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

main fern
#

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

glass hill
#

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

jolly token
pliant crest
#

does deep copy even make sense for structs?

glass hill
#

Shallow copy. Or does it already shallow copy?

#

Err, no, deep copy

#

I misunderstood

pliant crest
#

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

small latch
glass hill
#

That's good to know

main fern
#

well thanks for all the help. time to use google. lol

pliant crest
#

you shouldn't pass them by reference (normally)

crystal parrot
#

i`m having this errors on a headless server build. Is it possible to disable shaders and rendering?

random dust
#

I just assumed it injected code since that is possible too

lyric dragon
#

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.

split folio
#

@lyric dragon i think its a better option to do it in another way
Dont think unity is the best choice for that

lyric dragon
flint wraith
#

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.

winter yacht
flint wraith
lyric dragon
gusty tusk
#

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?

flint wraith
lyric dragon
trail cloak
#

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

icy aspen
#

@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

fresh salmon
#

Clamp returns the clamped value

icy aspen
#

ok

fresh salmon
#

Mathf.Clamp(5, 0, 3) would return 3 because 5 > 3

icy aspen
#

alright, so then what is wrong with my cod

#

e

fresh salmon
#

You don't use the return value Clamp returns

icy aspen
#

like this?

fresh salmon
#

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

icy aspen
#

hmm i see

fresh salmon
#

Nope, the speed calculation makes no sense inside the clamp

#

Do it once, in Start or whatever

gray arch
#

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

fresh salmon
fresh salmon
#

I just said what to clamp lol

#

The result of the increment

icy aspen
#

yeah but what is it in code

#

is it just start

fresh salmon
#

Trying, debugging is more than expected here

icy aspen
fresh salmon
#

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

fresh salmon
#

No

#

Assign the result of Clamp back to start

#

Then you'll see that start will gradually go from m to n

icy aspen
#

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

fresh salmon
#

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

icy aspen
#

yeah ok

#

this is my final code now, but when i run it, start stays 0

fresh salmon
#

Yeah you're not reading what I write

icy aspen
#

oh it should go from m to n

fresh salmon
#

speed = (n - m) / x
Where m is start value, n end value, x the number of seconds to cover that distance

icy aspen
fresh salmon
#

Swap m, n in the speed calculation

#

You have it bacwards

#

And same thing for inside the Clamp, backwards too

icy aspen
#

is it correct that the clamp function to declare start should be in update?

fresh salmon
#

Yes, that's what prevents your value to go below m or above n

icy aspen
#

the problem im having now is that its not working

fresh salmon
#

And then rename to make the variables clearer on what they are

start => value
m => start
n => end
x => time
dapper nest
#

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)

lean rivet
#

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

devout hare
lean rivet
#

in scroolbar i am using prefebs that are instantiate

gray arch
#

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

sly grove
gray arch
#

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

jolly token
sly grove
#

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

gray arch
#

So in case of unity or game development in general, it is not adviced to follow coding principles blindly?

jolly token
gray arch
#

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

midnight venture
#

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

bleak marsh
#

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

jolly token
#

interfaces are still not a silver bullet, but good tool to implement things with minimum coupling

bleak marsh
dusk plaza
#

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'

sly grove
jolly token
sly grove
# dusk plaza exactly

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);```
bleak marsh
#

as if it was never handled

jolly token
bleak marsh
#

But then the object won't get the event

jolly token
#

Turn it on only when you need it?

dusk plaza
bleak marsh
jolly token
#

Even if you 'ignore' the event, it only will bubble up, not finding another raycast target

bleak marsh
#

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

jolly token
#

So your option is disable raycast target or playing with raycaster's blocking mask

#

Or creating own event

bleak marsh
jolly token
#

You cannot do much if event is already fired for the target

bleak marsh
#

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

jolly token
#

You could make TMP child of the object behind the text

bleak marsh
#

Okay, but then how do I propagate the click up?

jolly token
#

I remember doing it with SendMessageUpwards

bleak marsh
#

Okay... ewwwwwwww

jolly token
#

But maybe there is some more improvement on that with event system

#

Yeah ik, ew

bleak marsh
#

I would rather GetComponentInParent than SendMessageUpwards

jolly token
#

Something like this should do it
ExecuteEvents.ExecuteHierarchy(transform.parent.gameObject, eventData, ExecuteEvents.pointerClickHandler);

bleak marsh
#

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

jolly token
#

Yeaah. That case is more complex

bleak marsh
#

Still, the lack of robustness of this system is astonishingly bad

jolly token
#

I remember implementing somewhat similar thing to that case with CalculateRelativeRectTransformBounds/RectangleContainsScreenPoint , but it does make things complicated

bleak marsh
#

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"

arctic lake
#

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

bleak marsh
jolly token
#

Sadly I also doubt that Unity team monitor this discord 😂

bleak marsh
#

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

undone coral
#

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

bleak marsh
undone coral
#

why from scratch

bleak marsh
#

But I don't think I can just override

clear wedge
#

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?

compact ingot
clear wedge
#

sorry, bad example - it is negated in my real code 😅

jolly token
#

Your code is not compiled by each namespace. It's compiled by each assembly.

clear wedge
jolly token
clear wedge
#

it worked, you're a legend @jolly token

whole quest
#

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

▶ Play video
jolly token
whole quest
#

how do ı use this asset for army commender splines and texturce changing in real time

jolly token
whole quest
#

Sorry I am not native speaker

jolly token
#

Me neither

whole quest
#

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

jolly token
#

You can simply draw on top of floor, you don't have to change texture

whole quest
#

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

jolly token
#

Or polyline, whatever shape you are thinking

whole quest
#

i see bro

#

thank you so much for your help

tight tapir
#

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.

mint sleet
#
        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?

devout hare
#

Can't reference how and doesn't show up where?

mint sleet
#

@devout hare

devout hare
#

What does it say if you type it anyway?

mint sleet
#

just it leaves it white text.

devout hare
#

but what's the error message

mint sleet
devout hare
#

is this a coding question or editor configuration issue?

mint sleet
#

let me compile

#

coding question.

devout hare
#

I mean it has to be valid anyway, like inProcess = false;

mint sleet
#

No error at all pixelconfused

#

it just compiled ???

devout hare
#

so editor configuration issue then

mint sleet
#

hmm what should I do?

devout hare
#

configure the editor ¯_(ツ)_/¯

mint sleet
#

🙂 ok let me google it. have not done it before. Thanks

random dust
#

What if you rename to _inProcess?

#

Restarting Unity? 🤔

mint sleet
#

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?

tawny bear
#

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

mint sleet
#

Yes, I'm doing this. I realized after I thought a bit.

#

how can I override the interactable property then?

#

@tawny bear

tawny bear
#

Can't you just do an override of the original function in the inherited class?

#

Without taking the base

mint sleet
#

Ive discussed it with my collogue. Decided to sticik with very basic solution. We will use Actions.

#

Thanks Wumpie

tawny bear
onyx blade
#

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)

tawny bear
#

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?

onyx blade
#

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

tawny bear
#

probably UnityEngine.XR.MagicLeap.MagicLeapSettings?
Check this object

#

Or thing

#

Not sure what it is

onyx blade
#

its part of the AR feature in unity

tawny bear
#

Try to disable it and test it again?

#

If that doesn't break stuff

onyx blade
#

how do you disable a package that is part of a feature?

#

I couldn't find that

mint sleet
#

And I send the button from my trigger class. when the API request is done. it just enables the attribute

#

Sometimes must think basic.

random dust
# mint sleet

What happends when you try to access that interface's definition?

#

Does it just not load?

#

I would assume it's internal at best

mint sleet
#

it did not load, I'm mixed up why

tawny bear
#
       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?

broken hare
#

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

terse bobcat
#

hello does anyonw know how to get the lobby type in steamworks?

worthy lodge
#

Need some linear algebra help in #1027941647880814632
About an enemy mirroring a player for a VR game

jolly token
# mint sleet

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.

jolly token
broken hare
rugged ether
#

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

abstract folio
#

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

fervent parcel
#

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!

undone coral
#

i think it's platform specific

#

is there a CreateMipMaps method in unity?