#archived-code-advanced

1 messages Β· Page 152 of 1

iron pagoda
#

I discovered it twice. Keep forgetting about it.

merry notch
#

I got it working for characters 😁

twilit chasm
#

Is there a way to see if two agents are on the same navmesh? I wasn't able to find some kind of "navmesh ID" in the docs. Does something like this exist?

shadow seal
#

I suppose this would be the same for both?

midnight violet
#

If you really only need one particle, you might use a single particlesystem for that or just a fake particle. But you can try to set some statements in the shadergraph too to only effect particles on a specific height or position

vernal kindle
#

mmmm i understand, i'll have to delete the comment because i noticed there's a vfx and particles channel

#

thanks for the help

gleaming thistle
#

ello, how can I detect via linecast if I'm hitting an object.. if I end up inside of the object? it seems to not count as hitting if the linecast winds up even a single pixel inside of the object.

#

imagine I cast a linecast downwards, and it detects that there is something there, and moves upwards.
but if it doesn't happen fast enough, then what can happen is it ends up partially inside of the object, and then it cannot detect a hit anymore

regal lava
#

Do you mean like your line that originates is drawn inside of the collider if you get too close such that it wont detect it?

#

In my game I have two stages for my linecast; one for which I attack when I get close enough to the collider, and another collider for where I deal damage which is a smaller collider in that.

static patrol
#

There's something that I don't quite understand here. I have a cubic Bezier curve system, which generates a procedural road along it.
However, when I rotate the object containing the control points, the Bezier curve does not match the rotation, and makes it impossible to place accurately in the world, where I have to do weird positions and rotations to make it align with other instances of the road.

gleaming thistle
#

@regal lava yes exactly.
so you're suggesting I make another collider essentially? in case it gets too close to the actual block/object?

#

I manually use position move the object around and was really hoping that I could make it go up ramps smoothly, but if I need a lot of colliders to do that that's chill ig

regal lava
#

Well, it seems you're drawing the linecast too close, so perhaps you can fix it by originating it further back if you continuously need the linecast to touch a collider.

gleaming thistle
#

ohh

#

so if the origin is further back

#

then it will still detect the collision

#

thanks for the advice mate

regal lava
#

aye

heady bane
#

Could I have a coroutine call an action<string> to return the value found in the coroutine?

#

Im trying to find a generic way of returning a value from a unity web request coroutine that I can then plug into several scripts that need to get information.

heady bane
#

Good idea? bad idea?

mild laurel
#

bad idea.

somber tendon
heady bane
#

yea a callback function

heady bane
novel plinth
#

anybody knows if Unity supports FastSpan already or not?

regal olive
#

sorry for repeating but its so strange for me and dont know if its intended :/

fresh salmon
#

Do not cross-post. This isn't an advanced code question.

hollow wing
#

is it possible to call Instantiate with an empty GameObject?

#

if I do Instantiate(new GameObject(), ..) i have it twice :)

humble leaf
#

You don't need to instantiate, just create the new GameObject.

hollow wing
#

I think there are cases where not calling instantiate confuses the physics

#

when you set position afterwards

#

therefore I consider it good practice to use Instantiate always when physics is involved

fresh salmon
#

You could have a prefab of an empty GameObject you drag into a field. I wish GameObject.CreatePrimitive supported empties, it doesn't

hollow wing
#

I think I'll be using a static new GameObject intead

#

I wish GameObject.Empty was a thing πŸ˜›

#

or Instantiate without a GameObject

regal lava
#

Couldnt you just make a naked gameobject prefab and use that?

hollow wing
#

I think static is the better approach here since I have one less dependency of my code

somber swift
fresh salmon
#

Probably, no idea

somber swift
#

it should work fine

hollow wing
#

hm I'm not sure maybe though the issues with physics I had before would have gone away if:

#
  • I had the prefab GameObject set inactive
  • I enabled the GameObject from Instantiate after setting the position
#

There was some issue where Physics tests wouldn't detect new GameObjects immediately

sharp otter
#

Hi guys got a problem with my photon 2 this is the code https://paste.myst.rs/xv38y2ko and this is the error i get when ever i try to create a gameCreateRoom failed. Client is on MasterServer (must be Master Server for matchmaking)but not ready for operations (State: PeerCreated). Wait for callback: OnJoinedLobby or OnConnectedToMaster.
UnityEngine.Debug:LogError (object)
Photon.Pun.PhotonNetwork:CreateRoom (string,Photon.Realtime.RoomOptions,Photon.Realtime.TypedLobby,string[]) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetwork.cs:1782)
CreateAndJoinRooms:CreateRoom () (at Assets/Scripts/CreateAndJoinRooms.cs:15)
UnityEngine.EventSystems.EventSystem:Update () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:385) i realy need help

midnight violet
sharp otter
#

okay

#

I fixed but thx

patent wadi
#

hello i have got a question?
can we add a file to an existing executable so as to customize the keys? attention i'm talking about an exe compile no code sources.

timber flame
#

Suppose a player with ads mode ability in shooting games.
I have a simple script AimDownSightAbility. It has a boolean field IsAds (getter,setter) and an event AdsChanged.
In different situations, we want the player to exit ads mode.
For example when reloading, if they are in ads mode, they should exit and then they can reload or when equipping/switching between weapons, picking items, consuming medkit, enter vehicles, player died, etc.
They are different business logic and procedures.
My question: how do you handle it? You will have one script, listen to these events (reload,consuming,etc.) and then set IsAds field of AdsAbility instance or you will write different scripts (listeners) for each?

formal lichen
#

I usually have a singleton eventmanager that listens for events and notifies listeners when one is invoked. This is not much different in amount of code to just having one event that is triggered with references but saves lots of time in that: 1. You don't need a reference to the specific object to invoke the event or listen for it. 2. Removes spaghettification of code and helps when scaling things up.

timber flame
#

So, do you mean something like below?

#

@formal lichen

public class AdsHandler:MonoBehaviour{
    private void Start(){
        _eventManager.Subscribe(EventType.ReloadStarted,OnReloadStarted);
        _eventManager.Subscribe(EventType.PlayerDead,OnDead);
        _eventManager.Subscribe(EventType.EquipmentChanged,OnEquipmentChanged);
    }
    privae void OnReloadStarted(){
       _adsAbility.SetAds(false);
    }
    //... others
}
#

It is my first approach. You just suggested global event manager instead of separate events, perfect.
By the way, I do not like globally event manger.

formal lichen
#

yes, like that

lilac jacinth
#

Hi everyone, I have developed a VR keyboard for my university project and I have a problem with my enter key. The player to access the rest of the map has to enter his name which I save to display later in the game. Can anyone help me please?

Here is a video of my problem, I would like my input text to be displayed in the sample text and saved using the enter button.I tried to store it in a player prefs but it didn't work

formal lichen
#

I'm sure there are other ways of doing it too πŸ™‚

lofty falcon
#

Is async void okay for Start() because exceptions will be thrown on the main thread anyways?

lilac jacinth
timber flame
# formal lichen yes, like that

It hides dependencies.
Also, arguments are different. You have to use something like object and then cast or use a bit different approach like Mediator pattern. This pattern hides dependencies as well

#

I use zenject, therefore, injecting dependencies is really easy and straightforward

formal lichen
#

You can also add another parameter to your eventmanager that will pass an object to the listener. I've used dynamics in the past but that doesn't work on all platforms

#

That's kinda similar anyways to just doing object and then cast though like you said

undone coral
#

to solve this problem

#

then your VR keyboard could behave like the native keyboard

undone coral
#

use

void Start() {
  UniTask.Void(async () => { ... });
}

or wrap it to deal with exceptions. there's no documentation for the behavior of async void Start, and besides, Unity's default synchronization context is bad

undone coral
undone coral
lilac jacinth
undone coral
#

creating a mock keyboard device is just two lines in input system

#

and queueing a keyboard event is self explanatory

#

then you can queue a keyboard event with the Enter key

#

and everything would work, specifically eventsystem-driven stuff like UGUI input fields

raw path
#

Hi there
how do you guys store/manage localization entries in your projects?
I'm using a simple .json file with key/value pairs per language but I find that a bit tedious to edit

lofty falcon
undone coral
#

Unity’s people don’t make games, but UniTask’s authors do

#

it works better

raw path
wintry turret
#

I am currently following the Unity documentation for Graphics.DrawMeshInstancedIndirect. I would like to rotate each mesh individually in the Z axis. How can I manipulate the unity_ObjectToWorld or unity_WorldToObject to achieve this?

sly grove
wintry turret
#

I'm working in the shader provided by Unity's example:

void setup()
        {
        #ifdef UNITY_PROCEDURAL_INSTANCING_ENABLED
            float4 data = positionBuffer[unity_InstanceID];
            //handle scaling
            unity_ObjectToWorld._11_21_31_41 = float4(data.w, 0, 0, 0);
            unity_ObjectToWorld._12_22_32_42 = float4(0, data.w, 0, 0);
            unity_ObjectToWorld._13_23_33_43 = float4(0, 0, data.w, 0);
            unity_ObjectToWorld._14_24_34_44 = float4(data.xy, 0, 1);
            //retrieve rotation from buffer
            float rot = radians(data.z);
            float c = cos(rot);
            float s = sin(rot);
            float4x4 rotateZMatrix = float4x4(
                c, -s, 0, 0,
                s, c, 0, 0,
                0, 0, 1, 0,
                0, 0, 0, 1);
            unity_WorldToObject = mul(inv(unity_ObjectToWorld), rotateZMatrix);
        #endif
        }```
No matter how I modify unity_ObjectToWorld, my meshes won't rotate in the Z axis. How should I do it?
cedar ledge
#

are you supposed to be using data.w everywhere?

wintry turret
#

data.w is the size that I pass in

#

data.z is the rotation angle in degrees

cedar ledge
#

what does it do, if not rotate on z axis?

wintry turret
#

It scales fine, but does not rotate the meshes

sly grove
cedar ledge
#

well yeah

wintry turret
#

I did

cedar ledge
#

that's what unity_WorldToObject = mul(inv(unity_ObjectToWorld), rotateZMatrix); is

sly grove
#

oh sorry

#

missed that somehow

cedar ledge
#

does positionBuffer contain rotation information?

wintry turret
#

yes. positionBuffer is a float4 containing (xPos, yPos, zRot, size)

cedar ledge
#

have you confirmed that setup() is being called

wintry turret
#

Yes.

cedar ledge
#

so changing the xyz of data does nothing at all?

#

forgive me but can you explain the purpose of data.xy in unity_ObjectToWorld._14_24_34_44 = float4(data.xy, 0, 1);

wintry turret
#

That updates the position of each mesh

cedar ledge
#

i feel like that might have something to do with it

#

do x and y rotations work?

wintry turret
#

No rotations work. The lighting on objects changes, however.

#

So maybe the normals are being rotated without the mesh rotating?

#

Just a guess that's probably wrong

cedar ledge
#

show me your vertex shader

#

i was going to suggest what happens if you change that line to unity_ObjectToWorld._14_24_34_44 = float4(data.xyz, 1); but lets put that on hold for now

#

i think that ^ will add z translation not rotation

wintry turret
#

The render call looks like this: Graphics.DrawMeshInstancedIndirect(instanceMesh, subMeshIndex, instanceMaterial, new Bounds(Vector3.zero, new Vector3(100.0f, 100.0f, 100.0f)), argsBuffer);

cedar ledge
#

oh its a surface shader

wintry turret
cedar ledge
#

did you change float4(data.xyz, 1); to float4(data.xy, 0, 1); yourself?

wintry turret
#

yes, as data.z is not the zpos

#

Rotating around the X gives this:

#

Around the Z gives this:

#

These are cube meshes

gleaming thistle
#

say we have object A here [plr] and object B [can pathfind around walls]
at the start, object B is at the same position as object A, however, it then pathfinds around walls etc.
now, suppose it takes a moment for object B to find the path.
as such, to make movement look smooth, object A is to smoothly move towards object B.

#

however, object A does not pathfind, so, as a potential solution, I've done something like so;

#

obj 1 follows 2, 2 follows 3, etc all the way to object B

#

object A follows obj 1

#

but despite my best efforts, replicating this actual behaviour seems impossible

#

something like this happens at every corner

#

imagining all those cubes as obj 1,2,3, etc

#

basically it follows the path just fine following object B, but anytime B needs to figure out a new path, there is a slight delay.

#

and because of this, the player will sometimes reach a point on his way to an end point, and stop briefly.

#

I want to make the player slower overall and never stop moving until the end

#

without running through the walls

wintry turret
#

MonoBehavior:

computeShader.SetBuffer(kernelIndex, "buffer", buffer);``` Computer Shader:
```int i = buffer[0];``` I have not filled the buffer, so `i` will be the default value. What is the value of `i` here?
long ivy
#

undefined; will vary by platform

wintry turret
#

yikes

undone coral
undone coral
undone coral
#

i don't see how this is an issue for pathfinding. that kind of world is easy for navmesh, provided you choose the correct agent radius

gleaming thistle
#

I wrote the pathfinding, not using navmesh

#

I have a pathfinding script.
it generates partial paths
when you click, it generates a path towards that position.

#

it's grid based

gleaming thistle
#

it works fine

undone coral
#

why aren't you using aron granberg a* then?

gleaming thistle
#

because it was too hard for me to wrap my head around lol

#

look I don't need advice on the pathing itself atm lol

#

it works fine, it's just when I generate a new path

#

theres some time in between

#

and I want to hide that by smoothly moving towards the object pathing

undone coral
#

you can generate partial paths. that's for you to implement

#

in A*, there's no guarantee that its path x_0 ... x_i will be part of the fully computed path x_0 ... x_destination

gleaming thistle
#

I'm not sure I'm wording myself well here.
it pathfinds. it avoids all the walls and gets to the end position

#

I'm just trying to make it smoother

undone coral
#

that's just a limitation of what it is. the right approach is to make pathfinding as fast as possible

#

you're saying there's time between asking for a path and getting the solved path?

gleaming thistle
#

yes, it's very little but it's visually displeasing

undone coral
#

and you'd like to somehow lerp towards an incomplete path?

#

i'm telling you that it's not possible to make that behave well in the general case with A*

gleaming thistle
#

no, I'm trying to lag behind the completed path a bit, basically.

undone coral
#

well are you computing a partial path at all?

#

a partial path could mean, "just in the direction of the destination"

#

think a bit more abstractly, if you're aspiring to not use aron granberg's A* or navmesh

#

otherwise you've made things harder for yourself, because you're attempting to replace an asset you don't understand

gleaming thistle
#

I'm not sure why you feel the need to just, idk, insult me. I'm asking for help smoothing stuff out, not for the actual pathfinding

#

I feel like I've been responded to a bit harshly without much reason.

undone coral
#

sorry, i'm getting to the core of the issue

#

in math terms

#

what you're trying to achieve.

gleaming thistle
#

ok, I'll try and be exact

undone coral
#

it sounds like you're saying, "i ask for a path. it takes some time to get a full path. i want th eobject to start moving as soon as i ask for a path"

#

is that correct?

#

as opposed to, waiting until you get the path

gleaming thistle
#

not exactly

#

sorry

undone coral
#

you want to smoothly move between points on a grid?

gleaming thistle
#

basically. but I can do that, to an extent already.
the problem is this:
I click somewhere
it generates a partial path towards that somewhere
I begin to follow that path.
at the end of the path, it generates another partial path.
Repeat until at the end point.

#

which works fine, but in between, when it generates the next partial path, there's a bit of delay.

#

before that path is generated

#

so to make the movement look smoother, I want to follow the pathfinding object with another object, a bit behind it

#

so that in the time it takes to generate the next path, I won't have stopped moving [or at least, not for as long]

undone coral
#

why are you doing it that way

#

why are there multiple partial paths

gleaming thistle
#

because the grid is around the player. the world is going to be huge

undone coral
#

why doesn't it just compute a path to the end point

#

how would you know which points are "in between"

#

you might choose wrong ones

gleaming thistle
#

it does compute a path to the end point. here lemme grab a short video without any of the trying to smooth stuff

undone coral
#

there's no guarantee that

Vector3[] ChoosePointsInbetweenHereAndPath()

and

Vector3[] AStarPathfindingPath

will share any points at all

#

so why are you generating partial paths

#

i don't understand what problem that solves

#

conceptually, you want to do something liek

AStarPathfindingPath()
 // tween between all the grid path
 // points
 .Select(gridPath =>
   DOTween.DOMove(gridPath, duration: 1f))
 // sequence them
 .Aggregate(new Sequence(),
   (seq, tween) => seq.Append(tween))
 // play the sequence
 .Play(); 
#

i don't think you want to/ need to generate partial paths at all

#

i don't see what problem it solves

#

are you saying because the player moves and changes the path?

#

that's why you are using partial paths?

#

"partial paths are my approach to solve the problem that the agents may run into the player, which is moving, if the player intersects the computed path"

gleaming thistle
#

the grid is around the player. the player of course aligns gridded.

#

I can't grid the whole world because it would take up too much resources

#

or lag

#

or something

undone coral
#

hmm

gleaming thistle
#

idek the technical terms here, but if I were to generate a grid and check for all the walls, it would either lag or take ages

#

if I did it for the entire worldsize

undone coral
#

okay well

#

what if i told you it's impossible to just ad-hoc a solution to that problem

#

you either use the solution from literature, or you will do something that won't work

#

do you believe me?

#

i don't mean to be disappointing

#

it's just really mathy

#

i hear what you are getting at

gleaming thistle
#

I'm tempted to believe that.

undone coral
#

i'm not sure that aron granberg A* even deals with it correctly

#

i can check for you

gleaming thistle
#

but I also believed that I wouldn't be able to make a pathfinder

#

so I've been hopeful

#

lol

undone coral
#

yeah it's still a good thing to have done πŸ™‚

gleaming thistle
#

this is what I mean, visually.
in case I still wasn't clear enough.

#

but I think you got the gist already

undone coral
#

yeah

#

i get it now

#

looks good

gleaming thistle
#

it just feels clunky when it stops midway for a split second. even just a tiny bit of smoothing it out somehow would make it look so much better lol

#

of course, I could quite easily smoothly follow the pathfinder, but then it could clip through corners and stuff

undone coral
#

this is bresenham's

#

this turns the floating-point lines from navmesh into grid movement

gleaming thistle
#

||just wishing I didn't make a 600 line script for a click to move game for nothing||

sand raven
#

is there a way to increase the limit of the StackOverflowException? I know my recursion isnt infinite, its just really big

tropic lake
#

first answer

#

read the warning because if you're running into an overflow you need to reconsider what you're doing

glacial wedge
#

Hi, I want to know if there is a way in C# to use GetComponent<T> where T is customizable from inspector

brittle pumice
#

wondering if someone could help me with a custom package workflow question

flint sage
#

@brittle pumice Ask away

brittle pumice
#

@flint sage so i have a custom package

#

with samples

#

the package in on remote git

#

so now i want to update the example

#

with a unity asset

#

my first thought was to clone the package into a new project under assets folder

#

update with a new unity asset and push

#

but the new asset is not short path

#

so it Asset/Samples/SampleA/MyNewAsset.xxx

#

so what is the workflow for a package change like this?

brittle pumice
#

or am i way off in the whop whops

austere jewel
#

What is the actual complication?
You can pull a package locally, reference the location as a local package (just add the package.json via upm), and then update its contents.
If you want to make a sample in the package, you just follow this https://docs.unity3d.com/Manual/cus-samples.html
Have your stuff under a folder named Samples~, remove the ~ while working and add it back when you commit (or use another method like symlinks)

brittle pumice
#

ok maybe it was that i committed without ~

mental rapids
#

hello !
Does somebody know how to get the parameter of a unity event by script ?

mental rapids
#

no, i don't want to add event by script
I need to know the type of the unity event parameter, to know the parameter is a bool, and get his value (true or false)

#

i am comparing two unity event, here, i am just doing that :

#

but if the parameter of the uniity event is a bool, i'd like to know if its false or true

midnight violet
#

Oh, so you want a generic parameter

mental rapids
#

i want a generic parameter ?
Don't know what you mean by that :/

midnight violet
#

you want to listen to multiple unity events, without knowing, what params they have when get triggered, some have bool, some have int or stirng, right?

mental rapids
#

Nope ahah

#

i explain what i have now

#

i'va made a tool, wich will take all the unity event variables in the scene, every where in every script

#

it will compare all these event to one unity event

midnight violet
#

What does it compare? so you got an array of UnityEvents and you compare it to what object?

mental rapids
#

i compare it to an other unity event

#

like this :

#

you see that i try to find all the unity event like this one :

#

i find two object where there are this event, but i don't compare the parameter, event if the parameter, here the bool, is true or false, it will indicate me that its the same event

midnight violet
#

Oh wow, okay. Not gonna ask why you do that πŸ˜‰ but you want to do what now?

#

Like what is your script and where are you struggling

mental rapids
#

so here i have my unity event comparaison method

#

i check the target, and then the method name
and now i need to check the parameter

#

so i need to get the parameter of the function

midnight violet
#

Oh no, you need the arguments, right

mental rapids
#

ouuuuh yeah its maybe that

#

okay, i don't find this functioon on my event ahah

midnight violet
#

What unity version are you on?

mental rapids
#

2020.3.16

midnight violet
#

Hm, should be available

#

I am on 2021.2.2f1

mental rapids
#

yeah, but here its just the method name

midnight violet
mental rapids
#

ooooh, i think i'm just stupid ahah

#

i think i can do something with that, thank yoou very much dude

midnight violet
mental rapids
#

after some test, i can't really get the parameter of the function like
I spend my time on forums and i don't find any solution, if somebody have an other solution, tell me !

#

https://answers.unity.com/questions/1310341/how-to-get-parameters-of-unityevent-that-i-set-in.html
i've find this, wich work, but i need to knwo what is the type of the parameter, and i will not know it

small badge
#

I wouldn't expect the parameter of the function to be available; it's very much something that user code shouldn't need to worry about. I'm surprised there are APIs to get any information about the persistent subscriptions.
If this is in editor code only, though, a fallback option would be to serialise the event and read the information you want out of the serialised object.

mental rapids
#

i'd like to don't have it in the editor, but i can probably mdodify my code to have it only in editor

#

but i don't need this at runtime, if it was the "question"

small badge
#

Oh, actually that's the approach the link is saying, too. Well, then that's that; you're not going to get the type of the method out of the event because it doesn't store that information; you'd have to look it up yourself by looking up the method on the target object's type.

#

(And if there are multiple methods with the same name on the target object I guess you'd have to experiment to see which one UnityEvent calls? As far as I know that's not documented anywhere.)

mental rapids
#

i had an idea, but idk if it can be done
Like as parameter, we can have an int, float, string, cinemachinepath and a lots of other things
Do you think i can get the parameter as string ?
Like imagine the parameter is a GameObject (nammed "myGameObjectAsParameter")
do you think i can do somethink like mySerializeObject.getParameterAsString ?

#

and don't need to check if its an int, a bool or other ?

small badge
#

No. Even if it allowed you to get the properties as the wrong types, the different argument value properties all have different names.

#

Depending on what behaviour you actually want you could possibly get and compare all of the serialised argument properties, including the unused ones.

mental rapids
#

i've found that, but cant define what is the "method" variable

violet fjord
#

Hi, I'm struggling to understand how to connect to a database and wondering if anyone can help. I have a PHP script to check info for a login against my database but I'm not sure how to run it. I'm following a tutorial but it doesnt match with the database type I'm using

#

This is the line that fetches the PHP script but I'm not sure if this is the correct way to do it or not

hollow garden
#

me when the WWW www = new WWW

violet fjord
#

I'm just following the tutorial : (

#

And making changes where required.

shadow seal
#

Nowadays we use UnityWebRequest, it probably tells you WWW is obsolete

violet fjord
#

Yeahh, I saw that but I really am not sure how to go about this other than following the only tutorial I've found that has made some sense.

sweet briar
#

here is something I've used.

IEnumerator GetUsers(string URL)
    {
        using (UnityWebRequest www = UnityWebRequest.Get(URL + "/GetUsers.php"))
        {
            // Request and wait for the desired page.
            yield return www.SendWebRequest();

            string[] pages = URL.Split('/');
            int page = pages.Length - 1;

            switch (www.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                case UnityWebRequest.Result.DataProcessingError:
                    Debug.LogError(pages[page] + ": Error: " + www.error);
                    break;
                case UnityWebRequest.Result.ProtocolError:
                    Debug.LogError(pages[page] + ": HTTP Error: " + www.error);
                    break;
                case UnityWebRequest.Result.Success:
                    Debug.Log(pages[page] + ":\nReceived: " + www.downloadHandler.text);
                    break;
            }
        }
violet fjord
#

maybe this is a dumb question but why does every tutorial or explanation involve a http address. I just want the script to be accessed through the project.

#

I have no idea what I'm talking about tbh

#

Did database stuff for my last uni module but crazily enough it taught me literally nothing because it was just copying things off a slide.

compact ingot
#

what kind of database is that?

#

is it your own? do people with your (game)client have to access it eventually?

violet fjord
#

For a login yeah

#

using mariaDB

sweet briar
#

In my example it's getting a PHP file, running that PHP file's logic, which picks information from an SQL database and returns it as json, which C# then serializes into a class

compact ingot
#

do you want to connect to the database directly (with all the security problems that has)?

violet fjord
#

I'm not sure I understand what you mean

#

I think maybe I should give up on this, its way above my level.

#

Any recommendations for courses or anything

compact ingot
#

usually you would build a server that accesses a database on its local/private network and processes all requests for data and offers responses to the internet

#

for security reasons people will be very reluctant to recommend making a database accessible from the internet directly (without such an intermediate server)

sweet briar
#

I'm pretty sure all they need is a sandbox database to play around with in their project. Don't really need to worry about where its stored yet

violet fjord
#

I mean, in the context of a simple uni project (all this really is), do you think its necessary to not have it be direct?

compact ingot
#

that depends on the database host

#

if your school allows public connections, then do it

shadow seal
#

I tried to access my own database from uni, boy did they block me

sly grove
# shadow seal I tried to access my own database from uni, boy did they block me

Universities are like weirdly obsessed with traffic monitoring.
One time while working in a research lab I got called into someone's office because apparently my computer was making suspiciously high numbers of DNS calls.

It turned out this was because I liked to keep google news open and refresh it all the time, which made tons of DNS requests for all the various news organizations.

sweet briar
#

I'd just use my phone's hotspot since it's three times faster and not logged half as much. Take that, Uni.

violet fjord
#

Can't even do my database stuff offsite so I have to be on campus whenever I want to test it.

#

Because they won't allow us to connect when off uni wifi

sweet briar
#

What kind/amount of data are you trying to load Hevii?

violet fjord
#

literally just login details for a website/game

#

itd be shared

#

oh and a highscore from the game

#

and hardly any data, we're not gonna have to test loads.

sweet briar
#

So your "Scores.json" and correlating C# class shouldn't be too lengthy or require much 'fancy' json parsing

#

That playlist I shared should have you up and running for your project within the first 3-4 videos. If you still need help feel free to mention me, I'm no expert but I've been toying around with DB handling and loading for a bit and I need a challenge that isn't my own mess for once lol

violet fjord
#

Alright, thanks dude.

#

Think I'm done for tonight though because its been like 6 hours and its just making me depressed now.

sweet briar
#

Take a break and you'll have some new approaches for tomorrow. Cheers!

pulsar isle
#

I want a 3D Model to appear at a certain location using GPS when the user is near. Like I have the location of the user, the location I want the 3D model to be present, the distance between the two(approximately) at every given time and ar foundation. Any guidance on how to achieve this, will be deeply appreciated.

timber flame
small badge
#

Or even (as the UniTask documentation suggests) just async UniTaskVoid Start() { await ...; }.

drifting galleon
#

just do not use unitask

#

it's not true async

small badge
#

In Unity it is exactly as "true async" as System.Threading.Tasks is; they both run all tasks on the main thread unless the task specifically switches context to another thread.

wind vine
#
   private void Start() {
        GameObject PlayerPlane = GameObject.Find("Plane cessna");
        PlayerControllerX playerScript = PlayerPlane.GetComponent<PlayerControllerX>();       
    }  
    private void Update() {
        if(playerScript != null)
        {
            if(playerScript.playerHealth <= 0)
            {
                gameoverUi.SetActive(true); 
            } 
        }

playerScript does not exist in the current context

#

line 7

#

how can i fix it

#

pls

small badge
tight junco
#

Hey all, I'm using a NavMesh right now to do pathing, but I really don't like how all my units have to accelerate/decelerate. How can I make it so that units start/stop moving instantly?

wind vine
tight junco
#

when you type GameObject playerPlane for example, you create a new object that exists only within that scope

#

in this case, only the scope of Start()

wind vine
#

i see interesting

tidal skiff
#

I'm making a music-based game where creatures play a part of a song (so for example a vocal or a piano) and I am looking for a way to make them play at the right time. I have an idea in my head but I don’t know how to write the code for it. An object called "SongManager" would send a signal to the objects and tell them to play a certain animation at a certain time. I am not really capable of writing complex scripts, could anyone help me with this?

fresh salmon
#

You could have a list of timestamps, where each timestamp denotes when an animation will play. The list elements are sorted. And the script will basically check if the current song time is greater or equals to the first timestamp in the list. If it does, play the animation and remove the first element from the list, repeat.

tidal skiff
#

That sounds logical, how would I do that though? I am not really experienced πŸ˜…

fresh salmon
#

Paradoxal isn't it

#

Anyway, learn about lists, how to access elements, remove elements, sort the elements. And a bit of class creation if you want to store more than just a timestamp in a list item

tidal skiff
#

Okay, thanks for the help!! ^^

small badge
#

Surely you would get better answers in a forum or discord that is in some way related to any of those topics, rather than in a discord for an unrelated framework that almost exclusively uses C#?

rocky otter
#

Oh sorry, wrong server

undone coral
empty vortex
#

hey guys, is it possible to access _ScreenSpaceShadowMap in deferred rendering? setting it to a global texture thru a command buffer on a light source works fine for forward rendering but i couldn't get it working or find any resources on doing the same with deferred rendering except recreating shadow mapping manually haha

undone coral
#

are you sure that's what it's called inf rame debugger?

warm spade
#

If I make a game full of easter eggs, is it possible to protect my assets (textures, sound files, models) from getting simply pulled by the players?

sly grove
#

not really

#

Not without dramatically increasing the complexity of your game/code, and even then it's not 100%. You basically can try to obfuscate/obscure it to the best of your ability but it'll never be foolproof

dense aspen
#

@sly grove I've always been curious, could a game be 'streamed' to completely hide its inner workings from the player?

sly grove
#

sure, launch it on Google Stadia only

dense aspen
#

such as with whatever the equivalent of stadia is

#

I thought it's defunct

sly grove
#

there are other services aren't there?

dense aspen
#

I'm waiting for the day one of those big corporations decide to make a proprietary game streaming service that their games will exclusively be played on

sly grove
#

That would be awful IMO

regal lava
#

too much money

dense aspen
#

no kidding

regal lava
#

if google couldnt get it to work it aint happening

dense aspen
#

at least not yet

regal lava
#

there was also something a decade ago that tried a game streaming service and it died just as quickly

dense aspen
#

Then the technology doesn't appear to be capable enough yet

sly grove
#

anyway you can certainly stream parts of your game. by which I mean have your game download assets only as they are needed, e.g. via Addressables or Asset Bundles

dense aspen
#

One of the better benefits of letting players snoop around is that they can mod it

#

I'm going completely off topic

#

I was thinking that there must be a way to put something into your game that is undetectable in the files

sly grove
#

You can obfuscate it

#

break the file into 3 different binary files and then combine them all in your code into a single file for example

#

Or encrypt it and hide the encryption key somewhere else in the code

#

or break the encryption key into multiple pieces and likewise hide them in multiple places

#

Ultimately clever people will solve all of these "puzzles"

dense aspen
#

at that point

#

is your easter egg worth locking up inside fort knox

sly grove
#

up to you

#

prrobably not

warm spade
#

The game is all about easter eggs and secret references to other games and movies, so it's basically the whole point of the game. If people can just pull out a program and extract all the assets, the game is ruined

sly grove
#

If players want to ruin games for themselves they will. If they don't want to, they won't.
For evidence of this: See the entirety of YouTube Lets Play content, the entire existence of GameFAQs/Game Walkthroughs, and the existence of cheat tools.

#

Why would someone "pull out a program" to find/extract assets from your game when they could just watch a YouTube video or read an article detailing the easter eggs?

warm spade
#

The thing is that the youtube videos are created out of players actually playing the games and finding out stuff. To my knowledge, it is extremely easy to pull out assets out of unity games. I want the players to slowly find out stuff about the game, I want it to be that kind of game that even after 10 years players still find out new stuff. What I don't want is someone just pulling everything in the first day of playing and pretty much ruin the 'quest' for everyone

#

The game will actually be a normal, horror survival story game. It's just that I want to make it special by including lots and lots of secrets. That's part of my plan on making the game popular. If people are able to just take everything in one touch, it's not worth the work.

flint sage
#

Pretty sure that progress bar runs on a different thread so it's not blocked

fervent parcel
empty vortex
# undone coral are you sure that's what it's called inf rame debugger?

i mistyped it in the message here LOL but i could get it just fine in forward rendering, but it doesn't seem to work in deferred and according to a forum user the command buffer method only works in forward with no further explanation
https://forum.unity.com/threads/accessing-screenspace-shadowmap.737840/

glacial wedge
#

I want to encapsulate a class to another class to add some info.
but I wont to change the full code.
How to write my new class to give the direct access of it's property old class?

class A{}
class B{public A data; public string info;}
print(b); //gets the A data
print(b.info); // gets the string info
flint sage
#

Inheritance?

glacial wedge
#

without inheritance?

stark sail
#

Anyone here familiar with UniRX ?

flint sage
#

Well print calls tostring on an object, so you can just override tostring and return a tostring from a

fresh salmon
#

So a sort-of wrapper / proxy?
Here's a versatile class you can use with any type

public abstract class Wrapper<T> {
  public T Data { get; }

  public Wrapper(T data) => Data = data;
}

Inherit at will to add your own properties

glacial wedge
fresh salmon
#

You can't

#

C# language limitations

#

You can't do b.Whatever and expect it to implicitly access b.A.Whatever

#

Unless you create the properties yourself of course

#

Which could considerably fill the class with a lot of code

small badge
#

An implicit conversion operator would let you use b in contexts that expect an A, but it's still going to be a B, not an A.

small badge
glacial wedge
#

ok 😦 thanks anyway

stark sail
#

Well, firstly, a question regarding vs. I have installed a nugat package and the warning message doesn't appear in the error list

fresh salmon
#

Because it's an analyzer warning and not a compiler warning. It's internal to VS and doesn't get reported back to Unity

stark sail
#

I am not trying to see it in unity but find the code line that produced it. Based on that I should be able to find it

fresh salmon
#

Double-click the error in the list, or check the other columns, Source File and Line

glacial wedge
#

You should replace the ObservableWWW with UnityWebRequest instead of trying fix a deprecated library

stark sail
#

Despite the fact that the library is obselete

undone coral
undone coral
radiant wave
#

I want to build a statue editor. You can select 3D pieces and attach them to another 3D piece. I'm using a Raycast to check if the player is currently looking at a valid place to position the new object. I can then use the Raycast Hit point as the spawning position for the new element. But this results in the object being halfway inside the other object (since the pivot point is in the objects center), see teh attached image. Since newly placed objects are fully rotate- and scaleable, I can't just move the pivot point. I need to determine the position of the 3D object where it would be just touching the other object. Is there a way for that? Basically "Set this 3D object as close as possible to the point"();

cursive horizon
radiant wave
#

Basically I would use the raycast hit point, then iterate through positions on the axis from there back to the camera and check for those positions whether they overlap or not using ComputePenetration

cursive horizon
radiant wave
#

I was confused by the bool return value. I just saw the out direction, out distance variables!

#

I thought I needed to iterate different positions until it returns false lol.

glacial wedge
#

is public event Action<T> MyEvent; the same of public Action<T> MyEvent;?

#

no it isn't. with event I can't assign another Action<T> to MyEvent

vague granite
#

Anyone with Tnet3 Experience here?

hushed fable
#

@shadow urchin Job posts go on the forum.

fallow lantern
mint sleet
#

Hello

#

Is there any way to swap the AWS SAM Template by Jetbrains Rider's AWS SAM Template

#

they use different cloud formation files: Rider uses 'yaml' and VS uses 'JSON'. and could not get it worked.

#

So, I am going to create the SAM application with VS first, and open that .sln file by Rider and everything will work smoothly?

#

and AWS Toolkit for Rider will be able to work with...

#

Am I asking too much πŸ™‚

drifting galleon
mint sleet
#
  public async Task<Restaurant[]> GetRestaurantsAsync()
        {
            ScanResponse result = await _dynamoDb.ScanAsync(new ScanRequest
            {
                TableName = "Restaurants"
            });

            List<Restaurant> restaurants = new List<Restaurant>();
            
            if (result != null && result.Items != null) {
                foreach (Dictionary<string, AttributeValue> item in result.Items) {
                    item.TryGetValue("Id", out var Id);
                    item.TryGetValue("OrgName", out var OrgName);
                    item.TryGetValue("OwnerId", out var OwnerId);
                    item.TryGetValue("RestaurantName", out var RestaurantName);
                    item.TryGetValue("Phone", out var Phone);
                    item.TryGetValue("Email", out var Email);
                    item.TryGetValue("RestaurantSlogan", out var RestaurantSlogan);
                    item.TryGetValue("Address", out var Address);
                    
                    restaurants.Add(new Restaurant
                    {
                        Id = Id?.S,
                        OrgName = OrgName?.S,
                        OwnerId = OwnerId?.S,
                        RestaurantName = RestaurantName?.S,
                        Phone = Phone?.S,
                        Email = Email?.S,
                        RestaurantSlogan = RestaurantSlogan?.S,
                    });
                }
            }
            return restaurants.ToArray();
        }```
#

Hey people! I want to get the "Address" value from dynamoDB.

#

Address is a "MAP"

#

that is why I can not assign it directly to a UnityObject as I have done to "restaurants" object.
Do you have any suggestion? thank you in advanced.

empty vortex
undone coral
mint sleet
#

I know! But I had to, I think... Because I have some fields that I should not retrieve at all.

undone coral
#

what is a "MAP"

#

i feel like you already know the answer to this

#

you have to copy your blah into your blahblah

#

is this something you plan to distribute in google play / the app store?

mint sleet
#

I have tried but I got {}

#

DDBContext.ScanAsync<Restaurants>(null);

#

is there any way not to retrieve all the fields by using data persistence model in AWS

#
        public string RestaurantSlogan { get; set; }
        public Address Address { get; set; }
        public List<Catalog> RestaurantCatalogs { get; set; }```
undone coral
#

is this something you plan to distribute in google play / the app store?

#

or on steam?

#

or in any way publicly really?

mint sleet
#

for mobile

undone coral
#

so for google play or the apple app store?

mint sleet
#

yep

undone coral
#

you won't be able to access dynamodb this way then

mint sleet
#

I give user policy when they are authenticated

#

so they are good to go.

undone coral
#

are you using an access key or cognito?

mint sleet
#

cognito

#
        public async Task<APIGatewayProxyResponse> GetRestaurantsAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {

            context.Logger.LogLine("Getting restaurants");

            var search = await this.DDBContext.ScanAsync.<Restaurants>();
        
            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = JsonConvert.SerializeObject(search),
                Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
            };

            return response;
        }```
#

this is my api I'm working on it.

#

there is a Restaurant that I will retrieve but not all the fields.

undone coral
#

configure a mapping for the map attribute type

mint sleet
#

@undone coral could you have a look the API above?

#

thΔ±s Δ±s the way that I want to use in fact

undone coral
#

it looks fine to me

mint sleet
#

But I do not want to get the whole fields in a Restaurant object

undone coral
#

item.TryGetValue("Address", out var Address); it looks lie you have to just do this a little smarter. are you sure you should be doing TryGetValue like that?

#

i'm sure it's in there

undone coral
#

if it doesn't try pinging AWS support

mint sleet
#

hmm to make a query, you mean?

undone coral
#

no i'm saying in the returned object

#

isn't that your objective, to get the restaurant? the data is probably there

#

you just have to access it correctly

#

so yes, to make a query

mint sleet
#

restaurant have 10 fields. one of them is a dictionary and have hundrets line. if I retrieve 100 restaurants, it makes thousands of lines of code.

#

that is why I am going to make another API for retrieving them separately.

undone coral
#

dynamodb supports creating a class

#

that will be used for mapping

#

so does JsonFx / newtonsoft JSON

#

i wouldn't overthink this

mint sleet
#

hmm.

#

you mean, I will make this operation in server side and get data directly as json

#

smart

#

Thanks I'll give it a shot

undone coral
#

you can do that too πŸ™‚

uneven ivy
#

How to host server?

wooden cedar
#

using which framework?

wintry turret
#

I am currently working with a compute shader. I am passing back and forth a buffer, buffer = new ComputeBuffer(data.Length, sizeof(float) * 5);. When data.Length <=21503, everything runs as smooth as butter, 200+ fps. As soon as data.Length reaches 21504, the whole thing chugs. Is there an explanation for this? I've determined that the size of each element in data does not matter. I dispatch the shader with computeShader.Dispatch(kernelIndex, data.Length / 1024, 1, 1); I suspect it has to due with the max thread size being 1024. I've noticed that the data in excess of 20480 is not processed.

compact ingot
undone coral
#

you should be able to have larger buffers

wintry turret
#

No, I still don't have a solution yet. I'll try messing around with the buffer size more as I haven't fully explored it.

#

I'll check the DirectX version but I just created a project with the newest LTS build

undone coral
wintry turret
#

When setting computeShader.Dispatch(kernelIndex, x, 1, 1); in the MonoBehavior and [numthreads(y, 1, 1)] in the compute shader, what relationship should x and y have? Or is it guess and check?

#

And a whole lot of

frozen stump
#

Hey! Been having trouble trying to get steamworks to work in my unity project. This is the error code I keep getting and unsure what else to do for it

untold pilot
#

@frozen stump seems like you may have that dll in multiple locations.

uneven ivy
undone coral
#

what are you trying to accelerate with compute shaders?

undone coral
uneven ivy
#

What Is a headless server?

undone coral
undone coral
#

there's also "Playfab unity"

uneven ivy
#

Ok thanks

undone coral
#

which people use for a lot of stuff

wintry turret
undone coral
#

oh yeah

#

compute shaders are so hard to use

wintry turret
#

Directx12 does nothing for me :/

small badge
humble loom
#

oh hey i didn't know there was a code channel

#

can someone help me with an interesting problem., already out the gate unity recorder is out of the question because it doesn't work in builds. but what i need is a system where i can run my simulation manually, and record each simulation tick as its own frame. The idea is i want to do this as fast as possible, record each frame, and then set the frame rate to what it would be if it had played normally

#

if that makes sense

#
public IEnumerator RecordSimulation()
{
  // I need a recorder like this
  SOME_AWESOME_RECORDER recorder = new Recorder();

  for (int i = 0; i < frameCount; i++)
  {
    simulation.Tick = i;  // Updates screen with new sim state
    recorder.CaptureFrame();  // Adds frame to video
    yield return null;
  }

  recorder.SetPlaybackFramefrate(60);
  recorder.SaveFile();
  yield return null;
}
#

this is basically what i would want to do

#

it seems like most plugins are geared towards realtime gameplay recordings though, which doesn't make sense for my application

#

i'm making a debate timer, so i'd want to record the debate in real time, go back and scrub it to make it tidier, and then save off the whole thing as an overlay to video

small badge
#

So, you just have code that produces simulation frames slowly (i.e. less than 60fps), and you want to turn those images into the frames of a video that you play back at 60fps?

humble loom
#

the opposite. i have a simulation that runs at normal speed, but i want to play it back as fast as the processor will allow, and create a video file that plays it back at normal speed

small badge
#

Hm; I'm not sure you'll save much time running the simulation faster than 60fps, since encoding the video will typically be slower than real time?
A straightforward way of recording at runtime is to save out a PNG every frame and encode them into a video with something like FFMPeg.

humble loom
#

so you're saying encoding a 1 hour video will always take at least 1 hour?

small badge
#

Well, obviously it will depend a lot on the video resolution, the compression and the hardware you're using.

humble loom
#

i don't mind necessarily how long the offline encoding takes. that's whatever it's going to be

#

i just want it to generate the image sequence as fast as possible

undone coral
#

It’s just expensive

#

Just use that

humble loom
#

what is it

undone coral
#

It’s called like av recorder pro or something

humble loom
#

avpro capture

#

from what i've seen that doesn't support manual frame capture

undone coral
#

Don’t overthink it

#

Just use the screenshot capture and save to png

humble loom
#

can you even control this from script? the only thing i can see in their documentation is via the GUI

undone coral
#

Yes

#

Search capture screenshot Unity scripting

humble loom
#

oh just the unity method

#

i see

undone coral
#

Yea

small badge
#

I haven't tried the AVPro assets yet, though they do have free trials so they might be worth investigating.

humble loom
#

so would avpro just be used to combine the png's as an image sequence at a target framerate?

#

i don't mind price. if i can get it working with the watermark then i'll buy it, ez

small badge
humble loom
#

does it play nice with the unity runtime?

undone coral
#

if this is only going to run on windows, you can copy and paste ffmpeg into your streaming assets folder, then call it from there

#

you can use it to composite too

humble loom
#

most likely yeah

small badge
humble loom
#

oh ok

#

is there any async callback for the encoding process?

#

the image sequence solution seems even better tbh because i can "record" in a format that doesn't care about audio

#

and i could probably even record them async potentially

#

ehh scratch taht

small badge
#

Ah, there is: Process.WaitForExitAsync.

humble loom
#

yeah just wrap it in a coroutine and trigger an event when it's done. that's fine if i can poll state

#

oh ok

small badge
#

(Though that's for real async, not coroutine async.)

humble loom
#

right

#

could you link the ffmpeg package you use? just so i don't download something silly

#

i really appreciate the help btw ^_^

small badge
#

(In theory I think it should be possible to save out frames a lot more efficiently than the built-in screenshot mechanism can, but it's a complex process; it's easy to waste time stalled waiting for data to copy off the GPU.)

humble loom
#

as long as it's faster than realtime that's all i care about

#

i would still be bound to fixedupdate though wouldn't i?

small badge
#

Hm, I'll see if I can find the source. I think we might be using a version bundled with a different asset (VR Panorama), but it should be identical to the standard versions.

humble loom
#

so i'd have to change the framereate of the application itself to actually see any discernable improvement

small badge
#

Not FixedUpdate, but yes, Update. In theory you can produce images faster than that, but at that point you'd be writing your own renderer which isn't tied to update, which seems like overkill.

humble loom
#

ya

#

well my concern with update is if i update the simulation but the next frame isn't drawn, i'm just taking two screenshots of the initial state

#

right?

#

do you generally download the source and add it to your project or literally just bundle the executable inside your project directory?

small badge
#

We just use the executable. I couldn't tell you which build provider we use, unfortunately, but any of the builds linked from http://www.ffmpeg.org/download.html should be fine.

#

They just include different libraries, I believe. I think everything you'd need for most purposes should be in the essentials?

humble loom
#

okeydokey. seems simple enough. thank god i have git LFS lol

#

oh you know what i can do

#
private IEnumerator Foo()
{
  myProcess.Start();
  yield return myProcess.WaitForExit();
  yield return myProcess.ExitCode;
}
#

would that work? or would the coroutine just hang anyway

small badge
#

That will block the main thread (and thus stall the application) until the process exits.

humble loom
#

yeah i think i should just do something like poll every few seconds

#

OH

#

process does have a callback

#
myProcess.Exited += (sender, e) => {/* do stuff */};
#

that's handy. so i'll just yield break the coroutine once i fire the process and just have some feedback mechanism in the callback

#

so where in the project structure do you usually drop the exe? just at the asset folder or what

#

just in terms of tidyness

small badge
#

If you want to use it in a player build, put it in a StreamingAssets subfolder and it will be copied to the output directory when you build.

humble loom
#

oh gotcha

#

is there a particular path you have to reference an executable from streaming assets? i've never done that

#

just

Process.Start(Application.streamingAssetsPath + "/ffmpeg.exe")
sly grove
#

Application.streamingAssetsPath is the path

humble loom
#

danke

mint sleet
#
JsonSerializer.Serialize(restaurants)
#
    public class Restaurant
    {
       // [DynamoDBHashKey]
        public string Id { get; set; }
        public string OrgName { get; set; }
        public string OwnerId { get; set; }
        public string RestaurantName { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string RestaurantSlogan { get; set; }
        public Address Address { get; set; }
    }```
#

yo!

#

My json returns with the empty value of Address.

#

I do not know why? The other attributes get converted to Json but Address.

#

Do you have any idea?

gentle topaz
#

what's Address?

mint sleet
#
    public class Address
    {
        public string Lon;
        public string Lat;
        public string HumanReadable;
    }```
gentle topaz
#

you have to mark it as serializable

#
[System.Serializable]
public class Address
mint sleet
#

hmm.

#

let me give it a try

#

No it did not work.

gentle topaz
#

you marked Address as serializable? I had accidentally written Restaurant the first time but I corrected it

mint sleet
#

I wrote to them all

#
    [System.Serializable]
    public class Address
    {
        public string Lon;
        public string Lat;
        public string HumanReadable;
    }```
gentle topaz
#

what if you don't make it a property

#

instead just put public Address address;

mint sleet
#

oh my

#

I did not put getter setter

#

maybe that Δ±s why

#

let me try

gentle topaz
#

these seem like pointless properties right now, you aren't actually using the getters or setters for anything special

#

you might as well just make them normal variables

mint sleet
#

what do you mean by normal variables?

#

We got it.

gentle topaz
#

I mean get rid of { get; set; } on all of them

#

you aren't using it for anything

mint sleet
#

but that will be weird but, I put just getter and setter

#

and it worked.

#

is not it strange at all?

gentle topaz
#

it is more strange to have { get; set; } that does nothing

#

this is basically what your code compiles to right now

public string Id
{
  get => _id;
  set => _id = value;
}

private string _id;

for every single property there

#

which is very pointless since you aren't using the getters or setters to add any logic

mint sleet
#

yes you have a point but I'm curious now why it ran

drifting galleon
#

enforces encapsulation.

rugged pollen
#

can anyone point me to any good resources on building a moba-style ability system in Unity? preferably using scriptable objects -- my google fu is only turning up simple examples or very complex ones

gentle topaz
#

but I guess I can't really defend it since I hardly ever use public fields anyway, just don't see the value here

humble loom
#
[JsonProperty] public int Foo {get; set;}
#

that's how you can serialize a property

#

I am also in the category of people that the only public exposure you should have are properties and methods. public fields is just bad practice, even if your properties are simple getters and setters

#

that's also how i like doing public constants fwiw

#
public string FooFolder => Path.Combine(Application.PersistentDataPath, "Foo");
#

a lot of people like doing public readonly strings that are all caps but that just looks gross and feels wrong imo

wispy summit
#

Take this as context.

public virtual IEnumerator InitScene()
{
    yield return FindObjectOfType<SceneController>()?.InitialiseScene();
}

Why does this not show syntax errors?
If ? returns null, then that IEnumerator block won't execute.
Isn't that essentially the same as a blank IEnumerator block? But a blank block shows return type mismatch syntax error.
So why does this block look okay?

compact ingot
wispy summit
drifting galleon
wispy summit
#

I started the code with private SceneController SceneController = null;

drifting galleon
wispy summit
#

the scenecontroller shouldn't be 'destroyed' through the lifetime of the 'this' object here

#

Oh

#

how do you check for Null. Intellisense isn't showing me any references to Null itself

warped grove
#

anyone know best practice for serializing sprites to json.net? right now its a massive block of sprite properties and im trying to imagine how it would be to edit that later

drifting galleon
wispy summit
#

So I kinda went out on a limb and tested the code out on a coalesce anyway

#

deleted the SC object from the scene

#

and started playing the scene

#

there was no NRE

drifting galleon
#

it might still happen. better be aware of it beforehand

wispy summit
#

Normally VS notifies about using null coalesce. But I noticed it hasn't been doing that lately

drifting galleon
#

begone fake null!

#

hopefully unity will fix that at somepoint

wispy summit
drifting galleon
wispy summit
#

yeah

drifting galleon
#

fake null is probably my biggest complaint about unity

wispy summit
#

i've gotta do a '?' search throughout the project later

drifting galleon
wispy summit
#

maybe they fixed it, is why VS isn't notifying anymore

drifting galleon
#

no. fake null is still there

wispy summit
#

i see

drifting galleon
#

and probably will be as long as we don't have a moving GC

wispy summit
#

moving garbage collector? i have to see how that works

marsh veldt
mortal lintel
#

idk if anyone does java but can yall help me?

wispy summit
drifting galleon
mortal lintel
#

ah ok

humble loom
#

hey could someone give me a hand? i'm trying to figure out how this ffmpeg execution is incorrect. running the process via unity

#

oh wow that's illegible

#
PS E:\Users\strop\Documents\GitHub\debate-timer\StropheumDebateTimer\Assets\StreamingAssets> E:/Users/strop/Documents/GitHub/debate-timer/StropheumDebateTimer/Assets/StreamingAssets\ffmpeg.exe -r 60 -i Frame_%05d.png C:/Users/strop/AppData/LocalLow/Stropheum/DebateTimer\Recording\test.mp4```
#

"could find no file with path 'Frame_%05d.png' and index in the range 0-4"

#

but they're certainly there

#

oh doi

small badge
#

It's looking for them in the current working directory, which is the StreamingAssets folder.

humble loom
#

i'm not specifying the absolute path

#

i just needed you to see how much of an idiot i am

#

OKAY so i got this

#

so every yield return null will re-execute on the next frame right? so all i have to do now to improve the record time is to scale UP my timescale/framerate whatever, and reduce the ffmpeg output framerate by the same factor

#

and that should give me the original simulation framerate right?

wispy summit
#

is yield return null; and yield return new WaitForEndOfFrame(); the same thing (in effect)?

undone coral
#

alright dr p's office hours last one before the holidays

undone coral
wispy summit
#

ok let me rephrase myself. How to let a nested coroutine return and let the parent coroutine continue executing before the frame starts being rendered.

#

what's the most useful one in this case i mean

undone coral
#

same thing

undone coral
#

versus

#
IEnumerator ParentCoroutine() {
  Debug.Log("1");
  StartCoroutine(ChildCoroutine());
  Debug.Log("2");
}

IEnumerator ChildCoroutine() {
  yield return new WaitForEndOfFrame();
  Debug.Log("3");
}
#

yield return a coroutine idiosyncratically is also a yield return null

#

if you do not want that behaviour, i.e., if you want to start a ton of coroutines and not automatically wait a frame for each one, you have to do

wispy summit
#

I mean like synchronously nested coroutines

#

yield return ChildCoroutine();

undone coral
#
IEnumerator ParentCoroutine() {
  Debug.Log("1");
  var enumerator = ChildCoroutine();
  while (enumerator.MoveNext()) {
    // do what you need to do
  }
  Debug.Log("3");
}

IEnumerator ChildCoroutine() {
  Debug.Log("2");
}
wispy summit
#

so you're manually handling the movenext. i see

undone coral
#

that's if you don't want to skip the frame

wispy summit
#

yeah

undone coral
wispy summit
#

so when you're 'ending' an IEnumerator block, it automatically yields and the coroutine manager, by design, waits for the next frame before it continues executing anyway?

undone coral
#

yes you can just read that forum thread

#

and yes what i wrote is the workaround

wispy summit
#

yeah, sorry I had to confirm if what i understood was correct or not

undone coral
#

that seems all fine to me

humble loom
#

i think i want to yield return null because i want to record the frame, not the end of the frame

undone coral
humble loom
#

i'm trying to take a screenshot of the frame asap

undone coral
#

okay, but presumably after all the cameras and UI have rendered?

#

and not any later?

humble loom
#

yeeeeeeeeees?

undone coral
#

then you want

while (true) {
 yield new WaitForEndOfFrame();
 take screenshot
}
wispy summit
# undone coral you can yield return `null`

yeah i wanted the parent coroutine to continue executing from that point on without skipping a frame. Anyway, thanks. much appreciated. This clears up a 'lot' of questions for me.

undone coral
#

coooolio

humble loom
#

that's what i got now

undone coral
undone coral
#

what is the issue?

humble loom
#

nothing's the issue, i was just responding to messages that kept coming in lol

#

what i'm trying to do now is just run the video faster, capture frames faster, and then generate a slower video

twilit gulch
#

Can someone help me wrap my mind around quaternion multiplication

I have read a host of StackOverflow answers on this and also the unity doc.
What I understood was that when multiplying quaternions the frame of reference is decided by the quaternion on the left
and then the quaternion on the right adds the extra spin in that frame of reference.

Here's a code sample with comments :https://paste.ofcode.org/DBsMtvuqduFdq8ZFGpMPgQ
I've commented the part which is the problem. If someone can help explain this, it'll clear up some fundamentals. Thanks!

austere jewel
humble loom
#

left is context, right is manipulation

#

you know how with ISROT every matrix transformation is sort of built off of the last one

twilit gulch
#

So when we do
transform.rotation=transform.rotation*Quarantion.euler(0,90,0)

Say at the beginning the orientation i.e transform.rotation is (0,0,40) so then the right hand side will make the orientation change to one which has been rotated from current orientation to one with 90degree spin on y? So basically just rotate the object as it is by 90 degree along global y axis. Right?

If that's true then idk, for some reason instead of that it's doing the 90 along local y axis. Sorry if I misunderstood what you guys were saying.

austere jewel
#
using UnityEngine;

public class Test : MonoBehaviour
{
    [SerializeField, Range(0, 1)]
    private float progress;
    private Quaternion rot;

    void Start() => rot = transform.localRotation;

    void Update() => transform.localRotation = rot * Quaternion.Slerp(Quaternion.identity, Quaternion.Euler(0, 90, 0), progress);
}```
twilit gulch
#

Huh, it's sort of what I did. The only difference is that the object was nested in another object. Would that change anything?

#

Such that the parent object has the 40 degree spin in z but the nested object in question had 0 local rotation.

grave spruce
#

So, i am trying to make my game save the variable called "firstCheckPoint" which is a bool to know if the player marked the first checkpoint (in my game the player can mark the checkpoint whereever they wants) but since the variable changes at the same time that the "SavePlayer()" function is called, it doesn't save, how could i make it save?

        {
            lastCheckPoint = transform.position;
            SavePlayer();
            firstCheckPoint = true;
            if (!GameObject.Find("Bandeira Checkpoint(Clone)"))
            {
                Instantiate(bandeira, lastCheckPoint, Quaternion.Euler(0, 0, 0));
            }
            checkingPointEnded = false;
        }```
humble loom
#

so i'm curious why this is happening. when i was manually iterating through the number of frames in the file and capturing each frame, the video was captured beyond when the video ended (and was faster)
i decided to modify the code to just start capturing frames and stop when the callback for video end is hit and it stops at the right frame it just still plays too fast

gentle topaz
#

shouldn't you be capturing frames at the target framerate instead of whatever framerate you happen to be getting in unity at the moment?

#

just seems a bit weird to have way more frames saved than your target framerate supports, but if the encoder handles that all for you then I suppose it doesn't matter

twilit gulch
#

@austere jewel

humble loom
#

The whole idea of what I'm doing is to generate an hour long video in less than an hour

humble loom
#

so for right now i'm trying to just record the video at normal speed, and output the frames at the same framerate, and then be able to move those values around arbitrarily

#

something i didn't think about is i could just count the number of frames i've encoded, divide that into the length of the video i recorded and that should give me the exact framerate that should match. idk why it wouldn't be 60 tho

wispy summit
#

since you're running a simulation only to record it, I guess it would be optimal to force the game to run at that frame-rate. or a multiple of that frame rate based on the time-scaling

#

unless ofcourse, you could ditch timescaling and vsync altogether and provide a custom time.delta based on the framerate you want and just spontaneously render frames till your video is complete

#

but idk how that'd sync with animator controller though

quaint iris
#

I hope this channel is okay for this question:
I'm trying to upload my project to an empty gh repo but I can't get rid of these git lfs errors... Can I get any help

thin mesa
#

Try to push them with 'git lfs push --all'

quaint iris
#

that... worked?
I swear I tried that command already

#

Maybe it's something that I did previously that allowed git lfs push --all to work

#

I tried some stack overflow answers previously that seemed to do something because the push logs changed

#

Thank you lol

thin mesa
#

lmao i just quoted what was shown in the image

quaint iris
#

I'm impressed that my project is still intact after typing in git commands from stack overflow I only had a vague understanding of

wispy maple
#

When defining and instantiating a list with only one element like this:

List<BossPurpleBugState> bossStatesThatCanRandomAttack = new() { BossPurpleBugState.Moving };

VS does not complain but unity cannot compile due to this error:
Assets\Scripts\Enemies\Bosses\BossPurpleBug.cs(13,70): error CS8124: Tuple must contain at least two elements.

Wth is this crap. I really cannot instantiate a list with just one element and manipulate it later? This strikes me as very weird and i cant find much online its flooded with the same error for other cases

drifting galleon
wispy maple
vernal kiln
#

Hey! I'm trying to figure out whether a certain point on a terrain is a floor or a steep cliff. I have a randomized v3 with X and Z and call terrain.GetSampleHeight to get a Y value on the terrain. Could anyone help point me in the right direction? Do I cast a ray?

regal olive
#

Can someone help me with the new mesh api? The documentation is so sparse it's hard to find anything
So I create a mesh using

            mesh.SetVertexBufferParams(vertices.Length, new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32));
            mesh.SetVertexBufferData(vertices, 0, 0, vertices.Length);
       
            mesh.SetIndexBufferParams(triangles.Length, IndexFormat.UInt32);
            mesh.SetIndexBufferData(triangles, 0, 0, triangles.Length);

            mesh.SetSubMesh(0, new SubMeshDescriptor(0, triangles.Length));

But then I need to modify mesh vertices. Modifying the NativeArray directly does nothing, and calling SetVertexBufferData again results in

#

What's the proper way to modify vertices using the new api?

drifting galleon
regal olive
#

So allocate a new array, then pass it in?

#

Any way to modify it without extra allocations?

drifting galleon
regal olive
#

Is doing what I described above possible at all in Unity?

drifting galleon
#

modifying vertices? the default api should work

regal olive
#

No, I mean modifying vertex buffer without allocating anything new. I pass a NativeArray to a mesh using SetBuffer, but I don't dispose of the array. Since I change the array, but none of the changes are reflected on the mesh, does this mean the mesh just makes an internal copy of array under the hood?

#

I couldn't find a lot of info about it so correct me if I'm wrong

drifting galleon
#

there's not much info about that. but most definitely

regal olive
#

Then there is no reason for it to break when passing the modified array... Experimental features never disappoint lol

drifting galleon
regal olive
#

Apparently, .SetUVs causes it

#

There's probably an advanced alternative I'm supposed to use

#

Oh, yes, it's in the vertex descriptor

#

Well case closed

#

@drifting galleon thanks for guiding me in the right direction

drifting galleon
#

np

mossy vine
#

Does somebody know how I can fix this

    void Crouch()
    {
        previous_y = cc.transform.position.y - cc.height / 2 - cc.skinWidth;
        //previous_y = 0f;
        if (Input.GetKeyDown(KeyCode.C))
        {
            if (isCrouching == false)
            {
                isCrouching = true;
                target_height = 1.2f;
            }
            else
            {
                isCrouching = false;
                target_height = 2f;
            }
        }
        cc.height = Mathf.MoveTowards(cc.height, target_height, 5f * Time.deltaTime);

        head.transform.position = Vector3.MoveTowards(head.transform.position, new Vector3(head.transform.position.x, cc.transform.position.y + target_height / 2 - 0.1f, head.transform.position.z), 5f * Time.deltaTime);

        cc.transform.position = Vector3.MoveTowards(cc.transform.position, new Vector3(cc.transform.position.x, previous_y + target_height / 2 + cc.skinWidth, cc.transform.position.z), 5f * Time.deltaTime);
    }
sly grove
tribal helm
mint sleet
#

Hey people!

#

I got a restaurant class and want to map the 'dynamodb' database accordingly.

#

I am not sure which one should be sort key which one is partition

#
    [DynamoDBTable("Restaurants")]
    public class Restaurants
    {
        [DynamoDBHashKey]
        public string OwnerId { get; set; }
        [DynamoDBRangeKey]
        public string Id { get; set; }
        public string OrgName { get; set; }
        public string RestaurantName { get; set; }
        public DateTime CreatedTimestamp { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string RestaurantSlogan { get; set; }
        public Address Address { get; set; }
       // public List<Catalog> RestaurantCatalogs { get; set; }
    }```
#

My customers should have more than one restaurants.

#

So when I make a query with ownerID, I want to sort all the restaurants belonged to that owner.

sly grove
#

OwnerId -> Id

mint sleet
#

what does it mean?

sly grove
sly grove
mint sleet
#

thanks! I'll have a look now.

sly grove
# mint sleet what does it mean?

By having OwnerId as the "partition key" and Id as the "sort key" this allows you to do things like get a list of all restaraurants for a particular owner

mint sleet
#

oh

#

I understood now.

scarlet copper
#

Hello guys, we use multi-scenes with own physic. We have one scene which contains stuffs like UI. This scene uses default physic settings (so normal). We use there Physics2D.CircleCast to make click and hit on other player. Since we are using multi scene and player is in another scene it is not working anymore. How can I make it possible? To make that possible for all scenes.

scarlet copper
#

Ok Found out scene.GetPhysicsScene2D() has all casts like Physics2D.

#

Works with it

regal olive
#

if you pre-cache something it reserves the right amount of memory to use it at Runtime right?

So if you DONT pre-cache, and just declare everything as it's required, isnt that causing more computation time for your CPU to reserve the memory needed and then apply the result? instead of just applying the result to the pre-cache...

compact ingot
#

thats what unity does when it loads a scene.

regal olive
#

So basically, better to pre-cache

compact ingot
#

i'd say its required

regal olive
#

nice, just wanted to clarify im doing things in the most efficient way, I dont use var or declare floats or anything inside Update() for that reason.

#

everythings pre-cached at global level

compact ingot
#

that may not be all as effective as you may think

#

the key is that you not allocate new things on the heap in update unless you have to

#

but turning all variables into members is not the right way to do it, that might actually be detrimental as it increases the footprint of all objects of the type

regal olive
# compact ingot that may not be all as effective as you may think

Depends on what it is, for things like Positions and Rotations i generally use an IF so the CPU only updates it if it changes from the pre-cached value:

if (transform.position != playerPosition)
{
playerPosition = transform.position;
}

That way it only updates when actually required

compact ingot
regal olive
#

not sure how thats possible, your either setting playerPosition = transform.position or you arent

#

dont see where the check would come into play under-the-hood

compact ingot
#

oh, sorry, i read that the other way round

regal olive
#

oh lol

compact ingot
#

still its not neccessary

#

assignment is the cheapest operation there is

#

an "if" is already 2 instructions

regal olive
#

surely that depends on what your assigning, a simple IF check is 0 or 1, assigning a Vector3 is 3 different operations instead of the IFs 2

compact ingot
#

maybe, it is however moot to debate this without actually measuring the performance of the relevant code

regal olive
#

well im not the greatest at measuring this, hence why I asked here.

compact ingot
#

chances are that something else in your project the actual bottleneck

#

i'd say it is wasted effort

#

if you want to optimize at that level, you have to measure and you have to architect your systems differently to actually benefit from pipeline and cache preloading

#

you should, essentially, do DOTS

regal olive
#

it's not a current issue I have for performance, Im asking the question so I use the most performant method by default, clearly one must be more performant than the other, even if that benefit is so small people consider it "micro-optimization"

#

which I always found hilarious, if you have 2 choices, why you wouldnt choose to do the more performant method by default is a mystery to me, the whole "dont worry about it until it's a problem" mantra doesnt wash with me, thats just asking for problems down the line.

compact ingot
#

the most performant method will be also one that is so much work and hassle that your project will never finish, that is why everyone uses different levels of optimization in their projects... the art is in knowing how much optimization each component benefits from

#

if you are thinking about the right choice of datastructures or not using GetComponent() in Update... those are simple things you can optimize and do right all the time

#

but real performance code is an order of maginitude more work than 'normal code'

#

performance code can also be very hard to understand and change

regal olive
#

If what you said is true, nobody would ever do things like pre-caching WaitForSeconds, despite it taking a grand total of 5 seconds to do. It's just lazyness IMO.

"Do at the right time" is "dont worry about it until it's a problem". Like I said, that doesnt wash with me. IMO you do it properly or be prepared to refactor potentially hundreds of scripts down the line, and thats just stupid.

compact ingot
#

optimization is not "don't do stupid things"

#

and i have never suggested anything of what you implying here

#

you should make sure that you understand the potential benefits of your optimization... checking if a value has changed before assigning it to a variable has practically no benefit when compared to the benefit of caching a WaitForSeconds

#

and caching WaitForSeconds has practically no benefit when used in a async routine that runs once every 2 minutes

regal olive
#

DOTS is a completely different data structure which has nothing to do with my original question.

"real performance code" covers a wide-variety of situations, my question was way more specific.

if we stick to Monobehavior, I have read several articles that say assigning the position and rotation of say, a camera constantly at Runtime is a poor thing to do and you should check if it NEEDS to be changed before doing so.

there are also several articles that say pre-caching WaitForSeconds is way more performant than simply declaring it inside the coroutine.

and it doesnt matter if it runs every 5 hours, pre-caching it costs less than declaring it as-needed, regardless of how often your doing it.

regal olive
#

it is posible to modify any shader to add a slider to increase the amount of specular highlights?

regal olive
#

does it hurt you?

gleaming thistle
regal olive
#

you know there are orcas and penguin diying

gleaming thistle
#

@regal olive there's rules to the server. it's really not that hard.

fresh salmon
#

Ah, a troll

gleaming thistle
#

don't be a troll.

regal olive
#

not a troll

#

im just real

fresh salmon
#

It's been some time

regal olive
#

does it really affect you

gleaming thistle
#

you'll get 0 help acting like this. @regal olive

#

it's the rules of the server. actually read them.

regal olive
#

if i posted in 2 channels?

#

yea but be real

#

it hurt?

gleaming thistle
#

man you're not gonna get any help by being an asshole.

regal olive
#

who is the asshole

#

here

gleaming thistle
#

you.

regal olive
#

?

#

for?

gleaming thistle
#

there is rules to the server.

#

you were informed of them.

#

you responded by being snarky.

regal olive
#

i asked if it hurts

#

if i paste in 2 channels

#

where is the assholness?

fresh salmon
#

It doesn't "hurt", it just shows that you're impatient

gleaming thistle
#

it's because if you get an answer in one then people in the other will still try to respond to you.

#

you derail other people for no reason and waste a bunch of peoples time potentially.

regal olive
#

i can see who is wasting time here

gleaming thistle
#

post in the correct channel for what you need and don't cross post.

regal olive
#

yea trolls

#

go away

gleaming thistle
#

Informing you of the rules is not trolling.

fresh salmon
#

Enough of this

gleaming thistle
#

you're flooding the chat and derailing it off topic. just drop it already. [hellokitty is]

#

I'm gonna go back to my project. gl

fresh salmon
#

<@&502884371011731486> Trolling, "aggressive-ish" answer to "don't cross-post"

austere jewel
#

@regal olive just follow the rules, and don't complain when you're called out for not following them. It's not difficult

regal olive
#

yea vertx i understand you

austere jewel
#

Seeing as you've spammed your question across the server it's extremely obnoxious

regal olive
#

i want to apologies to you vertx

#

woudl you accept my apologies?

#

i'm really sorry

#

i won't happen again

humble loom
#

i have a code design question i'm curious about. to minimize scene dependencies I've been thinking about refactoring the way i structure things. so if i have two monobehaviours that are essentially pretty tightly coupled. one will only ever exist when another does in the scene, what's the best way to handle that? should i just make the dependent script a class that i store as a member of the script and serialize it? or do i just make it so B requires A component and leave it at that? sort of enforce that they can only exist on the same object and not on their own

sly grove
humble loom
#

i figured that'd be the best practice

#

i suppose anything that doesn't require unity lifecycle stuff shouldn't be a monobehaviour though

compact ingot
#

there is no universal best way, just one that works best under the requirements you have.

humble loom
#

so maybe it should just be an internal member

humble loom
#

coroutines don't have to be invoked from monobehaviours though no?

#

oh shoot no they do

compact ingot
#

the coroutine runner i.e. StartCoroutine has to be launched from monobehaviour

#

you can however iterate them manually

sly grove
#

The lifecycle of a coroutine is tied to a MonoBehaviour

#

They can be iterated manually of course, but then you're rewriting the coroutine "engine" yourself basically

compact ingot
#

a coroutine is a C# thing, an automatically advancing coroutine is a Unity thing... those two get easily conflated

humble loom
#

yaya

sly grove
#

Unity exploits iterator methods to create Coroutines.

humble loom
#

i believe unity's coroutine controller is basically just a list of coroutines that get invoked once per update right

sly grove
#

There's a FixedUpdate one, an End Of Frame one

#

maybe a couple more

#

those are places where a coroutine might continue execution from depending on how it was previously yielded.

plush hare
#

does c# have a command that will give me the number of leading zero bits in an integer

empty vortex
sly grove
#

e.g. 15 gives you:
logbase2(15) = 3.9
floor(3.9) = 3
32 - 3 = 29

#

might be off by 1, not sure

#

gotta account for the sign bit too

#

so maybe 31 - 3

#

maybe it's Ceil() not Floor()

plush hare
#

Someone told me every processor has an instruction that does it in one operation

humble loom
#

so here's an interesting thing. for anyone that was familiar with my issue yesterday. i modified the code to basically take one snapshot every coroutine iteration until the video completes, and then when its' done, just take the # of frames / length to get the framerate. it looks like even though my video's framerate is 60, my games framerate is 60, i'm only getting 21.4 screenshots per second somehow

#

this makes me sad. i feel like capture screenshot hangs so if you call it too fast it gets ignored

sly grove
#

.NET's IL language might not have an instruction for it either

compact ingot
#

not available in unity (yet)

sly grove
#

ah nice

compact ingot
#

c# getting really serious with IA level stuff there

sand raven
#

so, i have two sets of code:

                possibleMineLocations.Remove(vect);
                mineLocations.Add(vect);```
and
```vect = possibleMineLocations[UnityEngine.Random.Range(0, possibleMineLocations.Count)];
                possibleMineLocations.Remove(vect);
                mineLocations.Add(vect);```
#

The top block of case uses a hashset for possibleMineLocations, and the bottom set uses a list. After doing some testing, with possibleMineLocations being 250,000 entries long, and iterating the code 45,000 times, the top block of code takes about 40 seconds to finish, while the bottom set takes only 15. My question is why does the hashset block take so much longer? is it the getting the random element of the remove? If its the remove, i dont get why, since list.remove is O(n) and hashsets.remove are O(1)

sly grove
#

In order to do Enumerable.elementAt on a hashset

#

you have to iterate through n elements

#

where n is the number you pass in

#

not only that but the element you get is basically a random one, since again, the enumeration order is not guaranteed as HashSet is not ordered

#

Whereas if you use a list you can get any element in O(1) time

sand raven
#

i see

sly grove
#

not only that but lists are actually ordered, so ytou can guarantee that list[n] is the nth element that was inserted in the list

#

or the element at index n

#

HashSets don't have such a concept

sand raven
#

so then I could get a random element from the hash set without having to enumerate through the entire list, it WOULD be more efficient since hashsets have a faster .remove right?

sly grove
#

well

#

I said "random" but what I really meant was "undefined"

sand raven
#

i mean, does it matter if its undefined since im removing it right afterwords?

sly grove
#

not really, but it's not going to exhibit "randomness" in the way picking a random index would

#

what you'll get is dependend on the implementation of the HashSet

#

It depends what you're trying to do wherther it's acceptable or not

sand raven
#

im making minesweeper, i start with making a square list/hashset of vector2's, which for a 500x500 board takes about .2 seconds. I then iterate through the blocks of code shown above x amount of times (x being how many mines are being added to the board, in the testing i did for the 500x500 board, this number is 45,000)

#
            {
                for (int y = 0; y < height; y++)
                {
                    possibleMineLocations.Add(new Vector2(x, y));
                }
            }```
cursive horizon
sand raven
cursive horizon
sand raven
sly grove
cursive horizon