#archived-code-advanced
1 messages · Page 61 of 1
I still disagree with your characterization of random not "fully filling" the area though .
By definition it will give you a uniform distribution
it just won't guarantee no overlaps
yeah
it will do a great job of filling it up
you could place things on a grid and then do a few steps of spring-force relaxation or something
the amount of "filled" just depends on how many items you actually place.
yeah, that's what I look for basically
you'll get that with Random.Range - you just won't get overlap prevention
nah, I need exactly this poisson disk or something similiar
all right, this poisson disk is really cool
also was lucky to find 100 line static script
Question:
For a game with "fishes" that moves using physics (moves the water), what would fit better? Grid-based fluids or Particle-based fluids? Water may also be mixed with other fluids. Or, otherwise how would you calculate the propulsion produced by the movements of the fins (fishes would be procedurally made)?
Seems like overkill and also computationally prohibitive to do actual fluid simulation for that, no? Why not just model the end-result (forces applied to the fish) of the fin movement?
how realistic does this really need to be?
modeling the actual physics of swimming sounds miserable
i'd say the key to stuff like this is figuring out what parts of the simulation are meaningful for gameplay/immersion, use trickery to fake them or simulate coarsely and ditch all the rest
Oh, I see
Actually, it's no game, just a hobby project idea.
I wanted to make small creatures that lives in an aquatic environment and evolve with random mutations.
I thought that having the move with actual physics would be interesting.
I guess I will have to minimize my project idea into something more feasible then.
My main goal is using neural networks for their behaviors 😄, the rest was basically "add-ons" for the core project
To implement undo/redo functionalities in a voxel city building game (editor), do you think it is more suitable to use command pattern or memento?
Because the number of voxels is huge (200,200,200) voxels. Memento keeps the states instead of actions
Whatever results in less memory use is probably better.
so command
Not sure if my opinion matters, but I think Command Pattern fits better for a undo/redo system.
If you only wanted to save one snapshot, then Memento, but that doesn't sounds like your idea.
Can anyone point me towards further reading for how a game like Risk of Rain 2 uses a composite pattern to make roguelike upgrades that stack with eachother?
They seem to do it REALLY well. Everything is so damn well coded
Another example would be the binding of isaac, ROUNDS, etc...
perhaps you could have, for each "property" you want to have, a list of items
and a corresponding method that's called with the current value and that returns the new value
so, each item would register itself with the appropriate properties
so an item that makes you deal double damage would put itself in the "damage modifier" list
and then the game would call everything in that list in sequence to figure out how much damage to do
Just found this game (https://store.steampowered.com/app/1133120/Ecosystem/) which surprisingly is about fishy creatures, real swimming physics, evolution and also use a neural network 😄
Ecosystem isn't just a video game version of the laws of ecology with pre-made fish models. The simulation actually determines the creatures in the game: their bodies, how they swim, and how they think and behave. All the creatures in the trailer evolved on their own in the game; none were hand-edited!Virtual creatures evolve on their own to ada...
$19.99
279
I wonder how they managed that 🤔
Their blog says they have some problems with their creatures because game engines usually ignore conservation of angular momentum... but apart from that they don't seem to explain what they did.
Hey guys, I need some help if you don't mind. I've been stuck on this for a while now.
Given a camera position and angle, how do I calculate the necessary FOV to cover a distance (d) on a plane?
project d into the camera plane with d * sin(a) = d', then atan(d'/cToA)*2 should be your FOV angle
Thanks! But not sure I'm following. Can you tell me what do you mean with "project d into the camera plane"?
you need to apply the projection matrix (part of it) to the line d to find out how wide it is when seen from the camera, i.e. how wide it is when foreshortened in a 2D projection
to do that you just need to multiply it with the sine of the angle (if it is parallel to the camera-forward, it is 0 * d, if it is orthogonal to the camera-forward it is 1 * d)
I tried with this and it's not working as expected. Returns very low numbers for FOV...
var distanceToCenter = PC2DUtils.GetCameraDistanceFromWorldPlane(GameCamera.transform, WorldPlane);
var angle = Mathf.Atan(dProjected / distanceToCenter) * 2f;
GameCamera.fieldOfView = Mathf.Clamp(angle, .1f, 179.9f);```
atan is in radians too
You mean I should do this? Doesn't seem to work either :/
var distanceToCenter = PC2DUtils.GetCameraDistanceFromWorldPlane(GameCamera.transform, WorldPlane);
var angle = Mathf.Atan((dProjected / distanceToCenter) * Mathf.Deg2Rad) * 2f;
GameCamera.fieldOfView = Mathf.Clamp(angle, .1f, 179.9f);
if your fieldOfView is in degrees, multiply angle with Rad2Deg
No, still doesn't work :/
var distanceToCenter = PC2DUtils.GetCameraDistanceFromWorldPlane(GameCamera.transform, WorldPlane);
var angle = Mathf.Atan(dProjected / distanceToCenter) * 2f * Mathf.Rad2Deg;
GameCamera.fieldOfView = Mathf.Clamp(angle, .1f, 179.9f);```
also you need to potentially convert between vertical/horizontal FOV based on your aspect
This is throwing numbers under 0.1 which is not possible to be correct. I must be doing something wrong.
what values do you have for d, eulerAngles.x and distanceToCenter?
d is 5, eulerAngles.x is -60 and distanceToCenter is 10
This is the actual thing in Unity
quick calculation with your values gives me this (y is fov):
and
depending on which way you want the calculation to go
If I input that value (28.07) into the camera FOV I get a resulting "d" of 12.3.
well the center distance isn't actually the right distance
The camera is at (-5, -8.666), so the distance to (0, 0) is 10.
yes, but you need the distance to the projected line, which is somewhat further back
I'm confused sorry. I think I'm not understanding what projected line means. How can I calculate the distance to it then?
i think there is a parameter missing, potentially another tan that scales distance to center based on angle a
You're saying that d projected is that red line? If so, the issue is now knowing how far that line is from the plane
its that red line yes, but not quite that far back
How far would it be then?
would cross d at the midpoint of d
thats not the midpoint of d, thats the center of the view
But I don't know where d actually is... I just know its length. I want to calculate it based on where the camera is...
i'll see if i can think of some other approach, this seems to be too complicated
Yeah, that's the conclusion I came too as well, hence my post here 😄 The premise sounds simple, but it's hard
i bet its very simple if you are well practiced with an inverse projection matrix
I bet so, but I'm not unfortunately 🙂
so, without having the actual math handy, you'd still do essentially the same thing, apply the camera projection matrix to each of the endpoints of d, the distance between those two points is the projected width d' in view coordinates, and from that you calculate the FOV. this way you don't actually need to know the weird center distance to d, instead just use the endpoints
The issue is that I don't know the endpoints of d. Those change depending on the camera angle
how do you know how big d is?
That's my input. I want to know the FOV by passing the d length
That's been my struggle 😄 Looks simple but can't get it right
Anyhow, thanks for all the help, need to catch some zzz's 🙂
hope someone else can figure it out for you!
I'm having a super weird issue.
In my scene, I have a BeatManager script, which listens to multiple BeatCounter scripts. They essentially determine when a beat happens in a song, then pipe that data to the BeatManager. BeatManager then sends out that beat information to any object that subscribes.
When I reload my scene, the BeatCounters stop sending out beat signals.
BeatCounter: https://paste.ofcode.org/39VyytuyRDvz7qKwtFCCzWX
BeatManager: https://paste.ofcode.org/DSJRWQLQpTF8ByUy8VSEJg
Wouldn't reloading the scene completely refresh these objects? They work if I LoadScene without having had the scene loaded prior, so that's what is confusing me.
How to post !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Did you start in the scene or navigated to the scene from the title scene? Usually folks would have stuff in the scene that isn't saved and could not work properly unless starting in the scene.
Otherwise, loading the scene from another and reloading itself should produce the same results.
I can navigate to it from the menu screen and it works fine, using SceneManager.LoadScene("Level")
But if I am in the scene and navigate back to the main menu, then into the scene, or back into the scene (with a restart function that just reloads the scene) in the same instance of the game running, it no longer works.
So visiting the scene at all means it won't work if revisited at all in the same instance of the game running
The only non-destructive object is the game manager, which only stores things like overall volumes and settings
Wait...
What about this Beat Manager?
public class BeatSynchronizer : MonoBehaviour {
public float bpm = 120f; // Tempo in beats per minute of the audio clip.
public float startDelay = 1f; // Number of seconds to delay the start of audio playback.
public delegate void AudioStartAction(double syncTime);
public static event AudioStartAction OnAudioStart;
void Start() {
double initTime = AudioSettings.dspTime;
GetComponent<AudioSource>().PlayScheduled(initTime + startDelay);
if (OnAudioStart != null) {
OnAudioStart(initTime + startDelay);
}
}
}```
This might be throwing it off
That static event
I changed it to a public nonstatic event and made the object a singleton to reference it that way so it would get reloaded on the scene reset, but that didn't seem to fix it
Where do you play the beat?
The BeatCheck coroutine in the BeatCounter script
Place a log and see if it's running after beat no longer works.
Tried, it isn't
Within the coroutine, not the Beat event.
I've done both
If the coroutine loop was false, it'd terminate.
So it's terminated.
The loop failed.
Determine why it was false: while (audioSource.isPlaying)
I think I might be the dumbest person on the planet. I set timescale to 0 on gameover and never set it back after reset or main menu, so that's why it wasn't working.
Literally can't believe I did that.
I think for whatever reason I told myself that reloading the scene also reset timescale, which obviously is not the case lol
I currently have an Editor that uses [InitializeOnLoad] to listen to SceneView.duringSceneGui. However, I only want it to listen when there is a particular component in the scene. I found that FindObjectOfType to see if that component exists works, and I don't think it's that much of a performance hit, but I was wondering if there is a better way to go about this.
I tried hooking the editor up to that component through [CustomEditor(...)], but the thing listens even when the scene does not have that component.
FindObjectOfType is considered very slow (especially in bigger scenes). People often use singleton patterns instead. A static list of instances also does the job - you can add the component to the list in Awake or OnEnable, and remove it in OnDestroy or OnDisable. Accessing such a list then will give the same results as FindObjectsOfType, but with constant speed.
So in the Awake or OnEnable of the component that I want this editor to only work if it exists in the scene, add itself to a static list of instances that a singleton is holding on to. The Editor then asks the singleton if the list of instances contain the component it is interested in?
A static list is needed if you don't use a singleton. If you use a singleton, then you can use a normal list inside that singleton. Also, remember to remove the elements from the list when instances are no longer available.
I see, so the key insight is that the component can add itself to a list somewhere that the editor can also access. Thanks.
Anyone know if its possible to add a reference to a class to a scriptable object? If I want to dynamically add or remove a component, and for the scriptable object to determine that component, is this possible?
could I potentially just use a string with the class's name?
would anyone know how to resolve this problem concerning horizontal layout group and child expansion? https://gamedev.stackexchange.com/questions/205527/unity-how-to-expand-a-child-in-a-horizontal-layout-group-to-the-left
You cannot directly add a reference to a Type. A string can be a valid option. (Not really robust by itself though)
Alternatively, you can use Prefab if it makes sense in your use case.
Can you just not move the whole panel of object by half of the size of the increment ?
hm. come to think about it. that should work. thanks!
thanks a bunch
I have an IEnumerator that sets the position and the rotation of a gameobject with Vector3.SmoothDamp() and Slerp(). But somehow the gameobject stops midway and also the rotation has not finished. I have tried changing the loop to while(true), and it works, but this wouldnt complete the process in the time that is given in movementTime.
Here is my code
```IEnumerator ToPerspective(Vector3 position, Quaternion rotation)
{
float elapsedTime = 0;
camIsMoving = true;
desiredPosition = position;
while (elapsedTime < movementTime)
{
elapsedTime += Time.deltaTime;
transform.SetPositionAndRotation(Vector3.SmoothDamp(transform.position, position, ref currentVelocity, movementTime), Quaternion.Slerp(transform.rotation, rotation, movementTime * Time.deltaTime));
yield return null;
}
}```
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Does anyone know what is wrong, or any better working alternatives?
I will try to help with what you give here.
I don't know much about SmoothDamp, but for Slerp, I got a lot of problems doing movementTime * Time.deltaTime.
Sometimes, I had the object flickering and did not do what we designed it for. I prefer to use a Smoothstep function. If you want to learn more about the subject, I suggest you look here: https://www.youtube.com/watch?v=mr5xkf6zSzk.
I can't help you more than that.
Here is a problem I have:
Does anyone would know if it's actually possible to make an animation work while loading a scene even if the loading of the scene would take longer?
I got something I want to show the player before the game starts, like the first Angry Birds game: https://www.youtube.com/watch?v=aiiQ8btusrs&t=22s
I tried to use LoadSceneAsync(sceneID, LoadSceneMode.Additive), but it almost completely shuts down whatever was happening in the previously loaded scenes.
Here is what I got on the scene management side of things:
private IEnumerator LoadScene(int sceneID)
{
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneID, LoadSceneMode.Additive);
CanSwitchScene = false;
while (!asyncOperation.isDone)
{
//Do something each frame, but almost it's not smooth at all.
yield return null;
}
CanSwitchScene = true;
}
Why would you want an animation while loading, if you want a loading scene animated then youd have to load the loading scene and then animate it while its loading
So, you have to load the loading scene + unload the first scene, then you load the second playable scene?
What I did was that the current scene that had the animation is the menu scene.
It just pauses right after a canvas appears
When the scene I aim to go to is loaded, the animation can occure.
Why does my IJobParallelFor gets paralleled only to 2 threads?
private struct FindNearestFoodJob : IJobParallelFor {
[ReadOnly] private readonly NativeArray<Vector3> _foodPositions;
[ReadOnly] private readonly NativeArray<Vector3> _headPositions;
[NativeDisableParallelForRestriction] private NativeArray<Vector3> _results;
public FindNearestFoodJob(NativeArray<Vector3> foodPositions, NativeArray<Vector3> headPositions, NativeArray<Vector3> results) {
_foodPositions = foodPositions;
_headPositions = headPositions;
_results = results;
}
public void Execute(int index) {
float sqr = float.MaxValue;
foreach (var foodPosition in _foodPositions)
{
float distSqr = (foodPosition - _headPositions[index]).sqrMagnitude;
if (distSqr < sqr)
{
sqr = distSqr;
_results[index] = foodPosition;
}
}
}
}```
Can you show the parameters you used in the Schedule call?
Entire method of setting them up?
Just the Schedule(...) call
_jobHandle = job.Schedule(botsCount, 32);```
And what's the value of botsCount?
40
That explains it. The 32 is the innerloop batch count. It's how many iterations each thread should do. So one thread is doing 32 iterations and the second thread is doing the rest, 8.
You could set it to 1 to map each index to its own thread, but there's an overhead to starting a thread (also most CPUs don't have 40 logical cores, so some threads will have to wait anyway).
You'll need to use some trial and error to find the right balance for your particular case.
Is it fine to not use powers of 2?
As far as I know, yes. You can read the documentation about it here:
https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobParallelFor.html
The relevant section here:
Batch size should generally be chosen depending on the amount of work performed in the job. A simple job, for example adding a couple of Vector3 to each other should probably have a batch size of 32 to 128. However if the work performed is very expensive then it is best to use a small batch size, for expensive work a batch size of 1 is totally fine. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be small but they are not for free.
What animation why do you need can’t you just run it on Awake()
My job is pretty simple but the calculations inside are performed 40000 times...
Do you mean the job is doing a 40K iteration loop for each index?
Can’t be needed
i have a script where a gameobjects moves left, for some reason, in playtime its position only changes between x(482.0) and x(482.1). no other positions, even though im telling the object to move left. Whats causing it to not advance?
What’s the code
rb.velocity = new Vector3(5, 0, 0);
Is that in update
Is there anything else controlling the movement in code
no
What about the editor? Also it’s better to use xF floats for velocity and positions
even if i put gravity scale to 1, it will be stuck in the air and not move
Does it have a rigid body and collider (2d if 2d)
yes
Have you enabled movement constraints in the rb
example of it being stuck
Is the rb the correct rb
yes its correct
Is this in runtime ?
yes
Why are you trying to move it in runtime
because it doesnt move by code either
Doesn’t make sense to me
is this a glitch?
i turned off everything exept the code which only contains "rb.velocity = new Vector3(5, 0, 0);"
Show script
Do you have any collider that could interfere with the movement of your object ?
@heavy rune are you trying to move the object via scene view instead of game view + are you selecting move and not just click
Is this applied to the object
yes
Are there any errors or warnings
no
Make an empty scene with this in it.
It should be working if you haven’t disabled something
rn i realised what was making it stuck - the animator which wasnt even activated
I said the animation may be
this is the animator in my gameobject, whats causing it to not move?
New state 0 could be infinite loop of default position
It needs to have connections between the animations to switch
Or make a thread
What is the most common way to implement and get coastlines in voxel based games? I mean edges of an island
Marching cubes?
two-pass algorithm with perline?
I have 40 worms, each with a head, about 30 body parts and a tail. All these 32 parts have a rigidbody and a collider. 40*32 = 1280 pairs of rigidbodies and colliders and I move and rotate each of them every frame. Performance with this setup is very poor, about 30FPS on a good PC, but the game is supposed to be for Android. The reason for having colliders on each part is to let bots check if there is any worm around with Physics.OverlapSphereNonAlloc and flee if it's the case. The reason for each of them is that it appeared to me like it was way more expensive to move a collider without a Rigidbody than a Rigidbody with a collider. Could you recommend any kind of optimisation to me? I can think of only one, a hellish one, - to store the position of each body part as Vector3 and go over all of them checking for distance without physics. Given that I can parallel it to jobs and use Burst for that sounds like several times more FPS to me.
Why have you added 1280 rigidbodies?
It is written in the same message, isn't it?
remove all the rigidbodies and make the body parts trigger colliders
Lower the physics timestep
you can also uncheck "enable enhanced determinism"
other settings like that can improve performance.
those wont make it run on mobile
How?
How is it fundamentally wrong?
The default timestep at 50hz is too high for shitty mobile devices
30hz and interpolation is completely fine
Anyway I don't see how lowering the timestep improves the situation, it only makes worse, beause the code is performed in FixedUpdate
that doesnt make any sense chief
no shit
you need to find a way to simulate your worms without rigidbodies and collision callbacks
probably a semi-custom simulation and clever overlap checks that dont happen each update
And it's 30FPS now on my PC, which is like several times more performant than any smartphone. Even with what you are proposing their FPS will be way below 10
You need to understand how interpolation works
running your physics simulation at 30hz != running your game's visual render at 30hz
decreasing the physics timestep WILL increase performance
it's a fact.
you don't want to 2x the performance here by tweaking the physics time step, you want to 10x or 100x it by using a fundamentally better architecture
Pretty much every 1/30ms there will be a huge lag. Ultimately 30fps if not worse experience because of constant change in framerate
You understand that cod warzone simulates at 10hz right?
No I don't
No idea about it
I tell you what. If it takes 40-50ms on PC and it is not the limit how much will it be on phone? 150ms? Way more. But let's take 150ms. Even if I run it at 10hz, FPS won't be adequate. Am I not right?
If the physics update is too expensive to run (which in this case it is), then it's not a huge improvement if that update is called less frequently. It just means that instead of every frame taking too long, it's every other frame, or every 3rd frame, etc... From an average FPS stand point, yes it improves, but the minimum FPS will remain unchanged and it will feel stuttery.
optimizing a fundamentally flawed approach is a waste of time
But one thing you can do is move some other computations to just the frames where there isn't a physics update. It's just tricky to balance that so you end up with a smooth FPS.
Sorry, but you're not optimizing Physics.Overlap
I don't know what you all are trying to argue here
we are just frustrated by the discussion that entirely misses the core of the problem
What is the core problem? That physx simulations run like ass on mobile devices?
that you don't even need physics simulation
True
I've done game for the Switch (With snake) and we use 1 rigidbody with multiple collider. Only one collider was actually being use for the collision with the environment and other for collision with the player.
I agree that it's unlikely that you can write a faster Overlap function than PhysX, but PhysX also has to do a lot of other things which a custom collision detection wouldn't have to do.
I think a Bursted Job combined with a good spatial tree can go a long way here.
the performance problem rn isn't even the overlap, its the N:N collisions between 1280 objects
Actually Overlap takes about ten times less time than Physics.UpdateBodies and Physics.Processing combined
just delete the rigidbodies, seriously
And leave the colliders? Than it will perform worse, tested
Moving static colliders has additional cost in PhysX, since it's probably recreating some spatial tree.
Even if we get rid of the rigidbodies, you should still absolutely find a way to separate the simulation logic from the rendering
ensure that you aren't doing your overlap checks in Update()
Your hellish approach can be improved with a spatial tree to reduce the number of comparisons. Here's a Burst compatible octree:
https://github.com/bartofzo/NativeTrees
If you're using sphere colliders for all the parts, then it simplifies the problem to just a bunch of distance checks between points. Putting those into an octree and reading from that doesn't sound wild to me, but maybe someone has a different approach.
Good, not sure about the tree tho, never used anything like that
It talks about some raycasts and AABBs, is it even what I need?
Doing it brute force with 40*32 parts would be 1,638,400 comparisons. Maybe that's low enough to not warrant an octree, but it doesn't scale well.
are your colliders triggers and are they colliding with each other?
i.e. does the physics layer collide with itself?
if you remove the self collision and rigidbodies you can move thousands of triggers each update without issue
and you can still detect them via overlap queries and a layer mask
Actually, only the head checks for collisions
then if you reduce the count of the triggers, mayb only on the head and tail or ever n-th bodypart, you can cut it down further
for proximity checks triggering a flee behaviour its probably sufficient to have 1 or 2 sphere or capsule colliders that approximate the worm shape, since you dont need precise collisions
Then ~50,000 comparisons, not bad (if I'm calculating it correctly).
and once you are down to 40 colliders, you could just ditch all of them and do what stable said and run down a list you calculate each frame
I am not getting what you are saying Anikki
I think you've already decided not to use an octree, but to answer this question, no you wouldn't need those features. You would just need InsertPoint and Range (same as OverlapSphere).
Oh now I get it
Tho this suggestion implies pretty noticeable mismeasurements of shape, so I don't like it
It could be fine for flee behaviour, but I am also supposed to die when I bump into any of them
you could tile your play area into a static grid, sized to approximate the flee distance of the worms, each update have each bodypart figure out which grid cell it is in, if the cell is already occupied by another worm, flee, if not then write its ID into that grid cell. you can improve this with a tree (octree etc.) or you could do the same thing with the triggers from the physics engine which maintains a BVH
Like slither.io?
Exactly
sounds very good
Don't know why I didn't think about it
🙂
This is similar to the octree approach, but uses more memory since you have to allocate for each cell, whether there's a worm there or not.
I don't mind a bit more memory actually
For a large map like in slither.io, it might not go well. Square law and everything
yes, but its conceptually easier to understand as a starting point
also depends on how coarse the grid is
and whether its even a grid or just a hashset
the idea is basically to have static cells of some kind and no movable triggers on your agents, and use a kind of 1-pass bucket sort
Also my map will finally become more scalable
I think there isn't anything else to discuss on this topic, what do you think?
everything was said 😄
</discussion>
Thanks, bye
possible regression: who else found that 2022.2.18 is 10x slower than 2021.lts at asyncgpu readback?
Hello there, I am currently making a 2D experiment, I want to subdivide a polygon collider so a simple sprite (cube sprite) can have more places to deform from, how can I do this? I have a script that lets me deform the terrain using the mouse but it doesnt(subtract the terrain but rather creates collider points on the mouse position
Unity has always been slow. It takes 5-10 seconds every time I save or when I play the game in debug mode
To manipulate a 2D Polygone Collider, use the following API. https://docs.unity3d.com/ScriptReference/PolygonCollider2D.html
To add more points, simply get the current path and subdivide each segment by an amount of points.
The user is not talking about Play Mode, but a specific operation.
If you find the play mode slow to start, you can look into https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html.
It removes step that may not be necessary for your code/project, which can make the play mode almost instantaneously in most case.
Is it possible to self-sign a windows .exe, or do you have to spend money to buy a signing cert from a CA?
It's not just play mode I talked about
Then it means you have issue in your game.
How does saving have anything to do with my game?
Hello. I am not sure if this is the right channel for this question, but I am researching options to do streaming unity to a browser and possibly wearables. I would want to do all the rendering on a server and then have it streamed to a device or browser (edge devices) which may have low gpu/cpu hardware. In my Unity app, I have several models, each in their own scene. I would want a user to be able to go to a URL and load the scene in their browser. I would have simple inputs as well, on the device side, to interact with the unity scene. But, each user who view a particular scene should have their own session(or an option to join a session already in process). From what I was reading, it looks like Azure Remote Modeling is the way to go here? I also did a quick demo using Unity Render Streaming. But, what I noticed is that there seemed to be one session. I.e, I would run Unity on my computer and all browsers that were receiving the broadcast would all see the same thing. for example, if a user in one browser moved their camera, everyone's camera moved.
I have a system where particle systems have "mirrors", basically another instance of the same prefab but with an offset position. Is there a way to "instance" unity's particle systems to automate any changes to all the mirrors (changing particle start color and stopping them). Is there a method that would have any performance benefits over just keeping a list of the mirror objects in csharp and looping over them so all are stopped or change color at the same time?
Not sure I understand. If this only about iterating on a list of ParticleSystem, you should not have a lot of performance issue. Anyway, you should profile before doing anything.
I was thinking that maybe it's a case for "instancing" but just read that this only helps with mesh particles, and if I'm rendering billboards I'm going to render the same amount of them regardless of how they are managed
"instancing" is a batching technique, it does not seem to have anything with what you are trying to achieve. In fact, what you seem to try to do is pretty simple and has no performance implication. At least, not how I understand it.
Whenever I change the starting color of a given ParticleSystem, I want the change to be replicated in every other ParticleSytem.
yeah, I was thinking there's a way to basically say "render this particle system exactly the same, but at a different position"
No, there is no way to directly that. They may be some way of doing so by using a Command buffer, but it might requires to make a Custom Scriptable Pipeline to achieve good results. (https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.DrawRenderer.html, https://docs.unity3d.com/Manual/srp-custom.html)
Anyway, you should not try to do that. Find an alternative and focus on what really matters. The best advice I can give you is: Work with the tool you have, you are doing a video game not an engine.
Do I need a custom plugin to write in the logs of the OS ? I understand Debug.Log. just works when working on debug or connected directly to xCode, but I want to log stuff of my game in the iOS logs so i can retreive them later?
I'm not sure on how logs work with IOS, but with android you actually need to go out of your way to get rid of it.
And, Debug.Log does work in release, it is suppose to fill the Player Logs. You could always make your own custom logger/wrapper around Debug.Log.
theoretically to write the logs in iOS you gotta use NSLog
but thats native i cannot access that without a plugin
didn't find one though
Debug.anything gets culled from the build in a non-development release
Can't you just use the normal File API?
thats what i thought
uhmmmm, i guess i could...
or use any existing C# logging framework?
yeah ill do that
forget it
any recommendable one ?
i used Log4 something in the past
dont remember the name very well
https://github.com/Cysharp/ZLogger might be worth a look
thanks
non-unity specific but with integrations: https://serilog.net/
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I just tested it, and I am fairly sure that the logs are being created in release by default.
Are they? I thought everything was culled. Maybe just Debug.Assert and Debug.Break?
It is not really hard to test it :P. Feel free to conduct your own experiment.
I believe you, not really in a position to test it at the moment
it doesnt look like Azure Remote Rendering can be done in browser (just devices). Anyone work with Unity Render Streaming? https://github.com/Unity-Technologies/UnityRenderStreaming/
in that case i had a stable diffusion console hogging the GPU 😆 after i closed it 2022 is slightly faster at GPU readback
🤔
Hello everyone. I'm trying to make a pathfinding algorithm, but nothing comes to mind at all. Can you tell me in which direction it is worth thinking?
Initial conditions: some adjacent rectangles. There is a start point in the first, and an end point in the last. It is necessary to find the path with the least number of turns through the edges of the intersection of rectangles.
Known :
coordinates of the corners of rectangles
coordinates of the beginning and end of the intersection edges
coordinates of the beginning and end of the path
The approximate result is shown in blue on this illustration
The main point of the question: the part about the least of turns)
is it possible for there to be two paths through the level? and does length matter at all?
Only one way. Even if something like this happens in the end, the order of passing through the edges implies only one specific path.
good to know. especially the ordered edges
my first throught would be to get a range of lines that go from start to the first edge
from there see if there is a line within those parameters that goes through the next edge
continue until no more edges can be passed through using those parameters
I think to simplify for a start, let there always be exactly 3 rectangles here
in a three rectangle example theres either one line through all, or not
so check for that first
one other question, do the walls have size or are they just data
if they have no size then this should be a valid path for example
Do you really want the path with the least amount of turn ? Or the shortest path ?
I think I would start with casting a line from the start to the edges of "doors", then do the same for the end. If some areas overlap, then the solution is simple (any point in the orange area is fine). But it would require some extra steps to calculate.
Also it gets more messy if the walls have width. 🤔
Yes, that's about what I was thinking, but before reducing the number of rectangles, my thoughts run away.
Then I'll try something like this:
line right to the end and check the previous edges. If it didn't work out - line to the next one edge from the end and repeat. Checks 3 times for every edge: the beginning, middle and end of each. If it didn't work out even for 2 in a row, then try to achieve the next rectangle in the centers of the conditional quarters and repeat the procedure from each. Maybe there is some kind of mathematical equation here, how to quickly check it with coordinates alone, but this is definitely not for me.
not doing it with math and equations it will be very difficult to find the lowest number of turns
You could also start with a valid path, and try to reduce the amount of turn.
building of this solution, you could go from start throughout the maze recursively. should scale with large mazes?
get the total area in the next rectangle that a line from start could hit. if that area has another shared edge, then get the area from start to those edges instead.
from that area, get the area it could cast into the next rectangle. if it hits another shared edge, get the area it could cast into that rectangle.
repeat until end is in your area
Just data in fact, but it is better to position their sizes in one conventional unit)
If we start going for door edges recursively, we will end up with some decent solutions, but not every possible solution will be found. In the illustration we can see that starting doing it from the left we will end up 4-line solution (first blue, then red, then we won't reach the blue, so we will need 2 extra lines instead), while starting from the end we will end up with better solution (blue, green and blue again)
And this sounds interesting (I try to read in order, perhaps I have already lagged behind the general idea of the conversation))
if edges dont have thickness you can also cast directly from that bottom left corner
would casts from all 4 corners through both edges of the shared side be optimal?
actually the whole box should be reachable in 1 turn assuming no edge width
The perfect solution has a point anywhere in the yellow area (assuming the walls don't have thickness).
true
im just thinking in bigger examples you would need some kind of way to recursively go on one direction
although all i gave was the area reachable not the optimal solution
I agree there is a need for some recursion. I just wonder if it could be sped up by doing it from both sides.
this would get the number of turns needed but not the route
youre right it probably would improve it
If every ray would result in another 2 rays, then the complexity is 2^n. On the other hand, if we did it from both sides, then there would be a need for search intersections. Multiplying each ray by each ray would return us to the complexity 2^n once again. 🤔
Gonna be honest: I think I would need to spend at least a day thinking about edge cases before finding a good solution. 🤷♂️
2^(n/2) no?
oh wait intersections
nvm
Thank you all very much, you had a very interesting discussion. But since my brain is already melting (It's after midnight here), I'll start with a simplified solution In 3 rectangles.
- First try one straight line start-end,
- If it doesn't work out, then the oncoming caste and the intersection zone
- if there is no intersection, then any point of middle rectangle, the second edge and to the end.
And depending on my free time, I will already expand for a potentially endless maze)
I have a graph structure, where each node is serialized to its own file, and has a list of child IDs and a parent ID.
This only has one issue, since each node is its own file. When working with a VCS, one node file can be pushed, but not the others, which can result in issues.
For example, add a child to a node, but only push the parent node. Now it has a dangling child ID.
My thinking was to instead, only keep a parent ID, and add the children on load. But the issue with that is how to keep them ordered. I could store an int with the nodes index relative to its siblings. But that gets messy if you start to add/move/remove some nodes.
Any ideas, or questions?
I'm creating a loading screen and I want to create a UI menu at runtime that shows metadata for each file. What's the best way to build UI that can accomplish this?
I feel I need to make some sort of UI template and then create a menu procedurally that populates each item from the template and puts them on screen somehow
- this is a code channel
- this is not advanced
- restart the editor
sry i thought i was in general
I have 0 idea of what you are talking about, but usually for circular reference serialization you need to do two pass. Initialize every object, link the object.
I have a class like this. I do two pass when loading the nodes. Once to load them and put them in a Dictionary<Guid, Node>, and a second pass to assign the references to the nodes uses the parent and child ids that are stored.
public class Node
{
internal List<Guid> ChildrenIDs; // Serialized to file.
internal Guid ParentID; // Serialized to file.
public Guid Id; // Serialized to file.
public List<Node> Children; // Not serialized to file
public Node Parent; // Not serialized to file
}
The issue is that if I have NodeA and add a child NodeB to it. But only push NodeA to the VCS, NodeA will have a id in the ChildrenIDs list that goes to no node because NodeB was not pushed.
I'm going to assume you can't change this, but why store each node in its own file instead of serializing the whole graph in one file?
You're always going to have potential issues if it's possible to forget to push individual nodes. Like if Unity saved scenes by storing a file for each GameObject.
A bunch of reasons. Faster saving, and better VCS support are the main two though.
(This is for my asset that lets you create collections of Assets)
So what are you hoping to improve? Obviously, if some node isn't pushed, then it isn't pushed and can't be part of the graph. So are you trying to find the most graceful way to fail?
Well, for example if I only keep the ParentID, then it won't have any issues if a child is not pushed. Each node would be fully self contained so to speak.
If a child node is pushed without the parent, it can fail gracefully by simply adding it to the root node instead
But wouldn't it be better to fail loudly by saying "Hey, this node is missing some children!" rather than fail silently?
Nah, some people are adding nodes only locally, or forget to push the parent or child change. And at that point it is already to late to fix it nicely
The only issue with the ParentID approach is that it doesn't keep the order of the nodes.
In my mind, I'm comparing this to as if I push some change to a scene where I add a prefab, but I forgot to push the prefab with it. When a teammate pulls that scene change, they'll have a red item in the Hierarchy saying "Missing Prefab". They can let me know, and then I push the prefab and problem fixed.
Does that not apply here?
Actually, that might work you're right
I will try that (might be something I am forgetting about), thanks! 😄
If anyones familiar with Facepunch Steamworks:
I setup a lobby on one client, and then when the other tries to join it goes through
SteamFriends.OnGameLobbyJoinRequested += (lobby, id) => { JoinLobby(id); };
but the lobby isnt right? The id doesnt match the one created, and all the data isnt right. Max players is 0, the SetData() I set isnt there, etc.
Is there a way to do procedural cubemaps? Like if I wanted to generate my own in shader graph or code?
Every search comes up empty
@tawdry lintel I have no idea about that api sorry but sounds like the data your getting is the type defaults, are there serialisation settings and hooks you can use to debug?
A fair thought, but I don't think its serialization related, not that there are even any settings like that that i know of. Because I can still query to look for any open lobbies, and I can see the correct lobby I need, in the returned results with all the information I need. I just have no way to know logically its the one I need. Good thought though
does static batching do emissive/specular in a separate pass that doesn't include batching? I'm seeing something kind of weird where certain meshes seem to get drawn twice - once as part of the large static batch and then again individually, and it only seems to kind of "brighten" the object. Is this expected?
pretty sure static batching just welds meshes together
Yes. What I’m seeing is one draw call with stuff welded together, and then N draw calls later where they’re each drawn individually. The later pass is just “brightening the image so I’m wondering if that’s just specular, and whether that behavior is expected
They should not be draw individually. It would make the static batching completely useless... The shader should not even know that there is multiple meshes as it only receives one.
The meshes are combined, but they are still separate draw calls, but even the official documentation contradicts itself in the first paragraph.
Static batching is a draw call batching method that combines meshes that don’t move to reduce draw calls. It transforms the combined meshes into world space and builds one shared vertex and index buffer for them. Then, for visible meshes, Unity performs a series of simple draw calls, with almost no state changes between each one. Static batching doesn’t reduce the number of draw calls, but instead reduces the number of render state changes between them.
again...I'm seeing each object being rendered in two passes. In the first pass the entire batch is rendered as a single mesh and draw call. In the later pass each object is rendered in its own draw call, and the only effect on the framebuffer is to "brighten" it. So I'm wondering if:
A) is this a specular pass?
B) is this expected?
C) is there anything I can/should do about it?
I cannot speak for the Static Batching by default, but I have been working with Mesh.CombineMesh for the past couple of month and I know that it does reduce the number of draw calls. I would expect the same from the Static Batching.
Anyway, you should never see your object being render twice from the FrameDebugger (as you only see the batches) which is what the user seem to experiment.
Without seeing the actual pass, this is hard to say. It might be lighting.
Unfortunately, I have little to no knowledge about the inner working of the lighting system of Unity as we use our own. That being said, we have specific draw call for things like shadow as we "fake" them.
That being said, do you have any issue in term of performance ?
I mean, performance can always be better…works fine enough in simple scenes but heavier stuff gets bad. I’ve already cut off a ms of rendering time with static batching.
I might experiment with manually combining the meshes because then it should be impossible for it to not be drawn in one call…
There is so much things that can be improved.
What is your target platform and what is your number of Draw Calls and Triangles ?
windows
this is actually a pretty simple test case
draw calls was ~7500 before batching (same tris/verts)
I was actually hoping that the batching would improve main thread CPU perf, but it seems like it mainly affected the gpu/render thread
There is something wrong here. 6000 Draw Calls for 1.4M Triangle is not what I would expect
Also, note that 6000 Draw Calls is way higher than what you should aim.
heh. well I'm working on a mod, so I have limited ability to make big changes. And there are a large number of small, simple meshes...which is why I'm trying to use batching
6k draw calls for 1.4M triangles is high?
maybe this is a good palce to ask...this is for a cockpit mod for kerbal space program, so there are a lot of switches, indicator lights, etc that can all move or be colored independently. Currently those are each their own draw call, and I'm trying to batch the static parts of those objects together (things that use the same material and never move). Is there a better way? Skinning maybe?
You number of triangles is pretty low. The issue is the amount of object batched.
If there is a lot of repetition, you should look into Instancing.
Also, you could probably activate Dynamic Batching.
If you are not in HDRP.
Does dynamic batching have a high cpu cost? I’d be surprised if not based on the docs…
It does increase the CPU usage, but in your case you would only gain because you are GPU lock for sure.
I cannot speak for the Static Batching
Hello there, thanks I already solved my problem, in the end I ended up using a third party API
Is there a function from the NetworkManager that checks when a new client has connected, there is a ConnectionApproval but I can't seem to figure out how it works and the documentation for NGO's latest version is not so thorough or explains it well, I am trying to make a lobby that has 4 player cards and when three clients join they are assigned a position as they join, but if a player (host) joins first they get a 4th spot which is reserved, can I use clientId or so to differentiate.
I have this simple player script that gives each player a P1-P3 when spawning but if I wanted to do the same thing on the lobby without spawning players yet and show it on the UI how can I do it, and how can differentiate the clients vs the host (The host will be the special slot)?
public override void OnNetworkSpawn()
{
networkPlrName.Value = "P" + (OwnerClientId + 1);
plrName.text = networkPlrName.Value.ToString();
}
Onclientconnected
Reminder that all the code will be executed on all sides
So same for host and client
If you are using unity's lobby system there will be dedicated methods for listening to new connections
The host always joins first by the way, how else would a lobby be started?
Just using NGO for a localhost only game
IsHost and IsServer then
And OnClientConnected
Be aware that sometimes in awake / start these are always false
OnNetworkSpawn is the safest place to check whether host or client
I do have a script that uses OnNetworkSpawn that changed the player's name and sprite based on this but it does not seem to work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Collections;
using Unity.Netcode;
using TMPro;
public class PlrSettings : NetworkBehaviour
{
[SerializeField] private TextMeshProUGUI plrName;
[SerializeField] private SpriteRenderer plrCurrentSprite;
[SerializeField] private Sprite[] plrSprites;
[SerializeField] private NetworkVariable<FixedString128Bytes> networkPlrName = new NetworkVariable<FixedString128Bytes>("", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
public override void OnNetworkSpawn()
{
if (NetworkManager.Singleton.IsClient)
{
networkPlrName.Value = "P" + (OwnerClientId + 1);
plrName.text = networkPlrName.Value.ToString();
if (OwnerClientId + 1 == 2)
{
plrCurrentSprite.sprite = plrSprites[0];
}
if (OwnerClientId + 1 == 3)
{
plrCurrentSprite.sprite = plrSprites[1];
}
}
if (NetworkManager.Singleton.IsHost)
{
networkPlrName.Value = "DM";
plrName.text = networkPlrName.Value.ToString();
//Change DM sprite
plrCurrentSprite.sprite = plrSprites[2];
}
}
}
Client on left and host on the right
I'm looking to make a game in which players can drag and drop components onto a player-character, essencially a "shipbuilding" style game, but where the ship in question is a swordsman, ect, ect.
Is there a way to create new prefab assets using in-game code rather than the editor, in such a way that I could create a drag and drop system, take all the items in it, and then turn them into a prefab that could later be instantiated?
I've been looking into other ways to handle it, like making a list that tracks every value of every item, and instantiating all of its individual parts as needed, but if there's a way to save and load to prefab assets, it would certainly make things a lot easier.
I've seen that there's a method to save things as prefab assets, but I'm uncertain if it functions in a built game, as it uses UnityEditor.
Essencially, I'm looking into seeing if there are ways to save/load assortments of objects that have complex position, rotation, parentage, and so on, in a clean way.
You cannot create a prefab at runtime.
Darn, so in short, I'll have to set up a system to record parents, locations, rotations, and other variables and a way to instantiate them all as needed.
Yes, you need to create your own Serialization/Deserialization process. I'm sure that you might find plenty of asset that does that tough.
It is usually not really hard to do.
How to test for collision detection in 3d using boxes (not spheres) when the boxes aren't axis aligned? (without using Unity's physics)
you can specifiy an orientation ```cs
var hits = Physics.OverlapBox(center, size, orientation);
WITHOUT using Physics
do something like this for all corners ```cs
bool OverlapBox(Vector3 point, Bounds box, Quaternion orientation)
{
Vector3 max = orientation * box.extents+ box.center;
Vector3 min = orientation * -box.extents + box.center;
Plane left = new Plane(orientation * Vector3.left, min);
Plane right = new Plane(orientation * Vector3.right, max);
Plane up = new Plane(orientation * Vector3.up, max);
Plane down = new Plane(orientation * Vector3.down, min);
Plane forward = new Plane(orientation * Vector3.forward, max);
Plane back = new Plane(orientation * Vector3.back, min);
bool isOutside = left.GetSide(point) || right.GetSide(point) || up.GetSide(point) || down.GetSide(point) || forward.GetSide(point) || back.GetSide(point);
return !isOutside;
}
So you're asking how to write your own physics then
You decompiled it?
But what is a Plane in this context?
the planes defined by the sides of the cube
a box check is made by making 6 plane-side-checks against a point
Could you possibly teach me how you got this code or provide me with a few other things on this topic? I also need to know how to detect collision between a sphere and a box and insides of the Plane
if you want to know it two boxes intersect you can simply check if any corner point is inside the other box
i wrote that code
Oh(
I imagine I could check whether a side of the cube is between the cube's center and the (sphere's center + sphere's radius)
Correct?
yes, just add a range check to the point-check above, this code can probably be optimized significantly
bool OverlapBoxAndSphere(Vector3 sphereCenter, float sphereRadius, Bounds box, Quaternion orientation)
{
Vector3 max = orientation * box.extents + box.center;
Vector3 min = orientation * -box.extents + box.center;
Plane left = new Plane(orientation * Vector3.left, min);
Plane right = new Plane(orientation * Vector3.right, max);
Plane up = new Plane(orientation * Vector3.up, max);
Plane down = new Plane(orientation * Vector3.down, min);
Plane forward = new Plane(orientation * Vector3.forward, max);
Plane back = new Plane(orientation * Vector3.back, min);
bool isOutside = left.GetSide(sphereCenter) && left.GetDistanceToPoint(sphereCenter) > sphereRadius
|| right.GetSide(sphereCenter) && right.GetDistanceToPoint(sphereCenter) > sphereRadius
|| up.GetSide(sphereCenter) && up.GetDistanceToPoint(sphereCenter) > sphereRadius
|| down.GetSide(sphereCenter) && down.GetDistanceToPoint(sphereCenter) > sphereRadius
|| forward.GetSide(sphereCenter) && forward.GetDistanceToPoint(sphereCenter) > sphereRadius
|| back.GetSide(sphereCenter) && back.GetDistanceToPoint(sphereCenter) > sphereRadius ;
return !isOutside;
}
Thank you very much
i think have something like that somewhere
nah its rayOOBintersect
do you really need 6 planes? why not 3?
trying to picture if its possible even
why 3?
to save on computations for each cube face
I mean how
if it would be possible to get side, offset by normal a point..
probably not
but you probably can early exit if you do sqrmag comparison with max length inside box vs total
Wait this method doesn't account for world position does it?
seems to account, sphereCenter and Bounds has center
But Bounds don't account for world position
i think there could be a strategy pattern and some early exit with comparing box size with sphere center distance
the 6 planes are just the first thing that came to mind
yeah i dont see any other way atm
and the || makes it an early exit
public static bool OverlapBoxAndSphere(Vector3 sphereCenter, float sphereRadius, Bounds box, Quaternion orientation)
{
Vector3 boxCenter = box.center;
box.center = Vector3.zero;
return box.SqrDistance(Quaternion.Inverse(orientation) * (sphereCenter - boxCenter)) <= sphereRadius * sphereRadius;
}```
the point of the code was explaining how such a check is implemented, this solution obscures the plane checks.
It removes the plane checks entirely by moving the coordinate system to 0
Why BB when you can AABB is what I always say
Unfortunately, or fortunately, I don't understand how it works
Because I at least do not know what Inverse of a Quaternion is
Instead of rotating one way, it rotates the other
Basically -1?
similar to * -1
the code "moves" the bounding box and sphere to the origin, removing the relative rotation from the sphere position, so you just have a sphere and an axis-aligned box at the origin. Then it's just a distance check, no rotation involved
❤️
(if you want to see how to actually implement the distance to a shape without relying on a built-in function you can use Inigo Quilez's SDF resource https://iquilezles.org/articles/distfunctions/)
The entire concept of moving points so they're relative to an unrotated shape at the origin is required to use any SDF functions, so it's pretty common logic to do
thanks
(just to illustrate the transform I perform which makes the logic much more simple. Instead of the complex case of a randomly aligned and positioned box and position, we just move it to 0 and remove the rotation)
https://youtu.be/MRw_ixL2Nyo
have been working on this and wanted similar gun pointing/movement mechanics to that unrecord game in UE5, but the way theyve made it move around is so realistic. Atm mine just simple which moves and rotates based on how far the mouse moves. Any tips on how I can make it more realistic in that sort of style?
Quick test on the new pistol, updated vfx, a little bit of the lighting, the map and a few extras for the feel of the game like the physically based weapon pointing to help simulate more of a helmet cam/body cam style.
OnNetworkSpawn is ran on both client and host
So when a new player connects, both the host and the new client run that event
So on the client you then try to change the networkvariable (which can only be written to by the server, so that's never going to work) and at the same time, but from the host perspective you overwrite it to DM
The code that you have should only be run on the Host, as the host is the only one who is allowed to change the playerName network variable
Ahhh I see, one thing that I do not like of the NGO documentation is things like this are omitted
You then try to figure out whether or not the host connected, or if it is another client that connected, I'll have to jump in unity but I think there's a IsLocalPlayer that would work
It's all in there
Use IsLocalPlayer, which would only be true on the player object of the host
So you can filter out if it's the host or a new player
What really helped me was realising that every piece of code is ran on every machine by default
Every game is essentially a copy from eachother
You are welcome
making text display when you click on an object
how does this handle the case that the sphere-center is not aligned with a box-face center?
I don't understand, what case, what could not be handled?
I don't get it
so if you use a distance check, and the sphere is not aligned, the distance at which it still collides is different when it is not aligned with a face center (green vs blue)
and how is that different from a plane side check?
it seems to me your solution is essentially doing the same thing with different methods from the API, the comparisons and local space transforms still have to happen the same way
Because apart from the small amount of maths to get the point relative to the origin, it's just:
float sdBox( vec3 p, vec3 b )
{
vec3 q = abs(p) - b;
return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0);
}```
(though length squared)
In comparison to constructing the 6 positions, 6 rotations, then performing 18 dot products and 6 normalisations
Im having a very weird issue of a class that is marked as [Serializable] and it contains list of objects that are also [Serializable]. I have a logic that relies on elements of this list being null. So sometimes you would have list<A> LIST = new list<A> followed by LIST.Add(null).
What Im observing is that if this list is null at seemingly random times it gets populated with an instance of the object A, as if Unity refreshed the list in the background because it is serializable. When I remove the Serializable mark, I no longer get this issue and I was also able to detect that the constructor of A is being called with no history in the stack trace. And if I dont have the Serializable mark then I can not serialize it with JSON serializer as is simply ignores it during the serialization. Can someone confirm this? And maybe explaing why is this the case? Thank you!
Unity does not serialize reference by default ([SerializeField]) so it cannot serialize null. See [SerializeReference] to use reference instead.
Wow thank you so much. I wasted like four hours on this x_x
I'm doing some CPU profiling because I was only reaching 40fps, and I found out it was lagging heavily waiting for the GPU to finish. When profiling the GPU I get this:
Mainthread is the entire problem
And I'm not entirely sure why it is
considering that all the calls it is making have significantly less than that, even cumulatively
so where has all the time gone?
this is all CPU side stuff - presumably the time is spent rendering the scene.
You can use the frame debugger and/or an external tool like RenderDoc to analyze the rendering itself.
Great, thanks, I'll use that
Does anyone have an idea on how to seam together 2 navmeshsurfaces (that are on chunks) so my agents can pathfind from one to another if/when needed? For example in the video attached, the agent can't pathfind to the other chunk/navmeshsurface. I have tried both navmeshlinks and offmeshlinks, but there's like no docs on that stuff so I dunno how to use them in my situation (that is, if they would even make sense to use here).
Or would I just be better off generating and re-generating a single huge navmesh each time a chunk is loaded
Are you profiling in a build or in the editor ?
I am fairly sure this is GPU timing. I guess it might happens if you have other things that run on the GPU such as ComputeShader.
But again, using RenderDocs might give more information.
If you're generating this navmesh at runtime, you could possibly try and parent the navmesh surfaces and then generate the navmesh, im not quite sure if this will fix your issue but it's worth a shot eh lmao
Yeah that's one solution which would fix all the problems with the chunk-based system, but I believe it would cause lag spikes every time the navmesh needs to be updated. So I guess my best bet is to just make the entities only move in their occupied chunks and not anywhere else
Since one chunk is like 512x512 so I don't think the player will notice
you could parent the chunks under 1 gameobject
and on the parent (the gameobject) you could make a really big navmesh surface
never tried it before
but it may work
But you would still have to update the parent's navmesh every chunk update I believe
Idk haven't looked into it too much myself too
what do you mean chunk update? like a new object placed?
Like when a chunk gets disabled/a new one loaded when the player moves around
Because if it doesn't get updated then eventually with many chunks the navmesh's size gets huge -> leads to even more lag
i cant remember but do navmeshes have a resolution feature like terrain?
Yeah they do, I have it on like the lowest setting because it has to be generated at runtime
I wish unity had just made it so agents can just jump between navsurfaces
But the package is experimental anyways soo what can you do
Never heard of that but I'll try looking into it l8r, thanks
im trying to install this logger:
https://github.com/Cysharp/ZLogger
But im getting this exception when trying to build for iOS
```ArgumentException: The Assembly System.Diagnostics.DiagnosticSource is referenced by Microsoft.Extensions.Logging ('Assets/Plugins/Microsoft.Extensions.Logging.dll'). But the dll is not allowed to be included or could not be found.````
I tried installing the last version of the System.Diagnostics.Diagnostic source from Rider:
but the build keeps failing 😦
I believe you cannot directly install a library from any library distributor from Rider or Visual Studio.
ouch
did you look in the releases for that repo? there's literally a unity package that includes almost all of what you need for it
yeah, you need also Zstring
and installed it, ran in editor all fine
damn im so frustrated
gonna try again
Is it possible that the package is not supported for IOS ?
it says supports I2LCPP builds
If you build a PC build. Does it have the same issue ?
i didnt try to be honest, im gonna do a last attempt and try that tomorrow
I have a script for my WebSocketClient, I'd like the instance of that client to be accessed across my unity project. Is the best way to enable that via a static singleton that each class can access?
Have you really maxed out the performance of your single threaded capabilities to the point where you actually need multithreading?
Because no, you cannot drive an animator from unity's non main thread.
Multithreading isn't some magic solution for running 1 million game objects
You first need to solve the spacial locality issue so you're taking full advantage of the CPU cache
which you won't be doing in standard unity
parallelizing code starts in SIMD
that doesn't matter
If you're not maxing out a single core's SIMD capability, then there's really no reason to spin up more threads
you'll need to move to DOTS if you want this many gameobjects at once.
you'll really need to go for pure ECS/DOTS if you want to do this right
the only thing it really lacks, as far as I know, is native animation support
Basically in OOP, the objects are spread out all over memory. You can't change this because of how C# works.
When your CPU wants to grab something from ram, it's also going to grab a bunch of stuff around it
hence spacial locality
in order to maximize SIMD throughput, you need to have good optimized memory transit to the CPU
when you're reading stuff linearly in an array, the CPU can pretty efficiently prefetch it
that's why DOTS is so much faster than standard unity.
as far as I know, C# internally is always moving managed objects around in memory due to garbage collection.
like I said, it has no animation support for right now.
that's probably going to be your only bottleneck
I think you can instance animations
probably wont help at this scale
Like I always recommend as well, you can turn down the simulation rate pretty low
like 5-10hz
and just interpolate in between
do you absolutely need a skinned mesh renderer or could you live without one, i.e. not animate the vertices in a mesh?
The second game abuses the hell out of the GPU over the first game abusing the CPU
Add to your wishlist now! https://store.steampowered.com/app/1468720/Ultimate_Epic_Battle_Simulator_2/
All the music in this video, is part of the official soundtrack from UEBS2 by our amazing composer Eric Disero. Note, the GTX 1060 we used in the one benchmark clip at 1:17 was only the 3 gig version. Performance should be better with the 6 ...
making of video from the devs
I wasn't aware that you were using a third party solution
you should probably ignore what I said about the multithreading part then
unity still does have a bunch of limitations on multithreading though.
interesting stuff 👍
this is not a code issue
they just have different use cases in gamedev and the frameworks built around them for games are therefore structured differently
thats something that trips up a lot of people who come from different programming fields and bring their mental models with them into gamedev... stuff just seems weird here since we care way more about performance when the rest of the world cares mostly about loads of data. i think you need to see a couple of fundamentally different approaches to and use-cases for software development before you truly stop running into that.
oh, whats your take?
interesting, ive never used that stuff, definitely can understand the excitement
would just limit your multi threading to things that are not touching not thread safe unity apis
Did you read the first reply in the thread?
The fact that you "can" do it, doesn't mean that you should. You could make an infinite loop(there's no error to prevent you from that), but should you?🤔
It's not about production or not. You'll run into race conditions and there's nothing to point them out.
I mean, if you're going that far, why not just use DOTS?
It would be more performant.
if you just throw locks everywhere you are no longer truely multi threaded
now its just code on multiple threads running no cocurrently so reason is becuase concurrency is still a hard problem
and locks based multithreading isn't really great for performance, its more about coordinating sync points than making stuff faster with parallelization
why it scales best to cases where its i need a bunch of individual jobs done that have no communication with eachother, let me know wehn its all done
O(1) can be a long 1
you are really over simplify it, and not understanding what synchronization is
there is no magic bullet to hey now any workload can run in parallel
sure, using SIMD. Not just shoving everything on a different core
and i am not saying dont do that
i am saying pick and choose where you get most bang for buck with it
if used for everything it adds a large complexity burden
also parallelization in DBMS has very different properties from parallelization for compute workloads
I don't see the issue
There's nothing wrong with more cores, it's just a massive waste if you aren't already taking full advantage of the first one
DOTS/ECS is pretty much designed for this
ECS components are homogenous data sets with the same sizes
how do you find all references to enable of only one script type?
somewhere in my code I'm setting this to false :/
is that vs? the find references panel should have type column you can sort
If your script throws an exception it can also be disabled
Also enabled = true; inside Awake will never do anything
Wow thanks. i can't think of how this is not a bug. I logged it as such.
It's intended behavior
Can someone help with implementing VR rig with oculus quest 2 and steam vr tracker 3.0 in unity !!?
https://forum.unity.com/threads/unity-crashes-badly-during-run-time.1434310/
heya...so i have this issue which is mentioned clearly on the forum, but here's the briefing.
during run time, at a certain time (mentioned on the post), my unity engine stops responding...and ive to force quit it in task manager. i tried to export the game in hope that it was just an engine fault...but it still happenes... i think it is due to the code sucks... can anyone pls help me out? this was for a game jam... thx.
also, u an ping me. 👍
Connect the debugger and break when the game freezes. You'll likely find an infinite loop.
This is not really an advanced topic.
I think I've spotted the cause, but I'll leave it to you to find, since you've posted in the advanced channel.😛
i didnt knew, i thought of doing general...then for some reason my brain was like: "this is very complicated...."
pls, tell me.
No. Use the debugger and you'll figure it out in a minute.
ok
i cant...it crashed so bad, taking this screenshots looked like taking screenshots on a life support potato pc... everyhting looked normal during the crshing though
wait a min~ i forgot one ss
can u tell me now? atleast on which script?
pls
Did you do what I suggested?
yes, debugged it
Take a screenshot of where you're breaking with the debugger
k, n sec
What is that?
Is the game frozen?
I didn't mean that you need to place a breakpoint, but to break execution.
If I'd meant a breakpoint, I'd say "place a breakpoint"
Maybe show us the console tab.
am I the only one that noticed this channel has dropped 50% activity since the coming of chatGPT ?
If only it was the case for #💻┃code-beginner.
To be honest, I do not think there is any correlation between those event. In fact, I would not even know if it was more active before. Also, ChatGPT is kinda dumb, it does not help much with real world issue. It is really good at being believable though.
AND, this is support channel, not a off-topic. So let's keep it that way.
do you know if the events
void OnPreCull()
void OnPreRender()
void OnPostRender()
are called one after another and syncronoyusly?
when the camera renders?
because i took for granted they did and nothing can happen in between
(maybe im begginer, though 😅 )
i mention this because i just had to ask chatGPT and gave me a detailed answer of how they are not and how stuff could happen in between that could mess the logic i had in my code
just a silly example
What do you count as something happening? OnPre/Post pair certainly implies that something has happened 😄
I would not blindly trust what an language model AI would say.
I have an inventory system but i would like to add a part where you put the weapons and you can equip them, if someone can help me 10minutes with that ??
i would go a step further and not try to use an LLM to understand the internals of a game engine
it will confidently lie to you
an LLM does not generate truth; it generates plausible text
Just make a function on your object that is called: Equip.
I have two BoxCollider components on my GameObject. I want one to act as a "PreCollision" so I can make things happen before the actual expected collision (via the second BoxCollider) happens. However I haven't figured out a way how I can differ between those two BoxColliders yet. For now I would create a custom component that extends BoxCollider and call it ProxyCollider. However I wonder if there's a more elegant way.
EDIT: just realised I can't extend BoxCollider 😄
I want to implement cutscene editor system using Scriptable Objects. Cutscene stores a list of actions represented by other SOs. For example I have SO class WaitAction that has float Duration field, but I don't want to create many SO instances for different Duration values, what can I do?
Create 1 SO for the whole cutscene.
Cutscene SO contains a list of actions that are also SOs
If you do not want to create multiple SO for multiple Action, you need to store the information somewhere. The only available place (that make sense), is the cutscene itself.
[System.Serializable]
public abstract class Action {
public abstract void Execute();
}
public class ActionA : Action {
[SerializeField]
private float duration;
public override void Execute() {}
}
public class Cutscene : ScriptableObject {
[SerializeReference]
private List<Action> actions = new List<Action>();
}
but how would the main function work? i have working inventory where you can drag items and everything but want to make it so when you click 1/2/3 the items from ur hotbar automatically equip
Can you equip an item without the inventory system ?
i have a different script that i was trying that has like primary-secondary-melee types of weapon
If you do, it is as simple as calling the function that does the equip.
k ty ill try some stuff
Actions are SOs as well, I mean if I want to have the same action with different durations I need to create multiple instances of that SO
But I don't want to do it
does anyone know anything about Photon Pun ?
What is the most common way to simulate water and fluid simulation in voxel based games?
Cellular automata?
PSA?
CA are very common
Is there an easy way to configure a modular pipe system for placing different pipe components such as corners and splitters in a grid?
This is why you need to not do SOs for your action... At least, not for the data. The data should be contained inside a global asset, which is the Cutscene.
You might want to look into https://learn.unity.com/tutorial/using-rule-tiles#
Thanks!
On your main gameobject, add two empty child gameobjects and add the box colliders to those. That's how I do it.
Hey, can someone please help me with dll in Unity. I have a normal cpp and header file that just adds 2 numbers and returns the result, I have created a .so file to implement in Unity. But when I run it in unity I get an error. The error is attached below in the screenshot.
I would be really happy to get some help. Have been working on this error since 5 days now.
And I check the name of the collider's gameobject's name then I guess?
Hoping someone has some debugging techniques I don't know of.
I am currently on contract building a singleplayer game to multiplayer, and it is clear the game wasn't built for networking in mind.
Here is my issue. I am spawning the vehicles correctly, and they are active in the scene. But something is tampering with the nested rig, which holds the skinned mesh renderer. The skinned mesh renderer is for some damn reason disabled, until the initialization function is run on that vehicle (when I switch to it).
I can't for the life of me figure out what is disabling this component... I am hoping some debugging I don't know of, can tell me when and what is disabling the mesh renderer in question?
Some kind of callback maybe, that return what has changed it?
I tried searching through my entire project for .enabled, but haven't seemingly found anything relevant 🤔
make sure the .dll asset is enabled for the platforms you're targeting - for the editor I think the default is off
I have already enabled it for android
Strangely, debugging is not a topic where you can find a lot of useful information/reference. There is different way to approach your current issue:
- You could start from a working point and try to get to your current point.
- You could remove things till you do not have the issue.
- You could try to find the "commit" that caused the issue by binary test a range of commit.
- You could search every possible known cause. (Like you did with searching .enabled)
- You could use the Scientific Method. (Renderer is inactive -> (Knowledge on the topic) -> Maybe it is being deactivate by the Network Solution ? -> Disable Network Solution -> Is my renderer still disabled ?, Renderer is inactive -> (Knowledge on the topic) -> Maybe a component on the GameObject deactivated it ? -> Remove all component of the GameObject -> Is my renderer still disabled ?, Renderer is inactive -> (Knowledge on the topic) -> Maybe it was disabled in the prefab ? -> Look into the prefab -> Was my renderer disabled ?)
- You could try to intercept the call. This is can be done by wrapping the code that is supposed to do the action. (.enabled might not be possible to do). You could try to inherit from SkinnedMeshRenderer and add a OnEnable callback as an alternative.
- You could try to find the moment where the issue happens by looking at every piece of code that has been executed between the point where it works and where it does not anymore. It can be hard to be done, especially with 3rd party library. Maybe this could help: https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html
Yeah, so as you also mention here. The networking solution turned out to be the cause, since they have some default parameters that triggered since the scene wasn't loaded correctly. I went looking through a bunch of code with searching "r.enabled =" and finally found one pointing to the networking solution.
no matter, some great feedback given here! I'll keep these steps in mind for a future case.
Thank you my guy!
If you add a script to each of the empty gameobjects, you can just check for the collision there. There shouldn't be a need to a do a name check (I think).
You could also add a single collision checking script to the parent gameobect and that would receive collision calls from the two child objects because collisions bubble up the hierarchy. In that script you would then need to check the name of the gameobject that had the collision.
As I far as I know, you cannot know the source collider of a collision in a composite collider (2 Collider+).
What does this mean?
The project I'm working on throws an OutOfMemory error after playing it for a while. The log file for the development build shows this.
While profiling, the memory usage does not increase steadily but spikes up in an instant.
I would be playing and memory would be stable at 0.5 GB,
It throws OutOfMemory error, the game freezes,
Resumes after a while,
and the memory has spiked up to 4.5 GBs.
What might be the cause of this? Is it related to the code I've written or is it profiler related as the log says?
does the game misbehave at all when you aren't profiling it?
Typically being out of memory stems from a memory leak in your code, or possibly a memory leak in unity itself.
Use the memory profiler to try to diagnose the issue
Yes, it throws the same error. Although it did take a significantly longer playtime for it to occur
I do think it's related to my code, since I played the game without profiling and the error still occurs.
Unfortunately, the memory profiler does not seem to work after the spike has occured.
I can take a snapshot but that snapshot just won't open.
So I cannot figure out what has happened after the spike
The profiler might add too much of a burden on your device. Do you have device with more memory ? For example, Switch have the possibility to get to 6G while the Switch itself has 4G.
can you get an out of memory error if you create enormous amounts of garbage in one frame?
i'm not sure how that works
Yes, you can.
i figured the GC would get invoked to clean it up
but i'm actually not sure where that happens
my understanding is that it can run any time you ask for memory (which is why you see long delays in your functions when the GC runs)
Garbage collection occurs when one of the following conditions is true:
The system has low physical memory. The memory size is detected by either the low memory notification from the operating system or low memory as indicated by the host.
The memory that's used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you don't have to call this method because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
I don't currently. But the error might be in the code? Since it occurs whether I profile it or not
Yes, but you need the profiler to know what the error is.
At least, to help.
I have HexTerrain generator and a path finding system in the scene.
I am performing the same pathfinding operation again and again.
It works fine for some time, the memory usage is stable at 0.5 GBs,
But then it freezes and memory spikes upto 4.5 GBs.
I'm not performing any other operation whatsoever.
that feels like the pathfinder is getting stuck in a loop
what algorithm is it? do you maintain open/visited lists? does the algo maybe not terminate under certain conditions?
It's A*.
Yes, I do have open/visited lists, But I'm using pooled lists and not creating them everytime the function is called.
you might be filling up the pool with additional lists if you dont release them for some reason
a pool doesn't fix memory leaks
might just be a missing release somewhere?
I've checked and the Pool count remains stable.
Are you sure the issue is the Pathfinding ? Sometimes the place where the Out of Memory happens is not the reason why the out of memory happens.
Here's the code if that helps
I actually don't know what the issue might be, that's what I'm trying to figure out
This is why you need a profiler.
Yes, but the memory profiler does not work after the error 😕
Because your application has crashed because of your out of memory. This is the reason why you need a device with more memory.
Otherwise, you need to go blind.
why not try getting rid of the pool and seeing if the issue remains?
just eliminate one avenue for spooky action at a distance
And do trial and error.
Probably don't go stabbing in the dark until you hit the jackpot
Reproduce the error in some way without crashing first.
Does it happen in editor or only on device?
Both. Editor and Development Build
In editor are you able to make a big spike happen but without causing it to crash?
Yes. It freezes for a while when the error occurs and resumes after
OOM error?
Yes
Are you able to cause a spike without it going OOM?
No.
Initially memory usage stays stable (0.5 gb) but then OOM occurs and memory spikes to 4-5 GB
Does it always happen when you do a certain action in your game?
Currently there's only Pathfinding happening in the game and it usually happens when I initiate a new pathfinding operation
I have taken several snapshots, before and after the spike
But strangely enough, I cannot open the 'after spike' snapshots. The Memory profiler just stays at the 'Busy for x seconds' dialog forever.
Profiler is probably dead after the OOM error, which is why I'm trying to guide you to reproduce a big spike without it going OOM.
The error occured when I wasn't using Pooling, then I tried Pooling to try to fix it. But no luck.
If you have a consistent way to trigger OOM, then start stripping things down to lower memory usage, until you can get a spike but without it going OOM, so you can actually use profiler and figure out what's causing all the memory allocations.
Otherwise you could spend all day poking at random parts of your code praying to get lucky.
So, I did manage to get before and after snapshots.
The biggest change in the after snapshot is increased Managed Heap size.
Most of the 'Objects' seems to be same, there's not much increase
Also, Empty Fragmented Heap space has increased
Well your managed memory went up a whole GB.
I don't really use Memory Profiler, look around and it should have detailed breakdown on stuffs, but it seems like you got a huge allocation somewhere.
On the frame that allocation spikes, should be pretty easy to track down what's allocating.
The managed heap is most of the time associated with memory you allocated in a script, such as array. The fact that you have that much memory being reserved means that at some point, you had a really high demand in memory. If you use the Profiler (Not memory profiler), you should see a high amount of GC.alloc happening at a specific time. By using the "call stack" with GC.Alloc enable, you should see where they are coming from.
I currently have an inventory system in which you can pick up items, see items in inventory, drag them around, drop them,... but i'd need help making it so you can equip those items with the stats if I could screenshare 10m
Better to post your issues here if you want help
I'm trying to make it so that somewhere in the gray section inside the square, a gameobject will spawn. However, since the blue section uses a edge collider I don't know how to make sure that it isn't touching the blue section, can I get any help?
How do you generate the blue area?
I have the video I used, but it mostly uses cellular automata with some modifications like ensuring there are connections between the gray areas
You could generate a space representation(basically a 2d array of points/bools) describing the occupancy of your game space when generating the shape. Then check against it for collisions.
Correct me if I'm wrong, but since the blue area only uses edge colliders, that would mean the inside wouldn't have collisions and thus it wouldn't work?
What wouldn't work?
What I suggested would work regardless.
Would it not only check colliders or would it also look at meshes?
Wat? My suggestion is for you to check if the space is occupied manually. It doesn't have anything to do with colliders.
I'll look it up and see if I can understand it, I'm not very good at understanding code
But if you can generate am edge collider, you can probably generate a polygon collider too, which should allow overlap collision detection
I'll test it, might be a while though.
I want to be able to control characters through either player control or AI control, is it possible to do this through the Input System?
Where I keep all the same actions
AI can't really push buttons on an input type like a mouse so no.
But if you want to use the same code for both player and AI without having to change things set up a statemachine.
You can change states based on direct input (from the player) or on information provided to the AI.
E.g. moving.
Player presses button > set state > state runs function.
AI sees player and wants to chase > set state > call same function
Then you can turn the state "off" when the players let's go of the button or the AI can't see the player.
AI can't push buttons, but what I meant was more so the functions associated with it, so like for example there is the "Fire()" function when a player left clicks, and I want that logic to also apply to an AI controlled version of that player
rather than having redundant code
Yeah so use a state machine and put the logic from fire() into it. Then when the player presses the button, set the state to firing() which then calls the function logic.
Then when you want the ai to use firing() it just calls it based on information given to it rather than input
That way you have the same logic for firing
But it's called differently based on the agent
Different question, for the input system, it is it's own mono behaviour that calls functions associated with input actions?
It's a bit more complicated than that and would take a lot of typing to explain. However you can generate a class file from your input controller if you want to see some of its inner workings.
In regards to the statmachine stuff it's again another topic that would take a lot of typing to fully cover but this tutorial is very good and explains thr concept. It'll take some time to set up but I think it's what your looking for
https://m.youtube.com/watch?v=Vt8aZDPzRjI&pp=ygUTc3RhdGUgbWFjaGluZSB1bml0eQ%3D%3D
Learn the fundamentals of programming State Machines in Unity with this new video break down!
This tutorial explains important concepts of the State Pattern, and how to use State Machines when programming! Today we will walk through an example project to showcase the benefits of using state, the state pattern and state machines in Unity!
This ...
is there a more programmatic way to do animation events?
animancer asset
i wanna way to get advertising id on android is there way to do it? they removed from this on 2019 https://docs.unity3d.com/ScriptReference/Application.RequestAdvertisingIdentifierAsync.html
In game, you usually do not have the possibility to comfortably define what is an available zone. The exception is if you are already using pathfinding, then you can easily find a point on the desired zone as the pathfinding already has done the work.
Most of the time, random placement is done by using "zone" of availability as this is the fastest and the least error prone. An alternative is to use a point of reference that we know is inside and then raycast randomly.
Depending if your need is runtime or not, you can use https://docs.unity3d.com/ScriptReference/AnimationUtility.html.
Hi guys, I would really appreciate some help if anybody tackled with this before... I am not entirely sure if I should post this in advanced or beginner. I am beginner myself but I feel like topic is quite advanced so I will post it here. I am trying to make stable diffusion work in AR. To do so, I first need to make dynamic tracking for which I need to add images in my library during run-time, and with that I am having issues. There is only a few documentation out there but this is basically what Ik so far. I need to use MutableRuntimeReferenceImageLibrary object, which will be created from ARTrackedImageManager object (because ARTrackedImageManager cannot be edited in run-time, while MutableRuntimeReferenceImageLibrary can). What I am trying to do is taking a picture on button press and then set that picture as new tracked image. I am currently using version ArFoundation 5.0.5, Google ARCore XR Plugin 5.0.5, OpenXRPlugin 1.7.0. I should also mention this is supposed to be android app. Stable diffusion will be done on pc and then sent over api to mobile device.
Exception occured while loading the dll file is : System.EntryPointNotFoundException: Unable to find an entry point named 'GetRandom' in 'myapplication'
I am getting this error when I implement it in Unity by using dll import
I have no idea what I am doing wrong. But, I know for sure that there is something I am not doing correctly, I just don't know what it is
Please help me out as I have been trying to do this for the past 5 days and getting this same error every time I try to do it. I have tried almost everything that I know, googled for the solution. I absolutely have no idea what mistake I have been doing.
how do i split a BitArray into portions of equal size? eg. turning
10 01 01 01 11 00 10 10 11 00 00 into an array
2,1,1,1,3,0,2,2,3,0,0?
or even better getting a select portion of bits based on an index eg index 4 returns binary 11 -> int 3?
the size the portion of bits are can vary eg 0 , 10101, 111 etc.
this doesn't sound like a Unity problem - sounds as if you're overcomplicating though, just write a wrapper/extension with basic math operations to read the relevant index and span (it's just an array)
What shader should I use for 2d grass? cut out shader or transparent and 2d rect shape or polygon shaped sprites?
Games like cult of the lamb
Those are regular sprites that auto align with the camera plane (billboards) around a pivot at the bottom center
So transparent shader + 2d rect or polygon shaped?
Either
This isn’t graphics bound in any way
You don’t even need transparency
Just alpha clip
and as you mentioned about rotating/aligning the sprites. You mean they don't look at the camera? Instead rotate around their pivots at bottom center in screen space?
Because in my game, the number of them can be huge.
Yes, in cult of the lamb, it is not high
Profile your design so find out how many you can have
If you do the billboarding on the shader it will be cheaper
Is there any way to assign a Component dynamically by a string instead of a type for example gameObject.AddComponent<stringToType("MyComponent")>() ? For my importer I kinda need to map Google Sheet strings to mappings of Components if that is possible. I want to avoid a large switch statement to map every possible string value.
gameObject.AddComponent("MyComponent")
what... no
Yes
Read the third overload: https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
lol ok will try asap
I mean AddComponent
Same deal
the first overload
though it does seem to be marked obsolete
It will still work
It's basically just going to be doing reflection under the hood - so you could also do the reflection yourself if you want.
Assets/Editor/Bangerang/CardEffectImporter.cs(200,38): error CS1501: No overload for method 'AddComponent' takes 1 arguments
Do I need to disable some compiler checks here?
public static T AddComponent<T>(this UnityObject uo) where T : Component
{
if (uo is GameObject)
{
return ((GameObject)uo).AddComponent<T>();
}
else if (uo is Component)
{
return ((Component)uo).gameObject.AddComponent<T>();
}
else
{
throw new NotSupportedException();
}
}
I am sure this is some dead code
What's UnityObject? Also these if statements can be simplified like so, using extended pattern matching
if (uo is GameObject g)
return g.AddComponent<T>();
You're using the wrong version of Add component
There's no generic type parameter for the one you want
That's Unity code not mine
Yeah so as mentioned you need to use the overload that's not generic. AddComponent(string), then cast the return type to whatever type you need
Oh that's interesting - I never realized that I am using the stuff from the VisualScripting package 🤮
I have this piece of code that I'm having trouble with. Essentially, I have a 100 x 100 area with the center being 0, 0 and I want the object that has this script to go to a random spot on the area. However, there are some areas I want them to stay out of, those areas are randomly generated so I can't predict them, and they don't have colliders. To fix this, I tried to make a multidimensional array that would set an area to false if it could spawn there, and true if it couldn't. However, it will sometimes tell me something is false, yet it spawns in the bad area (Sometimes it will spawn in the good area)
Some relevant information might be that the width variable is 100, the height variable is 100, and hasTile is the multidimensional array.
sorry, kind of long
I'm trying to understand, is the alg setting this 2D grid or are you doing something manually after it's being generated? Seems like something you'd want to integrate into that functionality when it creates a level.
When making a mesh via mesh.combinemeshes, do I need to do anything special in order for that combined mesh to be able to be combined with another mesh down the line? currently having issues with it
issues as in the mesh inexplicably doesn't show up when I merge with others
No warnings are shown in the log, it's not a null entry, I know for a fact the mesh exists
but when combined? nothing
the only possible way it's different is due to it being a mesh that was the result of it being combined, so I need to know whether that's actually the issue or I'm just cursed
what do you mean by this? Like including it in the script that generates the map somehow?
Right, you should be adding the constraints as the level is generated and have a populated grid when it's completed
the grid idea is fine if you're not trying to use colliders
Is there a reason the areas you can't spawn into that you rando generate dont have colliders?
Easiest approach would be to add them, set a tag or layer mask to them and then overlapsphere to check each area for that tag/layer before spawning.
When I said there weren't colliders, I wasn't exactly telling the truth, there are edge colliders, but not ones for the inside of the bad area, just the edges. I shortened it because it didn't seem like an important distinction.
Overlap should be fine then, no?
Should be able to detect them then
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
Forgive me for asking but, how would this work? since the inside of the bad area doesn't have a collider I would only be able to check if it was on the edge of the bad area right?
If you know the size of the areas you can't be in you can use two nested overlaps one checks if your outside one checks if your inside
If both pass. Spawn player
It'll probably be more complicated than that but you can add more checks to player location based on your project needs
Might want to add some debug info. For example print the spawn position and the indices of the grid that you check against, and compare it to your occupancy array. Really, you're supposed to be able to do this kind of debugging if you post in this channel...
I think there's no issue with finding an empty tile. The issue is probably that your spawned object occupies more than 1 tile, so it seems to you like it spawns in the occupied area.
I thought I already had enough Debug info but I'll look into adding more, as for the second part I've included an image, the green dot is the object, the blue dots are the surrounding whole number coordinates, and the blue area in the background is the bad area. I don't believe the object takes up multiple spaces, and the top left one is also considered in the bad area according to some debug info I got.
Then either your occupancy data is wrong, or you're not checking against the correct position in the array. Both of these you can debug and confirm with the visuals.
I figured something out, after looking over the code again I had some unnecessary code, after removing it it worked!
I'm implementing my movement system for my 2D top down RPG via rigidbody2D.move position, the exact code I use is:
character.rb.MovePosition(character.rb.position + movement * character.Speed * Time.fixedDeltaTime);
where the movement is
float moveVertical = Input.GetAxis("Vertical");
movement = new Vector2(moveHorizontal, moveVertical);```
and I've verified that it's running during every fixed update, but I still seem to get micro-stutter. Why?
Try pixel perfect camera, unlikely to fix, but worth a try
already have it added to my cinemachine
Try normal update with deltatime instead of fixedupdate
that doesn't seem wise
Why not
doing physics in update is not ideal
also there's just no reason there would be a difference
if it's running on every fixed update and being modified with fixedDeltaTime then it should be fine
Are physics necessary to implement movement in your project?
do u have interpolate on by chance?
I just turned it on
but I just realized, I think it's due to cinemachine
I turned off the cinemachine follow and it's butter smooth
i havent used pixel perfect so i cannot comment on that, i know that i have jitter when my character ragdolls insanely fast only
well it seems smooth because ur camera isnt moving anymore
the issue is that your player is moving but the follow isnt updated fast enough (i believe)
which implies it's an issue with the camera follow rate right?
Try making smooth follow instead of regular stiff follow
yes, 1 sec there was a nice link i have somewhere
thats odd i really thought i bookmarked the link that talks about camera jitter.. this isnt the one i was thinking of but its relevant
https://www.unity3dtips.com/unity-fix-movement-stutter/
did u try it with interpolation on and camera following the player?
yeah
looks like this
it feels like there's still micro stutter on it
i think it has something to do with the fact that I have cinemachine set to smart update and it's using late update?
late update should be good
hmm
this is the original link i was trying to find
https://kinematicsoup.com/news/2016/8/9/rrypp5tkubynjwxhxjzd42s3o034o8?utm_type=SMVideo
you can see the moments when the camera is not exactly following
once near the start and once at around 8s in my video
my suggestions wouldve been using late update and interpolate.. but if this happens with both then im unsure
maybe see if it still does the same as a build?
will do
actually that 1 frame at around 2 seconds indicates to me your animations and transform does not line up
the camera moves when the player doesnt
i think that's just due to the animation not starting yet though, right?
public override void FixedUpdate(Character character)
{
character.PlayAnimation("walking");
character.rb.MovePosition(character.rb.position + movement * character.Speed * Time.fixedDeltaTime);
character.FinishAction();
}```
cause I play the animation immediately before the move position
(the play animation function doesn't do anything if it's the same animation)
i do think it is a desync between animation and transform because u have 1 frame where the camera moves to the left. then from 2-7 seconds in the slowed video, your player movement seemingly lines up with the camera movement. But at 8 seconds u can see the animation (or transform) shift to the left
it seems like the camera is following properly but its hard to tell, im not really an expert on this. maybe draw a sphere where the real transform is as u play, then slow down the vid to see those jitters
wouldn't it be visible when I disable the camera follow then
no because your only visual is the animation, theres nothing to compare it to
if it appears butter smooth without the follow camera, then what suggests it's not working properly?
comparison
both look good
i know the movement is smooth when the camera isnt following, thats because the animation is always smooth. its an issue with the camera following the transform. But i dont believe the camera is following at the wrong time, i think the transform isnt always at the exact place of the animation.
it does not, look at the video i sent above, there are clear jitters
ah fair
ehh nope
it does look good overall but being hyper nitpicky
also the only reason i thought of this was because the camera moved BEFORE the animation. Which means the transform moved, but the animation did not
i don't understand how that'd be possible though if the rigidbody is attached to the same game object as the sprite renderer
what is the camera attached to ?
you will need to draw the actual transform on the screen to be able to debug this and see if im correct, i might be wrong even
maybe make the camera seperate from the body
the camera is attached to the parent of that sprite collection
no ?
i mean atleast thats how you do it in 3D
It already is
hmmm
really weird
cuz its the background thats jittery, so i guess the camera script is not moving the camera smooth
how would you recommend I do that?
protected void FixedUpdate()
{
Debug.DrawLine(Vector3.zero, new Vector3(5, 0, 0), Color.black, 2.5f);
Debug.DrawLine(Vector3.zero, new Vector3(0, 5, 0), Color.black, 2.5f);
doesn't seem to do anything
pls dont try and guess a solution.. we're already trying to see if the problem is what i think it is
try using OnDrawGizmos()
Gizmos.DrawWireSphere(transform.position, size);
https://blog.terresquall.com/2021/12/fix-jittery-camera-movement-in-unity-with-rigidbody-interpolate/
I found this

thats how most here fix problems, just trying out stuff suggested, but if you dont want to listen to people helping you lol
did u even read the article, or the conversation?
u might be right, transform seems to be updating before the sprite renderers?

uh that looks off, why is the circle always at the start
it's a gizmo
oh i see the red lines
the red lines are the transform pos
yea here its clear
can i see your hierarchy for the player/ what the animator is playing off of? i havent used 2D so im not entirely sure if my next idea will help u
i have 3 sprite renderers that are attached to the human game object