#archived-code-advanced

1 messages ยท Page 10 of 1

distant tree
#

wrote this in python as a draft and plan to convert it to c# once it's done since the most convenient console I had for experimenting with things like this was python

so I made this script to calculate the vertical trajectory of an object thrown at velocity velocity. it's a little hacky but it works fine.

problem is I need velocity as an output, not an input, since I need this for a spring which will attempt to launch the player toward a certain height, adjusting for forces like gravity over time.

velocity = 10

gravity = 2

iterations = 5*gravity

def sumFromZero(number):
    number /= gravity
    number = number*(number+1)/2
    number *= gravity
    return number

def calculateTrajectory(number):
    number += 1
    return sumFromZero(velocity)-sumFromZero(velocity-number)

print("============================")

for i in range(iterations):
    if (i+1)%gravity<0.01:
        print(calculateTrajectory(i)-calculateTrajectory(i)%1)

best solution I could think of was to convert this into a mathematical function and just use algebra to move velocity to the other side of the equation, but I'm not sure exactly how to do that.

anyone able to assist?

#

variables like velocity and iterations are mainly for testing and their values are pretty much random. gravity is the same value I have it set to in my game tho

#

so it would be something like -v_y=1/2*g*t^2-height_at_t*t

#

this is just off the top of my head so im not totally confident in it

#

crap wrong variable

#

fixed it

#

if u could that would save time but yeah it shouldnt be too hard to figure out myself

#

ty, this should work

ornate frost
#

Hi, anyone built apk for an Android TV before?

#

im trying to make a portrait apk there

#

does the android TV support Portrait mode, ?

distant tree
#

works perfectly when I just want to throw the player upwards, but I have a second type of spring which throws the player to a 3d position, not just y. currently I just set the rb.velocity every physics update until it reaches the goal, but I'd rather do the more physically accurate method of finding what x and z values will reach the player to the target on the same frame that it'll reach the y goal. any idea how I might do this? I'll try looking around a little but based on what little googling i have done it doesn't look like it's gonna be too easy to find

regal olive
gray pulsar
#

you could also print out some values in those, especially the ones inside the coroutine

#

think about how many times you expect each debug statement to print and how many times they actually print

austere summit
#

Hi all! If i have a package on my git and them want to install it through Package Manager with git url, then files will be downloaded to /Library/PackageCache. Well, how to locate any local files then?

wooden wind
#

Does anyone have experience with the google place API specific for photos ? I have the right reference but don't get the real image somehow can anyone help me with this ? Even I do a conversion tobasestring64 it is still a weird response

#

this is my code public void GetPhotos()

{

foreach (Photo photo in photos)
{
photo_ref = photo.photo_reference;
Debug.Log(photo_ref);
url_photo = "https://maps.googleapis.com/maps/api/place/photo?photo_reference=" + photo_ref + "&sensor=false&maxheight=400&maxwidth=400&key=" + API_KEY;
}

    UnityWebRequest www = UnityWebRequest.Get(new Uri($"{url_photo}"));
    www.SetRequestHeader("Accept", "application/json");
    try
    {
        www.SendWebRequest().completed += op =>
        {
            
            string photo = Convert.ToBase64String(www.downloadHandler.data);
            Debug.Log(www.downloadHandler.data);
            Debug.Log($"Code: {www.responseCode} --- Find Photo ---\n{JsonConvert.SerializeObject(photo)}");
        };

    }
    catch (Exception e)
    {
        Debug.LogError(e);
    }
}
sly grove
wooden wind
#

This is my weird response

sly grove
#

also what's weird about that?

#

That's just base64 encoded data

wooden wind
#

Because it was first like this png/ ? yes but i dont know how to get the png

sly grove
#

what are you expecting it to show an image in the console?

wooden wind
#

Just a png link so i can display the image in Unity

sly grove
#

it's not a link

#

it's the actual image data

#

the link is the thing you plugged into UnityWebRequest.Get

wooden wind
#

So if i just use loadimage then I will get the image displayed?

sly grove
#

no it will give you a Texture2D

#

to display the image you'd use a UI RawImage component or something

jolly token
#

This what you need?

sly grove
wooden wind
#

I think so thank you very much @sly grove @jolly token

sly grove
#

the end result is the same, a texture

wooden wind
#

So basicly i get a texture back and then i have to link it to a UI element to visual the image

sly grove
#

you can do anything with the texture you want

#

you can put it in your UI

#

you could apply it to a material and plaster it on a 3D model

#

You could throw it in your skybox

#

whatever

wooden wind
#

thank you for the info

plucky laurel
#

why is there a dep on some unrelated "screen manager"

#

with no documentation or even purpose described in readme

#

yeah no im not attacking, just weird af

#

im all for open source controller

#

also so much garbage in the project, pipeline files whatever, very dirty

jolly token
#

It is pretty weird

#

The package looks like some kind of unorganized dumps of utility functions

#

And the documentation is redirecting to itself lol

plucky laurel
#

weird right cuz the owner seems to be very familiar with dev in general with all the scoped registries and whatever, seems to be a nobrainer to make clean repo

jolly token
#

I guess he just wanted put all the common things and utils he uses to one repo? Though 99% of package user won't use it? ๐Ÿค”

lament briar
#

Hi! I'm using BinaryReader, as some of you tipped me in this channel some hours ago. I'm trying to save a json file.

#

However, every time I save it the reader saves three additional characters in the file, causing a json serialization error:

#

Those three starting characters are the only difference in the file with a FileWriter.

#

That's my code:

sly grove
lament briar
#

It should be faster with async

#

than file.WriteAllText, at least

sly grove
#

Nothing you're doing is async right now

lament briar
#

It's literally the first test

jolly token
#

if you use BinaryWriter to write string it writes length first (the doc linked)

lament briar
#

Definitely not gonna jump very far if I try to write more advanced code ๐Ÿ˜›

sly grove
#

BinaryWriter is literally for writing raw binary data

lament briar
sly grove
#

it's by far the simplest way

lament briar
#

Already done..?

sly grove
lament briar
#

Is this one fast? Will it be faster with another serializer? I'm trying to understand what's a good combo for file writing and serializing. I need to read, save and serialize those files without blocking the main thread (and lowering fps), even if they take some seconds to load

sly grove
#

note that the serialization and writing the file are two completely separate operations

deep peak
#

dont worry about read/write optimization if your file/data size is less then 10-100MB

lament briar
#

didn't find it and I thought it didn't exist :\

jolly token
lament briar
#

since it causes lag spikes

#

I need it for chunk loading

sly grove
#

ANY disk IO on the main thread is going to cause noticeable lag pretty much

lament briar
#

Exactly! And how can I move that load? I'll use async for files (if it's enough), but for serialization?

sly grove
#

wdym

#

do the serialization in a background thread if you want to

lament briar
#

I'm overloading the main thread because I'm 1) reading a large file and 2) serializing it (I'm talking about the loading of the chunk, but it's the same for the saving phase)

sly grove
#

you'll need the data to be fully copied to a separate object for the background thread to use unfettered

plucky laurel
#

wonder if its possible to reliably do

lament briar
#
  1. can be solved by async file reading, if I understood correctly
#

but about half the lag is serializing

sly grove
#

yes you can serialize on another thread

#

you have to understand multithreading somewhat to do it.

lament briar
#

Ok, that's what I thought

#

If writealltextasync is not in any way faster than binarywrite/read in async for json serialization, I'm gonna definitely use that function

sly grove
#

also you'll have to be very caerful that your serialization process doesn't involve any unityEngine.Object derived objects

lament briar
#

wdym? classes? I've noticed that I can't send a class as a parameter to my job

sly grove
lament briar
#

I'm really new to that (literally started using jobs yesterday)

sly grove
#

I mean any class that is derived from UnityEngine.Object

lament briar
#

some examples?

sly grove
#

that includes GameObjects, all Components, all MonoBehaviours, all ScriptableObjects

lament briar
#

mmmh, ok

sly grove
#

anything with UnityEngine.Obejct in its line of inheritance

lament briar
#

but all classes are still "banned" from jobs

sly grove
#

Who said anything about the job system

lament briar
#

since they're references and could cause problems

#

right?

sly grove
#

only you mentioned the job system

#

Yes you cannot generally use managed objects in the job system but I'm not talking about the job system

lament briar
#

ah hold up

#

nevermind i lost a message

#

sorry

#

yeah i'm serializing a custom class right now

#

made just from data

sly grove
#

good

lament briar
#

already discovered in the hard way that you can't serialize monobehaviours

lament briar
sly grove
#

you'll want to make a way to make a "deep copy" of your custom class

#

and then pass that copy to another thread

#

in that other thread you can serialize it to json and write it to a file

lament briar
#

what do you mean by deep copy?

#

on the jobs (not talking about threads since they seem really hard) I can use a struct, so I was thinking to turn my savefile class into a struct

#

that.. should work, I think

sly grove
#

I mean completely copying the whole object graph/tree. For example if you have a List<SomeClass> and you do new List<SomeClass>(originalList) for example, you have a shallow copy. Even though it's a new list, the references are still the same

#

a deep copy would be making brand new copies of every object in the list, and making a list referring to the copies.

#

Such that the two lists are entirely unrelated, and changes in one will not be visible in the other

#

Yes if you use structs in general it wil be simpley to make "deep copies" as structs are copied by default when assigning and passing them as parameters

#

You will basically need a strong understanding of struct vs class (value vs reference) to make this work right

lament briar
#

or using a copy constructor

sly grove
#

yea

#

exactly

#

but I say "deep" because it needs to go all the way through the whole tree of objects

lament briar
#

ok

sly grove
#

the idea here is it's not safe to try to serialize from an obejct that the main thread may still be using and pmodifying while you try to read it

#

creating a deep copy cleanly cuts the data apart so there can be no meddling by another thread.

lament briar
#

Are they serializable?

sly grove
#

I don't think you should use the job system unless you intend to write a json serializer from scratch

#

It will be simpler to use the typical System.Threading stuff so you can use managed objects and such freely

lament briar
sly grove
#

mutex is used for synchronization between threads

#

C# has mutexes, and semaphores, and concurrent collections, and everything you would ever want to write multithreaded code

#

same as any other language

lament briar
#

No mutex for jobs?

sly grove
#

not really

#

the way you handle synchronization in jobs is with the job dependency system

lament briar
sly grove
#

again though, I don't think jobs is the way to go here

lament briar
#

C++ and C were way easier and that's weird

sly grove
lament briar
#

Ok

#

So any c# threading tutorial will go

sly grove
#

Not sure why you think C and C++ are easier as C# has all the same tools basically

lament briar
#

that's enough I think, I now have to search a lot

#

I will be able to use my classes, right? Maybe with a mutex, to not break anything

sly grove
#

yes

#

I recommend a ConcurrentQueue for this system

#

you can just have a thread that is constantly polling from the queue and serializing stuff it finds in the queue to save files

#

and the main thread dumps the copied save data in the queue for that thread to pick it up

#

pretty simple

lament briar
#

A single external thread?

sly grove
#

yes

lament briar
#

Isn't a thread per chunk a good idea?

#

destroying the thread after it did its job

sly grove
#

maybe but you probably don't need it

#

not at first anyway

#

and no

#

destroying the thread is a bad idea

#

spinning up threads and destroying them is expensive

#

best to reuse the thread

lament briar
#

ok

#

well as long as my main thread doesn't get blocked, I think it's a wonderful idea

sly grove
#

try it out... see where you get

#

i've done similar things for listening for network requests from an outside application

lament briar
#

yep, thank you so much

lament briar
#

it was a small multiplayer game written in c++, with "two threads per client" logic since I didn't know what async was and how it worked

#

very ugly code and solution

#

That's my ReadAllAsnc code. There's the await operator, so it blocks until it finishes... Right?

novel plinth
#

If you mean by block is blocking the main thread, then no.. you're using task.run there

lament briar
#

ok

#

ty

jolly token
# lament briar

But it does block. Because you're doing GetAwaiter().GetResult()

#

You're forcing asynchronous task to synchronize

#

Use async/await instead

lament briar
#

How? I'm looking for examples but I can't find them

#

Maybe I should call it in a thread

#

since I need the result, and I can't wait for the reading to finish (or what I'm trying would be pointless)

jolly token
#
public async Task AwaitJob()
{
    var result = await Task.Run(async () => { return await ... });
}
jolly token
lament briar
#

How do I get my result? I'd still have to call .GetAwaiter()

jolly token
#

No I show you how to get result right there

lament briar
#

is there a way to call a main thread function once it has finished?

lament briar
compact ingot
lament briar
#

to make it unblocking

lament briar
jolly token
#
public async Task AwaitJob()
{
    var result = await Task.Run(async () => { return await ... });

    // right here
    DoSomethingWithResult(result);
}
compact ingot
jolly token
lament briar
#

at this point I'm not sure and I'm really tired, my brain is going really slow

compact ingot
#

can you explain why you need it?

lament briar
#

I'm trying to reduce lag in my chunk loading system, half of the lag is made by a json serializer and the other half by using (reading or writing) files

compact ingot
#

in any case, if you want to make life easy, you can just use UniTask and switch between mainthread and threadpool at any time and skip all the dirty work of doing the mainthread scheduling and workarounds yourself

lament briar
#

since I need to use the result of this readallasync (it's literally the json string that will be serialized into a class), I'll need to do that there

lament briar
jolly token
compact ingot
#

you could just do (in any async method)

await UniTask.SwitchToThreadPool();
await DoNastySerializationWork(); // lets assume this would cause issues if run on the main thread due to the CPU load it produces
await UniTask.SwitchToMainThread();
jolly token
#

Then return result;, in the main thread you will do the same like
var result = await AwaitJob()

jolly token
lament briar
#

I can use it by calling GetAwaiter and GetResult

jolly token
#

You can only await from method that marked with async

#

Eventually the entry point would look like async void

lament briar
jolly token
#

You cannot do that, so split a step

lament briar
#

And if I make a method async, calling that without GetAwaiter would need the calling method to be async, right?

#

creating a cascade effect in my code

#

idk if I explained my concern clearly

jolly token
#

Yes it will cascade

lament briar
#

ok at this point I'm too tired to think anything, so thank you so much tomorrow I will look at async methods, some multithreading etc, but for now I think I'm just gonna sleep ahah

#

ty ๐Ÿ˜„

jolly token
#

Rest well

sly grove
# lament briar

I see what you're trying to do here but Task.Run doesn't run in a background thread in UNity by default

jolly token
#

https://docs.unity3d.com/2021.3/Documentation/Manual/overview-of-dot-net-in-unity.html

Unity overwrites the default SynchronizationContext with a custom UnitySynchronizationContext and runs all the tasks on the main thread in both Edit and Play modes by default. To use async tasks, you must manually create and handle your own threads with the Task.Run API, and use the default SynchronizationContext instead of the Unity version.
Does not explain how to use default one what a poor documentation ๐Ÿค”

compact ingot
#

but isn't that precisely what Task.Run does?

#

i've never had any issue with creating a separate thread with Task.Run

#

that bit in the docs just means that if you async void Start() { await FooAsync(); } that await Foo() will not cause a Foo to be scheduled on a different thread

#

you can run a work task with task run and get no hiccups on the main thread

jolly token
#

I'm little confused here how Task.Run would work with custom SynchronizationContext, but I think it should work?

#

documentation is quite dilogical

sly grove
#

It's honestly probably simpler to just do:

Thread bgThread;
bool stop = false;

void Start() {
  bgThread = new Thread(MyCode);
  bgThread.Start();
}

void OnDestroy() {
  stop = true;
}

void MyCode() {
  while (!stop) {
    // do stuff
  }
}```
jolly token
#

async/await support also has been changed a lot between versions

compact ingot
sly grove
#

nah because that involves adding a big heavy framework to your project

compact ingot
#

its neither big nor heavy

#

and the misinformation and confusion about async, jobs and tasks that is spread in this discord makes it just completely impossible for anyone to get a solid grip on it

sly grove
#

what was the misinfo?

compact ingot
#

that Task.Run doesnt run on a separate thread for example

compact ingot
sly grove
sly grove
compact ingot
compact ingot
#

try it

#

see for yourself

sly grove
#

it's true unless you go out of your way to change it

compact ingot
#

you read the docs wrong

#

it even says in the docs that you need to use Task.Run to create your own threads

novel plinth
#

It does not necessarily run on a new thread, the scheduler decides that

compact ingot
novel plinth
compact ingot
#

await does not necessarily run on a separate thread, which is what the unity docs mean, in unity await will always stay on the main thread UNLESS it (the task) is explicity pushed to the threadpool with Task.Run

novel plinth
#

await does not necessarily run on a separate thread true, and it's just awaiting

compact ingot
#

?

novel plinth
#

in unity await will always stay on the main thread Not true, the default is Unity's sync cotext, yeah... but when you switched out of that context you no longer in Unity's thread

compact ingot
#

duh

#

thats exactly what i just said

strong harbor
#

I require some help if anyone has this editor level knowledge. Editor stuff is just out of my wheel house. Anyone know how to make an editor slider that can change the scale of an entire object

compact ingot
#

you can also replace the unity sync context to whatever you like

strong harbor
novel plinth
#

well yeah, then say bye to monobehaviors ๐Ÿ˜ƒ .. unless some dispatching involved, which the common way to deal with such situation

compact ingot
#

are you trying to roll up the whole discussion again from the start?

#

everybody knows that

#

and its also not true because you can easily switch between threads mid-method, UniTask has a nice API for that.

novel plinth
#

man, the bloats of UniTask just for this simple usage ๐Ÿ˜† ... but it's a fine option for sure

compact ingot
#

using unity and .NET and talking about bloat is quite ridiculous

novel plinth
#

It is important imho...

compact ingot
#

then dont use unity or .NET

#

they are bloat squared

chilly nymph
#

Hey gents, what's the proper way to "log" someone into a editor script?

jolly token
chilly nymph
#

Best way to log someone into a service. Be it a token or something else.

jolly token
chilly nymph
#

This is authentication editor side.

jolly token
#

To make sure you are trying to write editor extension, to make editor user to log in?

chilly nymph
#

I really don't know how to say this differently, I need authentication for a service editor side. "Log" them in to a editor script so they have auth to a external service.

#

Would I use some kind of UUID from the editor or something else?

jolly token
chilly nymph
plucky laurel
#

i use catheis sheet plugin and ive setup Creds dir, which is ignored by git, and where you drop any cred data

chilly nymph
#

How would you store this on editor side?

plucky laurel
#

storing google service account key there, for every user its own

jolly token
plucky laurel
#

no that is just a way to not have the key public or in repo @jolly token

jolly token
#

Oh the google service account I see

plucky laurel
#

doc, you cant imagine how much i dont want to do anything related to this

#

right ill shut up your advices are good

chilly nymph
#

Didn't know about editor prefs, thanks.

jolly token
#

I've been mentioning it tho

chilly nymph
#

Are we able to hook into any unity account data?

#

Do we have access to any of te tokens?

#

Ye

plucky laurel
#

i wonder what is the task

chilly nymph
#

Looks like it's refreshed each instancee.

#

So I guess I'll just store my own token.

#

yes i understand

versed warren
#

Im strugling trying to change the UV offset so I'm looking at other approaches at this point. How do I adjust the mip map bias of the texture?

#

And the weird thing is when I set the pixel length over 128 it pretty much goes away

#

the larger the resolution the smaller the bleed

plucky laurel
#

yes because larger mips as well

#

texture.mipMapBias

#

write it down, third time im telling you this

junior lynx
#

not sure where to ask about this

#

has anyone tried to use npm packages in unity project

plucky laurel
#

arent those js? why do you need to drag js into unity project

chilly nymph
#

Rewrite a npm package?

junior lynx
junior lynx
plucky laurel
#

then read its docs it should have instructions on how to install it properly

junior lynx
chilly nymph
plucky laurel
#

you can, with npm

#

since it doesnt care where you install it

chilly nymph
#

Unity can't run js.

plucky laurel
#

unity cant, some plugin may

chilly nymph
#

Is this a native plugin?

junior lynx
chilly nymph
#

That's still not Unity.

plucky laurel
#

read the docs

junior lynx
#

but the game is built in unity right

chilly nymph
#

But as an external plugin sure.

plucky laurel
#

it doesnt even have to be in unity directory it can be anywhere

#

even install -g can work

junior lynx
plucky laurel
#

unity?

#

cosmos docs

junior lynx
junior lynx
plucky laurel
#

read cosmos docs

chilly nymph
#

a flag.

junior lynx
junior lynx
plucky laurel
#

you said you need cosmos npm package to build your game for web

#

im telling you to read its docs, or whatever docs that lead you to requirement of a js library

#

im sorry im out of my depth here, ive never attempted to run js from unity build

#

well maybe when js was literlly unity's scripting language

junior lynx
#

Im actullay running js code in unity projects

#

but never used a npm package

chilly nymph
#

I wouldn't build it the way you are, as it's not extendable.

chilly nymph
#

Look into that.

junior lynx
#

yeah sure will do

chilly nymph
#

a REST api for your db

severe trail
#

Hey. Is there any way to apply this code to rotation for a turn in place animation? ```cs
private void PositionVelocityToAnimator(Rigidbody rb) {
Vector3 rbSpeed = rb.velocity;
rbSpeed.y = 0;
Vector3 rbLocalSpeed = transform.InverseTransformDirection(rbSpeed);

    float previousDirectionX = _animator.GetFloat("DirectionX");
    float previousDirectionY = _animator.GetFloat("DirectionY");

    _animator.SetBool("IsMoving", rbLocalSpeed.magnitude > _positionSpeedThreshold);
    _animator.SetFloat("DirectionX", Mathf.Lerp(previousDirectionX, Mathf.Clamp(rbLocalSpeed.x, -1, 1), _positionSmoothing));
    _animator.SetFloat("DirectionY", Mathf.Lerp(previousDirectionY, Mathf.Clamp(rbLocalSpeed.z, -1, 1), _positionSmoothing));
}
#

I tried this but Im not familiar with quaternions: cs private void RotationChangeToAnimator(Rigidbody rb) { _rbRotation = rb.transform.rotation; _rotationDelta = Quaternion.Angle(_rbPreviousRotation, _rbRotation); bool isMoving = _animator.GetBool("IsMoving"); if (!isMoving) { _animator.SetFloat("Turn", Mathf.Clamp((_rotationDelta * 100), -1, 1)); _rbPreviousRotation = _rbRotation; } }

regal olive
#

I want make it better

severe trail
#

My player pawn is physics based so I need to bypass controller input and grab that rotation delta directly to animate my Turn float

#

been scouring the forums, etc. surprised there isn't a simple solution.

severe trail
#

what do you mean?

#

like literally just the rotation as a Quat?

#

Don't I need that delta?

#

Or is a Quaternion already a delta?

#

Okay, maybe I'm not being clear enough.

#

I have a Turn float in Mecanim with a range of -1 and 1. I'm trying to figure out how to get the rotation delta of a rigidbody and map it to that range so that the Turn in place animations trigger when the rb turn?

sly grove
#

A Rigidbody has a current rotation

#

you'd have to store the rotation from the previous physics update if you want to take a delta

severe trail
#

I'm assuming the delta between frames

#

but I'm not sure if that's the correct approach

#

because that would happen too quickly to register on the float in necanim

sly grove
#
Quaternion previousRotation; = rb.rotation

void Start() {
  previousRotation = rb.rotation;
}

void FixedUpdate() {
  Quaternion delta = rb.rotation * Quaternion.Inverse(previousRotation);
  previousRotation = rb.rotation;
}```
severe trail
#

ha word, I jsut tried that

sly grove
#

uhhh not sure how you want mecanim to be involved in this though

severe trail
#
        _rbRotation = rb.rotation;
        _rbDelta = _rbPreviousRotation * Quaternion.Inverse(_rbRotation);
        bool isMoving = _animator.GetBool("IsMoving");
        if (!isMoving) {
            _animator.SetFloat("Turn", _rbRotation.z);
        }
        _rbPreviousRotation = _rbRotation;
    }```
sly grove
#

don't mess with the individual components of a quaternion, they're essentially nonsense

severe trail
#

ahhhh

sly grove
#

what are you trying to do exactly

#

with that Turn parameter

severe trail
#

use the rotation of an rb to control a turn in place float

sly grove
#

I don't know what that means

#

are you trying to get the animator to point a graphical element in the current direction of the rigidbody or something?

severe trail
#

I have a turn in place animation, with a float of up to -1 for left and +1 for right

#

so I 'm trying to control that with the rb rotation

#

so that when the rb turn it plays the animation

sly grove
#

So do you want the Rigidbody's current rotation, or you want its angular velocity, or what

severe trail
#

anuglar velocity probably

sly grove
severe trail
#

oh hell yeah

sly grove
#

it does assume you are actually rotating the Rigidbody via natural physics

severe trail
#

I'm applying force to rotate so yeah

sly grove
#

then yes that will do it

severe trail
#

word, I'll give it a shot thanks sos much

sly grove
severe trail
#

copy that, I was trying x and y and z individually when I copypasted it, didn't have luck with any of them, but if angular velocity doesn't work I 'll go back and see if I can get that code working

#

this is what I'm trying to adapt:

#
    private void PositionVelocityToAnimator(Rigidbody rb) {
        Vector3 rbSpeed = rb.velocity;
        rbSpeed.y = 0;
        Vector3 rbLocalSpeed = transform.InverseTransformDirection(rbSpeed);

        float previousDirectionX = _animator.GetFloat("DirectionX");
        float previousDirectionY = _animator.GetFloat("DirectionY");

        _animator.SetBool("IsMoving", rbLocalSpeed.magnitude > _positionSpeedThreshold);
        _animator.SetFloat("DirectionX", Mathf.Lerp(previousDirectionX, Mathf.Clamp(rbLocalSpeed.x, -1, 1), _positionSmoothing));
        _animator.SetFloat("DirectionY", Mathf.Lerp(previousDirectionY, Mathf.Clamp(rbLocalSpeed.z, -1, 1), _positionSmoothing));
    }
orchid radish
#

Hello, quite an unusual task: I need to manage multiple scenes each containing a fight, at the same time, so that basically multiple fights can happen without the player having to see them or interact with them.

I did a POC where each fight is managed by a different manager, and the user can switch the camera to any of them so that I can use NavmeshAgents, colliders and everything Unity2D has to offer without having to script it myself while having fights play in the background.

I looked for other solutions like scene loading, but I couldn't find some better solution. You guys have an idea ?

#

issue with that solution is that the fights exist at the same time, so I need to be careful that each fight don't affect the other. So I cannot create global abilities but must always ask the manager for the list of affected combatants, for example. It might not be a huge issue but if there's a better solution I'd like to know it ๐Ÿ™‚

regal olive
#

What's wrong with it

flat marsh
#

most people wont help over pm (especially with a broad topic like networking). why would they commit to helping if they dont even know wether they can help or not? just post your question in the appropriate channel #archived-networking so everyone can try to help

pulsar isle
#

Is Procedural Generation used only for aesthetic purposes (making cool things that are always different on each startup) or for performance reasons too ? If yes, how exactly does it affect performance ?

wispy terrace
#

Badly, procedural generation hurts performance

#

It's used for playable purposes too

#

Kinda like no man's sky, which could never be done by hand crafting a whole solar system

#

Depends on what you are going for, but it rarely helps performance against hand-made assets

tribal pivot
#

Its also quite feasible to generate geometry that is 'easier' to render compared to what artist can make.

real blaze
#

hey. is there any way to bake UnityEvent into simple delegates?

#

all we need is a methodInfo from a UnityEvent object

flint sage
#

They store it but don't think you have access to it without more reflection

real blaze
#

but, like, it doesn't make any sense

#

what if we wanna cache it?!

flint sage
#

It's been a while since I looekd at it but they might cache it too

real blaze
#

let me grab a screenshot from the profiler

flint sage
#

Yeah I believe you

#

But that's likely an inefficient way of doing things in general

real blaze
real blaze
#

comparing my own tween system with DOTween's , and this UnityEvents keep getting in the way

lament briar
#

Hi, I'm trying to move some of my code to a thread to not block rendering while loading objects. When I call my spawn object thread I get this:

#

what does it mean?

#

That's where I call it

tribal pivot
#

You cant use the Unity API from other threads

lament briar
#

So I can't use a GetComponent?

compact ingot
#

there is no way to make unity run smoothly during loading outside of using the async methods the engine provides itself, and not even those make it completely smooth. you can however do a lot of processing in threads that does not have to touch most of UnityEngine.

#

if you do need to use separate threads to offload work (i.e. parallelization), use the threadpool via Task.Run(()=> {}); instead of creating your own threads which requires you to manage them manually to not constantly create/delete them (which is expensive). So unless you have a specific need to manage your own threads: don't. Alternatively (and in most cases recommended: use the unity JobSystem which allows you to use parts of UnityEngine via special interfaces)

#

if you just need to sync up tasks (stuff running/waiting concurrently but not actually doing "work"), just use async/await or a coroutine, which (by default, if you don't Task.Run() them) run on the main thread and allow you to use the unity API.

orchid marsh
#

You'll not be able to do much with it other than simply holding references

worthy lodge
#

Testing what exactly?

compact ingot
#

exactly
/ษชษกหˆzak(t)li,ษ›ษกหˆzak(t)li/
Learn to pronounce
adverb
1.
used to emphasize the accuracy of a figure or description.

worthy lodge
#

What are the results you want. Video games is very broad, so no clue what you want to test rn. Is it players getting out of bounds, performance, AI concistency, something else?

tribal pivot
#

What do you mean a theory of this?

#

My theory is its alright.

#

Check out the builtin test runner

#

Its very broad and generic, not sure how this would apply to you.

My personal experience; it hasnt been worth it. Lots is untestable, and you spend a lot of time writing tests. There's always things falling through the cracks, i prefer to test manually.

granite ridge
#

Hi, I'm using firebase and unity. Does anyone know how to receive data from a firebase cloud function?

#

I can get data to the cloud function and print it out but unity doesnt seem to receive the data I sent back

#
function.CallAsync(json).ContinueWithOnMainThread((response) =>
{
  Debug.Log(response.Result.Data.ToString());
});
#

to print it?

#

just an object

sly grove
#

like System.Object?

#

That seems unlikely

granite ridge
#

will do

misty glade
#

@sly grove the documentation for firebase & unity seems really lacking, but I do think that response.Result.Data.ToString() is idiomatic from the examples I'm seeing at the top of searches

#

this is so poorly documented - the overview page doesn't even have a single paragraph

granite ridge
#

I get Status = Faulted and Result Not yet computed

misty glade
#

is ContinueWithOnMainThread correct? I am not familiar with the API but the name of this method seems to indicate it might be doing something wacky

#

Like it seems more obvious that you should just pass your lambda or callback to CallAsync directly?

granite ridge
#

I mean the cloud function managed to do everything correctly. In the logs it prints out the data I want to send back. It just doesn't send back. I'm using res.send(data) in the cloud function

sly grove
misty glade
#

print out your error message from google:

sly grove
#

maybe you're getting a 400 or something

misty glade
#
Firebase.FirebaseException e = response.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
FunctionsErrorCode error = (FunctionsErrorCode)e.ErrorCode;
Debug.Log("FunctionsErrorCode:" + error);
granite ridge
#

Ok let me do some more digging to see if I can resolve this

#

I hate how the firebase docs aren't great for unity

#
string json = Json.Serialize(new
{
  refreshed = false
});
#

well

#

thats not good

misty glade
#

what's in the InnerException ?

granite ridge
#

thing is tho, I still should get something back

#

like even if the json is bad

old hollow
#

Hello! So I was always wondering if this is possible and never found the answer on the google so I wanted to try and ask here.

So I want to have multiple enums in a class for example

Localization.UI enum
Localization.Items enum, etc...

These enums will have random items in them for example
Localization.UI.READY, Localization.UI.UNREADY and so on.

I wanna load at the start a json file which has enum names as keys and a string as a value.
Example:

{
  "ui": {
    "ready": "Ready",
    "unready": "Unready"
  }
}

So my question is is it possible somehow to return a provided string using an enum?

#

I could create a dictionary of string, string and create it at the start using a json file

#

but then

#

how do I get it without using an function and inserting the enum as a param?

obsidian glade
old hollow
#

hmm

#

well because

#

i dont need dictionary to return me the enum

#

i just wanna use the enum to get the

#

desired string

#

i mean i know i cannot use enums

#

to get the value

#

except ints

#

and stuff like that

obsidian glade
#

I mean you just flip the dict and have the enum be keys, or even just myEnum.ToString()

jolly token
old hollow
#

im not using anything at the moment im just trying to figure out a way to do it cause it seemed complicated

jolly token
#

There StringEnumConverter

old hollow
#

okay so

#
public enum Test
{
    [EnumMember(Value = "value")]
    Value001
}

youre talking about this right?

jolly token
#

Well that's similar stuff yeah

#

You can use enum string as key in json too. as long as your enum list does not change

old hollow
#

would it be possible to change the value on runtime?

jolly token
#

Which value? The value property of the attribute?

old hollow
#

yes

jolly token
#

๐Ÿค” That's for serialization purpose, which is a protocol, so it should not change

chilly nymph
old hollow
#

hmmm okay

#

so if I want to retrieve a string value using an enum how would I do it?
Lets say I have an:

enum Test
{
  Value001
}

And I want Value001 to retrieve me a string ---> "hello"

How would I do it? Or would it be better to do this with a field property inside a class?

jolly token
plucky hound
#

how do i Debug.DrawRay while not paused? I want to see the debug rays all the time, please.

sly grove
plucky hound
#

i only see a version with two parameters. lemme check that...

#

in Update() they still only appear while the unity editor is paused.

#

in Update with timeout set to Time.deltaTime... still not visible. maybe it's my eyes.

sly grove
#

set it to something like 5 or 10 seconds

#

or longer

wise fossil
#

hello, How can I improve this :

sly grove
#

turn it into an mp4

#

so discord can embed it

#

that would be a great improvement

wise fossil
#

oh okay ๐Ÿ˜‚

#

I m moving a button with sliders, so the user can move its movement buttons

jolly token
#

You have two slider UI component?

#

Horizontal vertical? That's new. ๐Ÿค” and what part you trying to improve?

wise fossil
wise fossil
#

that was my only idea, but I hope it exist others so I can change my way to do it

jolly token
wise fossil
#

what is drag ?

jolly token
#

Like.... drag event?

wise fossil
#

humm that is what I am looking for

#

I didn t know for now events

#

It on my list

#

so it exist an event that permit to drag objects ?

#

ofc it makes sens

wise fossil
#

thanks !

orchid radish
#

Hello, I have a hard time making the NavMeshBuilder.BuildNavMesh() work at runtime. My goal would be to instantiate a simple Grid object with their Tilemap, and bake the navmesh. Goal being loading and unloading scenes, keeping them in the background so the player does not have to see them while they play. Current code is very simple:

var gridInstance = Instantiate(grid);
        NavMeshBuilder.BuildNavMesh();

#

at the moment it does not produce anything

#

and that's my grid:

jolly token
orchid radish
#

yes, 2d top-down view

jolly token
#

Well nav mesh builds XZ plane, while Unity 2D is XY plane

#

And I don't think it works anything with 2D colliders etc

orchid radish
#

mmmh when doing by hand I set the X rotation to -90 to create the navMesh over the 2D field, any way to do this with the buildNavMesh method ?

jolly token
#

You might just want to find solution for 2D A* or something other than NavMesh

#

Well you probably need to add 3D collider

#

If you want to do it with NavMesh

tame patio
#

I am trying to find rig builder in unity but cant seem to find it anyone can help?

sly grove
#

Also not sure how this is the right channel

tame patio
tame patio
wooden bronze
#

no clue if this is the right channel for it but. So I have a field in a farming game, what I am wondering is whats the best way for it to work like a proper field, more specifically when it gets plowed lets say, for it to know the area of it that was plowed and save that data so only that part of the field can have seeds planted in it but not in the unplowed area. I'm confused on what even to google for this behavior lol basically somehow splitting it up into sections and then applying a state to them. Please ping me if you can think of a place to start or what even this is called, any help appreciated!

mint python
#

Probably better to ask on 'Unity-Talk' as you haven't got as far as the advanced coding part of your problem yet ๐Ÿ™‚

crystal parrot
#

is there any way to remove mesh from headless server?

#

This works but then when i switch back to client the mesh is null

#

remove from "Dedicated Server" build

#

can i do it on PostProcessorBuild somehow?

merry cedar
#

Hello, I am working on a game and trying to find out if it its posable to add scenes to build settings with some code? I am using the SceneManager.CreateScene method but well I have not found any way this is really useful unless you can add a scene to the build settings you can't do to much with just creating a new scene.
Is there something I am missing with this or is this just something that is not used?

gray pulsar
#

but that's editor only. Build settings doesn't exist in a build. Cause... why would it?

merry cedar
viral edge
#

If I have a class called "Enemy" that inherits from "CharacterBase", and then in my Enemy class instead of just referencing variables from CharacterBase like "health", or "energy" I instead access it like "this.gameObject.GetComponent<CharacterBase>().health" is that an actual performance hit, or does Unity know to drop that GetComponent call? I'm assuming it doesn't and the extra GetComponent calls just chew up more resources.

#

Other programmer seems to think Unity is smart enough to do that, I'm saying its not and its just a performance hit to have 20+ extra GetComponent calls on the parent class.

jolly token
#

Unity doesn't override how C# works

viral edge
#

That's what I figured, it'd be one thing if we cached the CharacterBase script, but since its inheriting from it we just don't need to do that and just directly modify the parent values, etc.

jolly token
#

Yes just directly modifying sounds sane way than calling GetComponent

jolly token
#

Unity is not "smart" to do such optimization. Even getting gameObject.tag allocates

viral edge
#

yeah I've been trying to get him to use CompareTag, its a fight

plucky laurel
#

show him yanderedev code and say it starts to look like it

viral edge
#

@plucky laurel lol

#

Right?

#

Todays profiling session was "holy crap, why is there 9k GC in this script", oh hes creating lists in Update(), that would do it.

jolly token
#

You need some exorcism there

viral edge
#

I'm trying to fix him, he does a lot of decent work, just has some bad habits we're trying to break.

plush lion
#

Hey, I'm looking for a way to disable the navigations buttons on Android for a unity app that'll run in a kiosk (where we don't want people to quit the app). Is there anything to block people from quitting the app ? Google doesn't find much.

plush lion
#

thanks I'll look into it !

lime valve
#

Is there a JsonSerializer setting that will handle the deserialization of a dictionary holding save data thats from an older version? (say in this example i'm saving XP and Apple counts, but then update the game to have XP, Apples, and Gold) Every time I deserialize it's missing "updated" keys and values in the dictionary and I'm trying to avoid writing a massive function to check for differences inbetween the save value dicts.

remote drift
#

Is it possible to modify Assembly through reflection?
I have a need to create certain attributes in runtime, because Unity gave me no other choice to register smth
These attributes are only used in runtime, by specific Unity code, so modifying them shouldn't not be harmful for code execution, unless there's some pitfalls I don't know?

#

ok, it's not possible to modify assembly in reflection

#

there's simply no fields

jolly token
#

Maybe explain what you want to achieve and someone will have answer?

remote drift
#

this makes me want to install harmony so hard

remote drift
#

but Unity made it so you can customly add them only through assembly attribute

#

which get loaded dynamically

#

so annoying

#

literally no reason not to let us do that dynamically

regal olive
#

Can you perform raycasts on another thread without moving into DOTS? I have a game where I need to compute a custom created navmesh semi-frequently and the amount of raycasts that would need to be performed may cause a stutter when its computed unless its done in the background before its needed.

tender light
regal olive
#

That's what I thought. What I've been reading seems to indicate that anything in the Unity API cannot be multithreaded, only standard C# stuff.

plucky hound
#

@regal olive I used to solve things like this by having a time budget (ns) for each feature. rays could spend, say, 1ms casting per frame. as long as your creatures stay ahead of the raycasting results everything is golden.

regal olive
#

Yea essentially splitting the method across frames. Could work well

plucky hound
#

what is the raycasting for?

regal olive
#

Tile based rpg without the tiles. When its a units turn they need to know where they can move to. Essentially, a navmesh but it needs to be restricted by a maximum walking distance. Unity's built in navmesh features does not allow for this.

#

Fairly complicated, because if an object is in the way they need to account for moving around the object to get behind it which restricts how far in that direction they can go.

plucky hound
#

tile based without the tiles. so more like warhammer, measure everything with a ruler?

regal olive
#

Never played warhammer. I guess like divinity original sin 2 but I haven't played much of that either.

A bendable ruler, yes.

plucky hound
#

I'd still use an occupancy grid to quickly block out what is and isn't navigable.

#

i meant like tabletop warhammer. map is totally flexible, there's no grid.

regal olive
#

Yea if the grid was really small it would be unnoticeable, just experimenting to see if its possible to go fully gridless.

plucky hound
#

the cost of rarely inserting and removing from the grid (once per item per move) is way lower than the cost to raycast through every time in the world multiple times per move.

#

i would start with a chunky grid and only make it smaller if it's really obvious.

regal olive
#

Technically would only have to do it once when its their turn (or precalculate it in the background as it approaches their turn). Right now its just an enthusiest experiment, but you're probably right.

plucky hound
#

i spent years doing it wrong so you don't have to.

crystal parrot
#

hHeadless server for multiplayer game

#

online rpg

#

No, but this is not what i want to remove from build

#

i want to remove animations

#

and some item meshes (equipments)

#

they are not used for collision on server or client

#

because it makes server build bigger

#

69 mega bytes now but i can grow really large

#

I think i found a way

#

but it will need some careful design

#

this is working for me

#

i want to host it using less ram

#

because it can have many parallel maps

#

1 map

#

why huge mistake?

#

My goals is to have profit, if i pay too much on server i wont have

#

this is a indie game, i have nearly 0 money

#

i need to handle 500 players on a always free server

#

this is my old online game, i was using .net core and it handle 500 players on always free server

violet field
#

So I have a list of a bunch of Vector3's
These are all points around the edge of my island groups, and i want to group these points in my list, so i only keep the ones that are part of the biggest island.

Image 1 here is an illustration of the Vector3's i currently have in the list.

Image 2 is the group i'd like to keep in the list.

sly grove
violet field
sly grove
violet field
#

Right now these points are just one big mess in a list

violet field
sly grove
violet field
#

Please do enlighten me!

sly grove
#

ok you'll need to get familiar but that's for after.

#

They're standard graph search algorithms

#

basically starting at a point in the graph they are ways to traverse through all the connected points on the graph

#

anyway for the distance thing... you'll have to either do some spatial partitioning algorithm like QuadTree or just a big nasty O(N^2) comparison of each point against every other point

#

but the idea is you want to build an adjacency list

#

e.g. dictionary of points to a list of the neighbors for that point:

p1 -> p4, p5, p6
p2 -> p3, p7
p3 -> p2, p7, p9
``` and so on
#

where that list is all the points within range of that point (the neighbors of that point)

#

Once you have that list you can do DFS or BFS to determine your islands

violet field
#

Oh my.

#

Thank you alot for this! But i gotta be honest here. I have no clue where to begin. This is some advanced stuff

sly grove
violet field
#

I was just thinking that code beginner or general wouldn't know about the required algorithms i might need. So now i have some material to read up on :)

sly grove
#

here's a nice little video

sly grove
# violet field my bad :(

btw the idea of the DFS here is to determine the islands of your graph. When you do DFS from a single point you can discover ALL of the connected points to that one point. That whole collection of connected points makes up an island. Any points not in that collection must be in other islands. So you'll basically end up doing several iterations of DFS to find all the islands. Once you have the islands you can just pick the one with the largest number of points in it to answer your initial question!

violet field
sly grove
#

each HashSet is an island

violet field
#

Hmm, never worked with hashsets before. I imagine they hold the neighboring data?

sly grove
#

nope they're just unordered sets of data

sly grove
#

called an adjacency list

#

or you can make a Node object which has like a coordinate and a bunch of references to neighbor nodes

#

you'll use that to do the actual DFS/BFS

#

basically the whole algorithm would be like (pseudocode)

List<Point> allPoints;
HashSet<Point> visited = new();
List<HashSet<Point>> islands = new();

foreach (Point p in allPoints) {
  if (!visited.Contains(p)) {
    HashSet<Point> island = PerformDFSStartingAt(p);
    islands.Add(island);
    visited.AddRange(island); // we can ignore all the points in this island going forward
  }
}

int largest = int.MinValue;
HashSet<Point> largestIsland;
foreach (var island in islands) {
  if (island.Count > smallest) {
    largest = island.Count;
    largestIsland = island;
  }
}
#

where PerformDFSStartingAt is a function that runs DFS from a point and returns a set of all the points in the island that point is a part of

violet field
violet field
violet field
sly grove
#

it's just adding all the points from the island to the visited set

sly grove
violet field
#

and that function is type of HastSet<Vector3> yes?

sly grove
#

yes

#

you'll need to write that function though

violet field
viral edge
#

We have a modifier class for adding dots, stat buffs, heals on players. He was in our Update routine creating a new list of modifiers to remove every frame, and checking every modifier if it was time to be removed...for every NPC in the game. ๐Ÿ˜„

#

First level had 119 npcs, so he was creating. resizing, and then clearing ~120 new lists every frame.

cerulean scaffold
#

Hi everyone, are floating point numbers deterministic on the same architecture?
Are there differences between Intel and AMD?
I couldn't find any forum posts about this topic. I only found information about determinism within burst.

maiden turtle
#

Is there a way to prevent unity from deleting meta files of inexistent files when running in batchmode? The use case is restoring packages with nugetforunity from the command line. The meta files contain configuration like for which platforms should a dll be used and whatnot, plus, if referenced in asmdefs, I might want to use the guids instead of the names. The two ways to get around this is git resetting the meta files within packages after restoring them, or code up a script that would restore on the side with packages.config and then extract then into unity

maiden turtle
#

If you want to binary serialize floats though, it's not hard to convert to and from the standard format

#

I have done some code on this, should work as a starting point, but there might be bugs

cerulean scaffold
#

My goal is deteministic lockstep networking with good performance. Currently I'm using soft floats but recently I discovered that floats in burst are deterministic between Intel and AMD as long as they are on the same architectur (x32 / x64)

#

No a Unity dev said so himself

#

no I'm not using physics

maiden turtle
#

I haven't tried that, but I'd guess unity will try to delete a meta file and crash

cerulean scaffold
#

Now the only question remaining is if it's the same outside of burst ๐Ÿ‘€

#

Btw Saying 'Dots in general is deterministic' is a bit eh. Copying or moving entities isn't deterministic for instance.

#

I already got working prototype with deterministic lockstep it works fine :p

#

a bit of extra convenience and performance by default would be nice that's why I asked my question here

mighty sonnet
#

I'd like to actually include the files of a Unity builtin package in my project as local files so that I can slightly modify one of them. Is there a cannonical way to do this?

maiden turtle
mighty sonnet
#

...trying

#

Should I then remove from the manifest using package manager? Since it's included manually/I don't want them to get out of date?

#

@undone coral Thank you extremely-a-lot also, you're saving my day ๐Ÿ™‚

#

Ah dang, I did this and now it doesn't recognize the UnityEditor.TileMaps namespace cannot be found

#

No I'm not

#

"it" is Unity and my IDE I suppose. Getting Assets\Source\Script\PrefabBrush\PrefabBrush.cs(8,28): error CS0246: The type or namespace name 'GameObjectBrush' could not be found (are you missing a using directive or an assembly reference?)

#

But I'm not using assembly references in this project

#

It cannot find UnityEditor.Tilemaps, the package I moved

#

MyProject/Packages

#

oh, OK. So I should have it installed both through the packagemanager AND copied into the directory?

#

OK, I've added it back!

#

Ah wonderful, I'll give it a read, thank you

#

Yup, using source control on this, definitely good call ๐Ÿ˜‚

#

Thanks very very much, really made my day

#

If someone ever asks you again, I think what it needed was to have the @<package-version> removed from the folder name after copying in order to be picked up by Unity.

languid sinew
#

I've got an idea I don't know how to implement, I'm making a deckbuilding tool for a card game I like, and I want to add a deck analitics screen, as well as maybe more screens in the future, so I came up with an idea, I want to basically mimic the unity editor tabs, so you have two windows, one on either side of the screen, with tabs at the top with every screen possible, the issue is, I want people to be able to put the deck screen on either side, and it edit the one and only deck, so I can't duplicate everything twice

#

How would I make basically a portal to another place in the world

#

Aka, I want to have all my screens offscreen, and when you want to see one, make a portal from on screen to infront of it, and carry over the mouse clicks and what not

#

that way you could even have two copies of the same screen that both click the same buttons and everything

#

Here's a visusal explanation

#

Basically, the portals are there so you can easily switch to other screens, move the screens around, or display multiple of the same screen

#

Ok, but I can't duplicate or move this arround

#

I do

#

I want two tabs

#

not just one

#

Yeah, but two tabs that both have every screen

#

And can both display the same screen at the same time

#

Well, if I duplicate it, they wont both be editing the same screen, they'll be editing different screens

#

and then I'll have to duplicate it every single time I add a new one

#

No, like in the deckbuilder I have a library side and a deck side

#

the deck is a screen

#

I use screen for lack of a better word

#

Ok but they need to both edit the same screen

sly grove
languid sinew
#

they can't just edit their own instance of the screen

languid sinew
sly grove
#

cleanest way would probably involve a custom input module

torn basalt
#

Hey, I am creating a cube mesh from scratch. I then want to raycast to that cubes a face on that cube and return the normal and the associated verts of that face. I have been stuck for days on this. I understand that you can get the 3 verts from the hit info but I do not understand how to get the 4th. Can anyone provide guidance?

long ivy
#

is it always going to be a cube? an easy way would be to collect vertices that belong to a triangle whose normal matches the raycast result. You could pre-cache this and then just do the lookup via normal direction (in local space) if you are planning on doing it often

torn basalt
#

Yes, it will always be a cube. Would the position of the cube matter if say I wanted to return all that had a y value of greater that 0 but then moved the cube itself below zero

long ivy
#

no, if you're getting the vertices from the mesh. They will be in local space

torn basalt
#

ahhh.

#

I am struggling with this part here

"collect vertices that belong to a triangle whose normal matches the raycast result. "

long ivy
#

each triangle is composed of 3 vertex indices. Scan through these triplets and calculate the normal of the triangle they create (use cross product - script reference has an example of exactly what you need to do)

frozen imp
#

@crystal parrot Don't cross-post, please

crystal parrot
#

ok

fathom locust
#

I'm working on an AI system and I have plenty of experience making state machines and function flow stuff. But I keep debating whether to make the AI brain a component on the actor itself or a separate "cpu player" object.

What would you guys do?

plucky laurel
#

that is solely dependent on what is common for the rest of your project, there is virtually no difference

chilly nymph
#

What's the process with webgl and serializating? Do we have access to local storage with a js plugin?

tired escarp
#

Hello all,
I have a problem with the Jobs system. Here is a simplified version of it:
I have a struct that I pass to jobs and also use in the main thread (let's call it StructPassedToJobs), which contains a NativeArray (let's call it nativeArrayInStruct). I want to be able to modify nativeArrayInStruct sometimes, but only when no jobs are running. So I can't set the nativeArrayInStruct to [ReadOnly] within StructPassedToJobs. I used to just mark StructPassedToJobs as readonly (using the keyword) in the 2019 version but in 2020.3 I get the exception:
InvalidOperationException: The previously scheduled job MyJob writes to the Unity.Collections.NativeArray`1[ArrayContent] MyJob.structPassedToJobs.nativeArrayInStruct. You must call JobHandle.Complete() on the job MyJob, before you can read from the Unity.Collections.NativeArray`1[ArrayContent] safely.
The job should not be able to write to nativeArrayInStruct here because MyJob.structPassedToJobs uses the readonly keyword. Which did have this effect in 2019 (I tried removing it and got the same exception).
So my question is: What's the proper way to protect the readonly access here?

rugged radish
#

readonly keyword doesn't make containers immutable iirc

#

it just protects the reference from changing

#

so you have to use the attribute

tired escarp
#

Except, based on my experiments, for NativeContainers.

#

Where should I put the attribute? On MyJob.structPassedToJobs or StructPassedToJobs.nativeArrayInStruct?

rugged radish
#

on the native array that jobs never write to

tired escarp
#

Sorry but that doesn't resolve my conundrum.

#

I need it to be read-only for only some jobs.

#

All of which get passed StructPassedToJobs. So where to put it?

rugged radish
#

and main thread must claim ownership of the job handle before modifying the array
I don't think [ReadOnly] affects main thread in any way

tired escarp
#

and main thread must claim ownership of the job handle before modifying the array
Oh, that's new to me.

rugged radish
#

yeah, it says that in the error too " You must call JobHandle.Complete()"

tired escarp
#

Right. But can I do nothing with the contents of the NativeContainer in the main thread while the job is running? Not even read it?

#

The problem is I get the error when trying to read it.

#

Because it thinks the job is writing into it, which it isn't.

rugged radish
#

never tried reading in that specific scenario, can't say for sure

tired escarp
#

But still (and sorry for insisting): In my scenario, where do you think [ReadOnly] belongs? On MyJob.structPassedToJobs or StructPassedToJobs.nativeArrayInStruct?

#

That is, when the job is getting a struct containing a NativeContainer, not a NativeContainer directly. I very much hope this is not impossible, as I have some fairly complicated data structures.

rugged radish
#

if I understood it right StructPassedToJobs.nativeArrayInStruct is the NativeArray that jobs read from, but never write to, so it should be marked as [ReadOnly]

tired escarp
#

OK, but that would ban all jobs that are passed StructPassedToJobs from ever writing it?

rugged radish
#

correct

tired escarp
#

Just to be clear: This would mean the [ReadOnly] tag would be somewhere other than the type implementing IJob, which comes off kind of odd to me.

rugged radish
#

oh, it doesn't implement an IJob

tired escarp
#

StructPassedToJobs does not implement an IJob. MyJob does, of course.

#

But as per your suggestion, [ReadOnly] would be placed in the former, not the latter.

rugged radish
#

not a use case I'm familiar with, can't help here either

tired escarp
#

OK, thanks for your thoughts!

#

I'll just have to run some more orderly experiments then.

rugged radish
#

at least it lets you put [ReadOnly] on a container inside a regular struct
so it looks like this may work

#

can't actually test it right now

tired escarp
#

Well, according to my simplified testing, it's fine to put [ReadOnly] on MyJob.structPassedToJobs.

tired escarp
#

I'm afraid not, since my code doesn't seem to agree with what you wrote. But I need to narrow it down more to ask useful questions.

#

I haven't used .AsReadOnly (wasn't aware of it).

#

So... the NativeContainers themselves have a read-only flag? I thought read-only was a property of a field, not their content.

#

All right, I'll try the .AsReadOnly.

#

OK, well, that works, though applying that to my current design (where I have a big structure of nested structs and NativeContainers) would be quite difficult and clunky. I'd really much prefer to just use the [ReadOnly] attribute...

#

Yeah, no, that's not 5 minutes, more like 5 days.

#

The weird thing is, this whole setup doesn't even produce any errors in 2019.3, even without the [ReadOnly] attribute.

#

Yeah, that's why I need to narrow this problem down so I can actually ask a proper question.

#

Navigation.

#

I have huge arrays of complicated data that represents the lay of the land, and I feed that to jobs.

#

Navigation of NPCs in a 3D action game.

#

Multiple kinds of pathfinding, yes.

#

The environment doesn't change often, no.

#

The environment needs to be able to change every once in a while, in the main thread.

#

Yes, I'm using A-Star.

#

I'm also using a homebrew obstacle-avoidance algorithm.

#

Yes, it's been working fine in 2019.3 and I've put quite a lot of effort to it. It's only started to complain about these (theoretical) race conditions in 2020.3.

#

Perhaps. Though again, I'll need to narrow down the problem unless I'm going to give them my whole project to investigate.

#

Perhaps it will. Either way, thanks for your efforts!

#

I don't think I did this.

#

I was not writing into that container from that job.

#

That may work, though I didn't even upgrade the collections...

#

(But when I did, it still didn't work.)

#

Anyway, I'll get back to narrowing it down. Thanks for your time!

tired escarp
#

There's no toggle or something somewhere that turns the [ReadOnly] attribute on and off, is there?

#

Because I've now narrowed it down to a trivial case and it's still not working, even though it's working fine in a separate test project.

real blaze
#

hey. does anyone know how to create somethig similar to sub-assemblies in Unity? I know it's not possible to create sub-assembly, but I want to have a assembly that has access to internal fields of another assembly. is it possible in Unity?

jolly token
#

And if you want other assembly to access internal, use this

real blaze
real blaze
jolly token
real blaze
#

oh

#

right

#

actually I saw that in a stackoverflow, but haven't seen any thread on how it'll work with Unity

jolly token
#

[assembly: InternalsVisibleTo("TheAssembly.YouWantToShow.Internal")]

#

It works the same

real blaze
jolly token
#

What? ๐Ÿค”

#

You put that in the source code

#

That's C# attribute

#

Which one is assembly you want to expose internals
And which one is going to reference internals?

real blaze
real blaze
#

@jolly tokenthanks ๐Ÿ™‚! did some research for the attribute u told me, and got it to work as expected

#

the idea of a class-less file was totally new to me

jolly token
torn basalt
#

Hey, I am working on some stuff in VR and can't figure out how to determine the direction my controller is moving. I have tried Dot product and Magnitude but can't seem to get it right. I am basically using the controller to push in a set of verts. I got the verts reacting to the position of the controller but its way off.

What I am looking for is a way to determine the direction my controller is moving relative to itself. If am pushing forward I want a positive value or if I am pulling then return a negative value;

I want to basically remap that to a smaller value (-1 or 1) so that I can add that value to the z or y or x of the verts.

#

yea

#

Yea this makes sense. I never would have thought of using the constraint lol

#

i even tried setting the parent on the oppiste side and setting the anchor as the parent of the cube and then just scaling on the axis but even with adding offset to the axis per the amount scaled it just seemed to not work very well

tired escarp
#

I've finally narrowed it down enough that it makes sense to do this. Thanks for the suggestion!

torn basalt
#

lol I am

#

deadline. creeping

#

first time working with Procedural Meshes

#

So I am creating a clone of the orginal mesh and I am manipulating an array of Vectors and updating the meshs vertices array with the one I am manipulating. Then on button release I recalculate the mesh

#

This is def something I will look into.

#

After I make it past today

keen axle
#

I have an unsual question, is there a programing tool or injection program; whose purpose is to auto determine the runtime complexity of a particular program/algorithm? Is something like that out in the field already?

#

I'm getting ready to officially join the cs field as a college graduate, and I just had an idea on a software, and I'm not certain if its been done already.(i feel like it already has been)

#

so the database manager/planner dose that process in unity already? still getting used to sql stuff

#

ohhhhh

jolly token
#

You want to analyze the complexity?

keen axle
#

i guess that means there isn't a program that has been released commerically that dose that.

#

yeah

jolly token
#

Well there is Profiler that doing it by data-collecting

#

Not by algorithm

keen axle
#

yeah that was how i was thinking about doing it

jolly token
#

The Profiling tool itself is integrated in Unity btw

keen axle
#

do you think it would a pretty useful tool, if the tool did exist?

jolly token
#

Uh.. depends on how do you use it?

tribal pivot
#

Here i think is a difference between a CS student, and a programmer.
As a gamedev, it is not interesting to me if some routine is o(n) or o(n2). The former with 10000 inputs might very well be slower than the latter with only 2 inputs.

This is why its common to use a profiler, and not some analyser. Profilers measure how long your computer took to do something, that is what we are interested in at the end of the day

sly grove
silk sable
#

In my code, OnEnable() has a problem with an unitialized value that is initialized in Awake(), isn't that not supposed to happen with the normal order of execution?

silk sable
inland delta
#

awake -> onenable -> reset -> start

silk sable
#
Obj1.Awake();
Obj1.OnEnable();
Obj2.Awake();
Obj2.OnEnable();
Obj1.Start();
Obj2.Start();

Actual order of execution actually looks something like this

#

which is objectively stupid

#

and unsaid in the docs

maiden turtle
#

and I believe it is highlighted in the docs

silk sable
#

aka it's stupid

#

and it makes coding around it stupid

maiden turtle
#

It doesn't really make sense to be consistent across all objects. If you instantiate something at runtime, these methods run on instantiation, instantly

inland delta
#

stupid would be:

  • Iterate through scripts
  • Execute Awake
  • Iterate through scripts
  • Execute OnEnable
  • Iterate through scripts
  • Execute Reset
  • Iterate through scripts
  • Execute Start
#

when you can just do it once

#

also its really easy to get around this

#

just change the project settings execution order and you're good to go

silk sable
silk sable
maiden turtle
inland delta
silk sable
#

I don't want to fix my code issues in the editor

#

no thanks

silk sable
#

If you can't see the issue then there's no point talking

inland delta
#

that seems like a problem to me

tribal pivot
silk sable
tribal pivot
#

...

inland delta
#

damn, good luck spawning 300 threads

silk sable
silk sable
#

did you ever multithread ?

inland delta
#

yeah, did you ?

silk sable
#

I coded my C implementation I think i'll be fine

inland delta
#

nice, so there's no point in crying on a discord server about something that's really not a problem

#

for this there's Twitter

silk sable
#

Yet you are here crying back

#

curious

#

Live by your words

inland delta
#

well, i never had any problem with the script execution order in my 6 years of using Unity daily and i don't see any beginners having this issue very often, however here you are in #archived-code-advanced

silk sable
#

Like described before, I had a misunderstanding about the execution order

#

It's true that optimally these would not be used very extensively

#

I'll keep that in mind next refactor/project

#

Maybe i'll try, I do implement events into my game logic the more I grow as a dev

chilly nymph
#

What's the process with webgl and serializating? Do we have access to local storage with a js plugin?

upbeat path
chilly nymph
#

I don't think the only option is a emscripten plugin.

upbeat path
#

nope, dont work in browser

upbeat path
#

That is emscripten

chilly nymph
upbeat path
#

I did not say it doesn't work, I said that is your only option

chilly nymph
#

Is PlayerPrefs stored locally in a web application?

#

Yes but I don't know about that, as I've never heard of it. Need to check the docs.

#

Local storage is key value.

#

So I don't know where indexeddb is.

upbeat path
#

in WebGl indexdb is Application.persistentDataPath

chilly nymph
#

WebGL: Application.persistentDataPath points to /idbfs/<md5 hash of data path> where the data path is the URL stripped of everything including and after the last '/' before any '?' components. hmmmm

upbeat path
#

yes, and?

chilly nymph
#

Where data is stored.

#

But looking at the docs it does look like the prefs work.

#

No please explain what a computer is.

#

Slow, you're going too fast.

#

"opposed" is a big word, going to need help on that one too.

#

But that answered my question, thanks gents.

upbeat path
#

ffs
Application.persistentDatapath in webgl stores data in the indexdb do you need more information than that?

chilly nymph
upbeat path
chilly nymph
lavish sail
#

can you guys not turn into 7YOs on xbox live chat

chilly nymph
lavish sail
#

I'm talking to both of you

chilly nymph
#

But due to web security I also assumed the only option was a plugin, so I'm glad I asked here didn't know about any other options so thanks mate.

#

fukn cors.

winter obsidian
#

can i use a phone as a display for the camera to render? for example, someone can use their phone as hider and another one the monitor as seeker, can this be done with something like Bluetooth or do i have to make an app?

upbeat path
# chilly nymph Says the guy who literally had no idea about player prefs and said the only opti...

Use the Player Prefs Plus from SteveSmith.Software on your next project. Find this utility tool & more on the Unity Asset Store.

Use the Player Prefs Lite from SteveSmith.Software on your next project. Find this utility tool & more on the Unity Asset Store.

chilly nymph
winter obsidian
#

no

#

local multiplayer, like a party game

#

no

#

a second camera in unity

chilly nymph
#

Multiplayer is one scene with multiple cameras in it.

winter obsidian
chilly nymph
#

On each client.

winter obsidian
#

yes i mean

chilly nymph
winter obsidian
#

can i use my phone screen

#

without having to build an app

#

for online/lan multiplayer?

chilly nymph
#

You can stream a video if you wanted but I don't know why you owould do that.

winter obsidian
#

can't i just stream to the phone

chilly nymph
#

You can.

#

WebRP

winter obsidian
#

okk

winter obsidian
#

yes

#

no, just watch

#

it doesn't matter at all, it's the same

#

yes

#

okk, thanks a lot

chilly nymph
winter obsidian
#

oh okk

#

thanks to both of you

#

thanks

#

yes

#

okk

#

no

#

wait

#

the game is on pc

#

and it streams to android

#

kinda

chilly nymph
#

Use Unity's native JSON. You really shouldn't be using JsonFX/Newtonsoft/JsonObject, it will massively balloon your code size due to the compilation of generic specializations.

How badly?

winter obsidian
#

the game is like i have a player who is the hider and then i need like 5 seekers, and the seekers can't obviously see the hider screen, but how can i do that on a pc with 1 monitor? i thought streaming a camera to a phone device could be the solution

#

oh okk, well i could try