#archived-code-advanced
1 messages Β· Page 152 of 1
I got it working for characters π
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?
https://docs.unity3d.com/ScriptReference/AI.NavMesh.html if it exists, it'll be in here somewhere
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
mmmm i understand, i'll have to delete the comment because i noticed there's a vfx and particles channel
thanks for the help
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
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.
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.
@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
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.
ohh
so if the origin is further back
then it will still detect the collision
thanks for the advice mate
aye
The three scripts that I employ for this
https://hatebin.com/behfvrrzcq
https://hatebin.com/vthapsltgz
https://hatebin.com/bovfddbsfb
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.
Good idea? bad idea?
bad idea.
Do you mean something like a callback function? I'd say yes, why not
yea a callback function
why is it a bad idea?
anybody knows if Unity supports FastSpan already or not?
sorry for repeating but its so strange for me and dont know if its intended :/
Do not cross-post. This isn't an advanced code question.
is it possible to call Instantiate with an empty GameObject?
if I do Instantiate(new GameObject(), ..) i have it twice :)
You don't need to instantiate, just create the new GameObject.
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
You could have a prefab of an empty GameObject you drag into a field. I wish GameObject.CreatePrimitive supported empties, it doesn't
I think I'll be using a static new GameObject intead
I wish GameObject.Empty was a thing π
or Instantiate without a GameObject
Couldnt you just make a naked gameobject prefab and use that?
I think static is the better approach here since I have one less dependency of my code
can't you just use GameObject constructor?
Probably, no idea
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
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
a powerful website for storing and sharing text and code snippets. completely free and open source.
#archived-networking maybe better for this, and please domnt paste code in raw messages... #854851968446365696
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.
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?
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.
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.
yes, like that
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
I'm sure there are other ways of doing it too π
is that enter key a Button?
Is async void okay for Start() because exceptions will be thrown on the main thread anyways?
no, it's a cube with input text and i take the content of textmeshpro to display it, like all key
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
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
me or gladiator ?
you probably wanted to use Input System and QueueInputEvent
to solve this problem
then your VR keyboard could behave like the native keyboard
no, i think that's too weird
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
what is your objective?
use local space instead of world space for your bezier curve rendering code
yeah but can we declare a storable variable in a playerpref by saying (if Key.text =="Enter") you store the result of the text input to the text meshpro?
this is #archived-code-advanced i'm trying to give you a great answer here
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
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
Unity's talk on async vs coroutines best practices shows examples of using async void Start() to start other async Tasks. Would you not reccomend this?
No, use UniTask
Unityβs people donβt make games, but UniTaskβs authors do
it works better
The Localization package
yeah I've stumbled upon it just now myself π
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?
you can either rotate the object in your compute shader or in the vertex shader
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?
are you supposed to be using data.w everywhere?
what does it do, if not rotate on z axis?
It scales fine, but does not rotate the meshes
multiply it by a rotation matrix
well yeah
I did
that's what unity_WorldToObject = mul(inv(unity_ObjectToWorld), rotateZMatrix); is
does positionBuffer contain rotation information?
yes. positionBuffer is a float4 containing (xPos, yPos, zRot, size)
have you confirmed that setup() is being called
Yes.
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);
That updates the position of each mesh
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
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
The render call looks like this: Graphics.DrawMeshInstancedIndirect(instanceMesh, subMeshIndex, instanceMaterial, new Bounds(Vector3.zero, new Vector3(100.0f, 100.0f, 100.0f)), argsBuffer);
oh its a surface shader
I'm following the example here: https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html
did you change float4(data.xyz, 1); to float4(data.xy, 0, 1); yourself?
yes, as data.z is not the zpos
Rotating around the X gives this:
Around the Z gives this:
These are cube meshes
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
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?
undefined; will vary by platform
yikes
what's your objective? what are you trying to draw?
you should use vfx graph
what is the issue you're trying to work around?
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
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
hmm
it works fine
why aren't you using aron granberg a* then?
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
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
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
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?
yes, it's very little but it's visually displeasing
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*
no, I'm trying to lag behind the completed path a bit, basically.
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
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.
sorry, i'm getting to the core of the issue
in math terms
what you're trying to achieve.
ok, I'll try and be exact
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
you want to smoothly move between points on a grid?
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]
because the grid is around the player. the world is going to be huge
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
it does compute a path to the end point. here lemme grab a short video without any of the trying to smooth stuff
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"
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
hmm
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
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
I'm tempted to believe that.
i'm not sure that aron granberg A* even deals with it correctly
i can check for you
but I also believed that I wouldn't be able to make a pathfinder
so I've been hopeful
lol
yeah it's still a good thing to have done π
this is what I mean, visually.
in case I still wasn't clear enough.
but I think you got the gist already
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
the best performing graph will be navmesh, and then turning the navmesh path into a grid using bresenham's algorithm
this is bresenham's
this turns the floating-point lines from navmesh into grid movement
||just wishing I didn't make a 600 line script for a click to move game for nothing||
is there a way to increase the limit of the StackOverflowException? I know my recursion isnt infinite, its just really big
first answer
read the warning because if you're running into an overflow you need to reconsider what you're doing
Hi, I want to know if there is a way in C# to use GetComponent<T> where T is customizable from inspector
wondering if someone could help me with a custom package workflow question
@brittle pumice Ask away
@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?
or am i way off in the whop whops
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)
ok maybe it was that i committed without ~
hello !
Does somebody know how to get the parameter of a unity event by script ?
Or better this, to give you an example: https://docs.unity3d.com/ScriptReference/Events.UnityEvent_1.html
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
Oh, so you want a generic parameter
i want a generic parameter ?
Don't know what you mean by that :/
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?
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
What does it compare? so you got an array of UnityEvents and you compare it to what object?
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
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
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
What unity version are you on?
2020.3.16
yeah, but here its just the method name
ooooh, i think i'm just stupid ahah
i think i can do something with that, thank yoou very much dude
You are very welcome π
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
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
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.
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"
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.)
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 ?
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.
i've found that, but cant define what is the "method" variable
You cannot do it without introspecting the stack yourself (and this is fragile since many optimizations may mean the stack frame is not what you expect, or even
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
me when the WWW www = new WWW
Nowadays we use UnityWebRequest, it probably tells you WWW is obsolete
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.
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;
}
}
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.
what kind of database is that?
is it your own? do people with your (game)client have to access it eventually?
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
do you want to connect to the database directly (with all the security problems that has)?
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
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)
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
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?
that depends on the database host
if your school allows public connections, then do it
to connect to a database directly from C# its easiest to use Dapper https://github.com/DapperLib/Dapper
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.
I'd just use my phone's hotspot since it's three times faster and not logged half as much. Take that, Uni.
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
What kind/amount of data are you trying to load Hevii?
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.
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
Alright, thanks dude.
Think I'm done for tonight though because its been like 6 hours and its just making me depressed now.
Take a break and you'll have some new approaches for tomorrow. Cheers!
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.
#π€―βaugmented-reality might be the right place to ask
Why not
private void Start(){
Method().Forget(); // or add Exception in Forget param
}
async void Method(){
await ...;
}
async UniTask Method(){
await ...;
}
Or even (as the UniTask documentation suggests) just async UniTaskVoid Start() { await ...; }.
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.
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
You should read up about the concept of variable scopes in C#, e.g. https://www.tutorialsteacher.com/articles/variable-scopes-in-csharp (no idea if this tutorial is any good, it was just the first result from google). If you still have questions about how they work after reading up on them I'm sure #π»βcode-beginner will be able to help you out.
alright will do thanks a lot
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?
so is my code supposed to be in method level scope ?
Declare your variables out of the scope of the functions, and initialize them inside of Start()
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()
i see interesting
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?
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.
That sounds logical, how would I do that though? I am not really experienced π
Paradoxal isn't it
You just posted in #archived-code-advanced
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
Okay, thanks for the help!! ^^
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#?
Oh sorry, wrong server
this is alright, i just like the UniTask.Void because it's the most clear about what's really going on
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
hmm, the whole point of deferred rendering is that you can mess with it no?
are you sure that's what it's called inf rame debugger?
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?
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
@sly grove I've always been curious, could a game be 'streamed' to completely hide its inner workings from the player?
sure, launch it on Google Stadia only
there are other services aren't there?
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
That would be awful IMO
too much money
no kidding
if google couldnt get it to work it aint happening
at least not yet
there was also something a decade ago that tried a game streaming service and it died just as quickly
Then the technology doesn't appear to be capable enough yet
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
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
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"
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
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?
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.
Pretty sure that progress bar runs on a different thread so it's not blocked
nvm solved it, it wasn't processing anything, it was just a huge lag spike from GC
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/
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
Inheritance?
without inheritance?
Anyone here familiar with UniRX ?
Well print calls tostring on an object, so you can just override tostring and return a tostring from a
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
not enought, to access it I have to write .Data. my goal is to get a direct access.... i mean... return the property instead of the class as default
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
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.
If you have a question about something then it's generally best to just start by asking the question itself. If someone knows the answer, they'll answer.
ok π¦ thanks anyway
Well, firstly, a question regarding vs. I have installed a nugat package and the warning message doesn't appear in the error list
Because it's an analyzer warning and not a compiler warning. It's internal to VS and doesn't get reported back to Unity
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
Double-click the error in the list, or check the other columns, Source File and Line
You should replace the ObservableWWW with UnityWebRequest instead of trying fix a deprecated library
I do not think that the problem appears in this function since the message is received normally
Despite the fact that the library is obselete
the source to URP and HDRP are open. you can look how to access the pass that way
i wrote the observable web request that is correct
https://gist.github.com/doctorpangloss/b5677d2b925b5f07a8525760af25d818
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"();
there's https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
but you might be better of manually placing 'snap points' on each of your pieces and having those snap by distance
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
ummm doesn't sound right? iteration positions? I think you just spawn the thing inside of the other thing, then see how far inside it is (with compoute penetration) and push it back out
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.
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
Anyone with Tnet3 Experience here?
@shadow urchin Job posts go on the forum.
you can only do += and -= on fields with the event keyword. Think of it as properties for delegates
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 π
list of methods for your delegates as well
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.
i use SRP for now:/ but yeah a migration to hdrp/urp seems perfectly logical, it would've been nice to support everything tho
you're making stuff really hard for yourself
I know! But I had to, I think... Because I have some fields that I should not retrieve at all.
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?
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; }```
is this something you plan to distribute in google play / the app store?
or on steam?
or in any way publicly really?
for mobile
so for google play or the apple app store?
yep
you won't be able to access dynamodb this way then
are you using an access key or cognito?
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.
Map arbitrary data to the Amazon DynamoDB types using the AWS SDK for .NET object persistence model.
configure a mapping for the map attribute type
@undone coral could you have a look the API above?
thΔ±s Δ±s the way that I want to use in fact
it looks fine to me
But I do not want to get the whole fields in a Restaurant object
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
i think the attribute must have the value as an IDictionary<string, object> accessible somewhere
if it doesn't try pinging AWS support
hmm to make a query, you mean?
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
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.
dynamodb supports creating a class
that will be used for mapping
so does JsonFx / newtonsoft JSON
i wouldn't overthink this
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
you can do that too π
How to host server?
using which framework?
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.
you have to make tests at which group count your shader runs fastest. In most cases the group count should be a constant value and not depend on data-length. if it depends on length as part of a strategy pattern, the actual dependency function is most likely a step function with clearly defined thresholds.
it sounds like you've figured out the problem. is this on windows directx 12?
you should be able to have larger buffers
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
i think what anikki told you is the most accurate
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
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
@frozen stump seems like you may have that dll in multiple locations.
I have little to no knowledge about hosting a server so I gave no idea what you're talking about
what are you trying to do?
what are you trying to accelerate with compute shaders?
for absolute beginners, you will probably want to use firebase. if your goal is to host a unity headless server, don't
What Is a headless server?
also try changing to directx12
i think google "Firebase Unity" and check it out
there's also "Playfab unity"
Ok thanks
which people use for a lot of stuff
Boids
Directx12 does nothing for me :/
As far as I know optimal numbers are GPU-specific. I don't think there are any "invalid" numbers, though, so you shouldn't be getting GPU crashes/timeouts unless you're doing way too much in one call, or you're indexing outside the buffer?
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
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?
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
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.
so you're saying encoding a 1 hour video will always take at least 1 hour?
Well, obviously it will depend a lot on the video resolution, the compression and the hardware you're using.
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
Thereβs an asset you can use
Itβs just expensive
Just use that
what is it
Itβs called like av recorder pro or something
can you even control this from script? the only thing i can see in their documentation is via the GUI
Yea
I haven't tried the AVPro assets yet, though they do have free trials so they might be worth investigating.
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
I'd just use ffmpeg for that part; it's command line, fairly efficient and free.
does it play nice with the unity runtime?
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
most likely yeah
It's just a separate (windows) application, so you run it with Process.Start. We use it for our runtime video production, we've had no problems.
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
You can observe the Process object and see when it exits; I don't know if there's a good async wrapper for that, but you can just poll every frame.
Ah, there is: Process.WaitForExitAsync.
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
(Though that's for real async, not coroutine async.)
right
could you link the ffmpeg package you use? just so i don't download something silly
i really appreciate the help btw ^_^
(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.)
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?
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.
so i'd have to change the framereate of the application itself to actually see any discernable improvement
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.
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?
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?
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
That will block the main thread (and thus stall the application) until the process exits.
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
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.
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")
Application.streamingAssetsPath is the path
danke
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?
what's Address?
public class Address
{
public string Lon;
public string Lat;
public string HumanReadable;
}```
you marked Address as serializable? I had accidentally written Restaurant the first time but I corrected it
I wrote to them all
[System.Serializable]
public class Address
{
public string Lon;
public string Lat;
public string HumanReadable;
}```
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
but that will be weird but, I put just getter and setter
and it worked.
is not it strange at all?
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
yes you have a point but I'm curious now why it ran
incorrect. you should never have public fields. only properties. that is c# standard
enforces encapsulation.
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
I supposed if you are making some public library or something.. I just think it's pointless to have the overhead if you aren't going to use it for anythingβand especially for a class that presumably just stores already validated data for serialization
but I guess I can't really defend it since I hardly ever use public fields anyway, just don't see the value here
[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
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?
it executes either yield return null or yields whatever is returned by InitialiseScene()
thanks. this was really eating away at me
it will never return null btw. it will return Null so ? will not work and it'll still throw NREs
I started the code with private SceneController SceneController = null;
FindObjectOfType will only return Null though. not null
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
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
null is c# built in null. also known as true null. Null is unity's fake null. it get's returned for every object that derives from UnityEngine.Object. that's why you must always check unity objects for null with ==. is, null coalescing, and ? does not work as expected on unity types
Yeah I usually keep that in mind. that unity might not return true null. I guess i just didn't grasp that this was a unity function return.
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
it might still happen. better be aware of it beforehand
Normally VS notifies about using null coalesce. But I noticed it hasn't been doing that lately
fair. I just dislike the fact that i have to declare a new variable to store the return data, so i can process it in the next line again
as long as there is fake null, unfortunately you'll have to
yeah
fake null is probably my biggest complaint about unity
i've gotta do a '?' search throughout the project later
especially now with nullable reference types
maybe they fixed it, is why VS isn't notifying anymore
no. fake null is still there
i see
and probably will be as long as we don't have a moving GC
moving garbage collector? i have to see how that works
I haven't read the whole chat but quick tip, You can return multiple data types like this
(int id, string name) FunctionName() { return (1,"objectName"); }
idk if anyone does java but can yall help me?
dont need to return anything. It's just an IEnumerator block. I just wanted to null coalesce a nested coroutine in a single line...
not a java discord
ah ok
I see now
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
It's looking for them in the current working directory, which is the StreamingAssets folder.
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?
is yield return null; and yield return new WaitForEndOfFrame(); the same thing (in effect)?
alright dr p's office hours last one before the holidays
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
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
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
same thing
IEnumerator ParentCoroutine() {
Debug.Log("1");
yield return StartCoroutine(ChildCoroutine());
Debug.Log("3");
}
IEnumerator ChildCoroutine() {
Debug.Log("2");
}
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
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");
}
so you're manually handling the movenext. i see
that's if you don't want to skip the frame
yeah
are you saying you want a workaround to https://forum.unity.com/threads/yielding-a-nested-ienumerator-waits-a-frame-even-on-break.772352/
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?
yeah, sorry I had to confirm if what i understood was correct or not
you can yield return null
that seems all fine to me
i think i want to yield return null because i want to record the frame, not the end of the frame
are you trying to take a screenshot "at the right time" ?
i'm trying to take a screenshot of the frame asap
okay, but presumably after all the cameras and UI have rendered?
and not any later?
yeeeeeeeeees?
then you want
while (true) {
yield new WaitForEndOfFrame();
take screenshot
}
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.
coooolio
start by studying the moba asset in the asset store. all of them are based on the starcraft II / WC3 scenario stuff. unity also borrows a lot from starcraft II's architecture so
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
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!
Picture the left hand side being an orientation, and the right hand side being a rotation of that orientation in its local space
left is context, right is manipulation
you know how with ISROT every matrix transformation is sort of built off of the last one
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.
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);
}```
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.
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;
}```

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
https://pastebin.com/NmVBDSbu curius what yall wizards think
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
nvm, it works, I was probably messing up something earlier. Thanks a lot!
@austere jewel
If I was just trying to record a video that would be ideal. But I'm trying to produce a 60fps video regardless of the framers I simulate
The whole idea of what I'm doing is to generate an hour long video in less than an hour
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
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
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
Try to push them with 'git lfs push --all'
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
lmao i just quoted what was shown in the image
I'm impressed that my project is still intact after typing in git commands from stack overflow I only had a vague understanding of
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
you're apparently not using the latest unity version. your unity version does not yet support new() you have to write new List()
Crap yeah. using 2020 but VS 2022 and it "corrected" my instantiation and i did not pay attention to that. Thanks man, it was so weird I couldn't believe that i could not instantiate with 1 element π
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?
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?
pass in a new nativearray with the modified vertices
So allocate a new array, then pass it in?
Any way to modify it without extra allocations?
no. that's not what it's for
Is doing what I described above possible at all in Unity?
modifying vertices? the default api should work
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
there's not much info about that. but most definitely
Then there is no reason for it to break when passing the modified array... Experimental features never disappoint lol
you're probably unknowingly changing some other things. e.g. maybe you're not recalculating normals
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
np
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);
}
What's not working about it?
The character Dodges just fine, nothing to fix.
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.
OwnerId -> Id
what does it mean?
It's analagous to the Artist -> Song Title key in the Music example https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.TablesItemsAttributes
Learn about the building blocks of DynamoDB your app will need. You'll discover the basics of tables, items, attributes, and how they work together to make a database for any scale you may need.
Learn about the building blocks of DynamoDB your app will need. You'll discover the basics of tables, items, attributes, and how they work together to make a database for any scale you may need.
thanks! I'll have a look now.
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
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.
Ok Found out scene.GetPhysicsScene2D() has all casts like Physics2D.
Works with it
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...
generally, in games, the idea is to load as much as you can into memory and cleverly replace things you haven't used recently with stuff that is likely to be requested soon.
thats what unity does when it loads a scene.
So basically, better to pre-cache
i'd say its required
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
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
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
unity already does that check internally
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
oh, sorry, i read that the other way round
oh lol
still its not neccessary
assignment is the cheapest operation there is
an "if" is already 2 instructions
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
maybe, it is however moot to debate this without actually measuring the performance of the relevant code
well im not the greatest at measuring this, hence why I asked here.
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
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.
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
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.
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
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.
it is posible to modify any shader to add a slider to increase the amount of specular highlights?
Please don't cross-post.
does it hurt you?
you know there are orcas and penguin diying
@regal olive there's rules to the server. it's really not that hard.
Ah, a troll
don't be a troll.
It's been some time
does it really affect you
you'll get 0 help acting like this. @regal olive
it's the rules of the server. actually read them.
man you're not gonna get any help by being an asshole.
you.
there is rules to the server.
you were informed of them.
you responded by being snarky.
It doesn't "hurt", it just shows that you're impatient
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.
i can see who is wasting time here
post in the correct channel for what you need and don't cross post.
Informing you of the rules is not trolling.
Enough of this
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
<@&502884371011731486> Trolling, "aggressive-ish" answer to "don't cross-post"
Origin <#archived-code-advanced message>
@regal olive just follow the rules, and don't complain when you're called out for not following them. It's not difficult
yea vertx i understand you
Seeing as you've spammed your question across the server it's extremely obnoxious
i want to apologies to you vertx
woudl you accept my apologies?
i'm really sorry
i won't happen again
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
Use the [RequireComponent] attribute, and get the reference with GetComponent in Awake()
i figured that'd be the best practice
i suppose anything that doesn't require unity lifecycle stuff shouldn't be a monobehaviour though
there is no universal best way, just one that works best under the requirements you have.
https://pastebin.com/Ezqj4a7L so like this. the only thing it's really using from unity is the inspector binding
so maybe it should just be an internal member
And coroutines
coroutines don't have to be invoked from monobehaviours though no?
oh shoot no they do
the coroutine runner i.e. StartCoroutine has to be launched from monobehaviour
you can however iterate them manually
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
a coroutine is a C# thing, an automatically advancing coroutine is a Unity thing... those two get easily conflated
yaya
Coroutines are a Unity thing. Iterator methods are a C# thing.
Unity exploits iterator methods to create Coroutines.
i believe unity's coroutine controller is basically just a list of coroutines that get invoked once per update right
there's a few entry points for coroutines in the game loop.
There's a FixedUpdate one, an End Of Frame one
maybe a couple more
You can see all the places where "yield <something>" are mentioned in this diagram: https://docs.unity3d.com/Manual/ExecutionOrder.html
those are places where a coroutine might continue execution from depending on how it was previously yielded.
does c# have a command that will give me the number of leading zero bits in an integer
Is there a way to get the dominant light direction and intensity from a SphericalHarmonicsL2 probe?
I'm using this to get the probe:
https://docs.unity3d.com/ScriptReference/LightProbes.GetInterpolatedProbe.html
but i don't quite understand spherical harmonics yet to translate the answers i found in GLSL to C# (i want to query over just 1 given point)
Do log base 2 of your number, Floor() it, then do sizeof(int) - theResult
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()
Someone told me every processor has an instruction that does it in one operation
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
There is one but I don't know if C# exposes anything that directly uses that instruction
.NET's IL language might not have an instruction for it either
not available in unity (yet)
ah nice
there is even one using intrinsics https://docs.microsoft.com/en-us/dotnet/api/system.runtime.intrinsics.x86.lzcnt
c# getting really serious with IA level stuff there
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)
HashSets are not ordered.
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
i see
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
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?
i mean, does it matter if its undefined since im removing it right afterwords?
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
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));
}
}```
i'm confused as to why you need to iterate at all...can you skip the first step entirely, and then pick some random coordinates to place mines at?
well i dont want two mines to be able to spawn on the same tile
use a hashset and a while loop? π
alternately, there are clever algorithms that solve this
what do you mean hashset and a while loop? and what algorithms?
well this is essentially what enumerable.elementAt does
something like this:
int mineCount = 10;
Vector2Int gridSize = new Vector2int (500, 500);
Hashset<Vector2Int> mineLocations;
while (mineLocations.Count < mineCount) {
mineLocations.Add(new Vector2(Random.Range(1, gridSize.x), Random.Range(1, gridSize.y)));
}