#archived-code-advanced
1 messages · Page 49 of 1
There is no overshoot.
It tries to land at half in the wall, but it lands further because that point is unreachable
Because the calculation find the correct velocity base on the angle and distance
It wont land in the wall if you adjust the height
Velocity, angle and distance got nothing to do with the y offset
Then use Height and distance
And that y offset is exactly the problem. Because if I put the height higher, the distance will be greater and too high
That's the problem I got with the raycasts I was using to determine the height
Because it calculates the distance based on diagonal instead of horizontal
Which is logical, but makes it much harder to calculate a precise distance point
The code I posted was using diagonal 20
So the distance between the circle and the x point is 20 diagonally
I can show you in like 8 - 10 hours when I wake up again
Because we are probably not on the same line yet
Pretty sure the distance should be only on the X/Z axis
I had a bit of time so I did a small script. Maybe it can help you figure out your issue.
public class Shoot : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private Rigidbody rigidbody;
[SerializeField] private float angle;
[SerializeField] private float maxDistance;
public void Execute()
{
//x = v * t
//x = v * cos(a) * t
//h = v * sin(a) * t + 1 / 2 * g * t ^ 2
//t = x / (cos(a) * v)
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) ^ 2
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) * (x / (cos(a) * v))
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h = sin(a) * (x / cos(a)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h - sin(a) * (x / cos(a)) = 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) = cos(a) ^ 2 * v ^ 2
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) / cos(a) ^ 2 = v ^ 2
Vector3 delta = target.position - transform.position;
float distance = Mathf.Min(Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z), maxDistance);
float height = delta.y;
float a = 0.5f * Physics.gravity.y * distance * distance;
float b = height - Mathf.Sin(Mathf.Deg2Rad * angle) * (distance / Mathf.Cos(Mathf.Deg2Rad * angle));
float c = a / b / Mathf.Pow(Mathf.Cos(Mathf.Deg2Rad * angle), 2);
Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
rigidbody.velocity = direction * Mathf.Sqrt(c);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Execute();
}
}
}
How am I to go about debugging a segmentation fault. I’ve never had to debug a crash stack like this before. I think it says something about cameras.
I’m on a slightly older version of Unity 2022 so should I just update and hope it goes away
There are a bunch of tasks in my voxel game. Also, there are some workers who do these tasks.
I want to show if a reachable path from a worker to that task exists or not.
From my view, flood fill is OK.
Partitioning the world to some connected areas.
Do you know better way to handle it?
hello, anyone knows how to override package scripts? (if they dont have any virtual or abstract modifier)
when i attempted to edit the script, it said:
The package cache was invalidated and rebuilt because the following immutable asset(s) were unexpectedly altered: Packages/com.unity.2d.tilemap.extras/Runtime/Tiles/RuleTile/RuleTile.cs
heres my question from #🖼️┃2d-tools
#🖼️┃2d-tools message
if you need to edit a package file you need to copy it out of the packages location and stick it in Assets
i think so, i havent done it in a while
actually i think you move it from PackageCache to the Package folder
like this?
i will hope this is the way
Hi!
I am writing a test for an editor script in Unity Test Framework and come across a problem where it reset the test midway as the test enter play mode twice. And I realised the UnitySetUp is called whenever it enter playmode.
Is there a way to prevent it?
Did you try Unity NavMesh ? It is one of their supported scenario. Otherwise, standard A* star path-finding should work in most case. If you really, really, really want more performance. You could precompute each entrance-exit foreach "chunk" and then use each "chunk" as a node for your A*.
https://learn.unity.com/tutorial/runtime-navmesh-generation#
In this live training session we will learn how to work with Unity’s Navigation tools at runtime. We will explore the publicly available Components for Runtime NavMesh Building and look at how we can use the provided components to create characters which can navigate dynamic environments and walk on arbitrarily rotated surfaces, including enemies that walk on walls. In this session we will learn how to bake NavMeshes at runtime, including for procedural style levels.
Do not override package script. (Except if you really, really need to) It is not a good practice. If you want to override a package. You need to extract the whole package in your project. Copy it from the Packages Folder and then remove it from the package manager. Also, clear the PackageCache.
Alternatively, you could use a script that would contains a TileMap and instead of using directly the TileMap, you can call a function on your script which will alter the functionality. That would be a sort of "Bridge Pattern".
Example:
public class MyTileMap
{
private TileMap map;
public void SetTile(Vector3Int position, Tilemaps.TileBase tile)
{
map.SetTile(position, tile);
}
}
No, I do not want nav mesh unity
It is not for voxel based games.
So, you say a star with many workers and tasks is better than flood fill?!
I just want to know if it is reachable or not
Flood fill, if I understand correctly, is Breadth First Search.
I don't think a star is a good way to handle this scenario.
Yes, I have implemented a star and used it to find best path
Breadth First Search being the worst algorithm you can do that will find the fastest path.
It is the most basic one.
You did not get my problem I think
The question is not to get the best path from worker1 to task b
There are task1,...., task n in different positions
There are worker1,..., worker m in different positions.
Q:find is there any path from any worker to task1,..., task n
Isn't time consuming to run a star for each pair worker, task?
A* will still be better than Breadth First Search in any circumstance.
Yes, it is.
Even more if you want to find the shortest path between a Start point and N tasks.
But, you do not need it to be instantaneous. You can make a little animation: <Searching> for your character which could buy you a lot of time to run the algorithm.
if MonoBehaviours are only executed in Play Mode, how come DrawGizmos work in Edit Mode?
Unity detects that the method is implemented, and calls it.
You can have MonoBehaviour instances running in edit mode by applying a [ExecuteInEditMode] attribute on it
void OnDrawGizmos() {
if (Application.isPlaying) return;
// do stuff
}
Can I have a script run only in Edit Mode
Yes.
[ExecuteInEditMode]
class MyEditModeScript : MonoBehaviour {
void Update() {
if (Application.isPlaying) return;
// do stuff
}
}
Or you can write an editor script.
or does it already happen if I only have a OnDrawGizmosSelected function for example
It's not a matter of MB's working at runtime and not at editor time, it's just that Awake/Start/Update etc. are usually only called at runtime, but Reset, OnValidate, OnDrawGizmos and OnDrawGizmosSelected will work in editor as well.
What are you trying to do?
a script only for drawing gizmos
Then just implement OnDrawGizmos()
You don't need any checks
That's just how it works
and I'm thinking how inheriting MonoBehaviour will bloat my Game assembly
ehh, I think I'll use handles instead
MonoBehaviour will be in your assembly no matter what
of course, but the small script only for edit mode will be too
no it will not
editor only code is not included in a build
What is editor only code?
duh, code that only runs in the editor, like OnDrawGizmos
nothing to do with the compiler, look at the unity code stripping docs
I'm getting very mixed velocities
Especially when it's out of range. It can jump really far when going up and not far when it needs to go down
What about if there is no path between workeri and task j? When run a star
You limit your search.
Hello
I'm using URP
Have material A with texture (binded)
Have material B withOUT binded property
So the question is how to set property of material A to B
in runtime
switching forward renderer feature?
What do you mean by switching forward renderer feature ?
sorry for a late response,
i did copy it from the Packages Folder and then removed it from the package manager and cleared the PackageCache. its working, but i realised i need completely different script for this which is my problem and wont be hard to fix
Like here
So, it has nothing to do with materials ?
I have normal texture on URP/Lit material
and when I overriding material NormalMapMaterial (it has no normal texture) I could set it manually, but what would I do with other URP/Lit materials?
The best solution is:
Get rendering material; Get property; Set property to override material Render
I do not understand at all what you are trying to do but.
Did you try to use the Layer Mask ?
Did you try to use SetTexture on the materials ? https://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html
But I cant GetRenderingObjectMaterial() because this feature is under the hood
Maybe it become more understandable
Wouldnt that be drawingSettings.overrideMaterial ?
Can you not get the current drawingsetting
Because I see you created a new one.
Drawing set required to
context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref _filteringSettings, ref _renderStateBlock );
No
Then what materials are you trying to get ?
If the GetRenderingObjectMaterial is really a function, you could potentially use Reflection to get to it. I would be surprise if it is really what you are searching.
Materials on object which can be rendered by camera (better in array)
No it's pseudo code
What material?
DrawSetting is a struct (like a cartridge), you set data there, then feed it to context.DrawRenderers
For example in Oxygen not included, I don't think I have seen limitation in searching.
So they have limitation or their world is small kinda?
What GetRenderingObjectMaterial is supposed to return ?
No
Man, I had written it for example) It's unreal
What GetRenderingObjectMaterial represent then.
That is what I'm trying to understand.
A material on first object in render queue
What object ?
Pretty sure Render Feature are kinda like postprocessing. I might be wrong.
There is always limitation.
Hmm
So I must change materials on objects because on post processing there is no objects anymore...
Thanks)
I mean, you do not work on the object directly. You work on the whole.
But, like I said. I might be wrong
What you wanna do, is maybe a shader. If you want to change the behaviour of the rendering of each object.
Yes)
Im having a hard time creating an arrow in editor window, but the problem itself is probably more related to math/rendering so maybe here I will find some help.
As you can see arrow is getting narrower with the angle between nodes increasing (or deacreasing in this case i guess). Actually arrow itself appears only in 2nd and 4th circle slices (but ive noticed that if I change indices order it appears in 1st and 3rd). I dont understand what im doing wrong here :/
start = edge.GetPoints()[edge.GetPoints().Length/2 - 1];
end = edge.GetPoints()[edge.GetPoints().Length/2];
Vector2 lineDirection = end - start;
Vector2 midPoint = (start + end) / 2;
Vector2 perpendicular = new Vector2(-lineDirection.x, lineDirection.y);
float arrowEdgeLength = 12f;
float distanceFromMiddle = (arrowEdgeLength * Mathf.Sqrt(3) / 4);
MeshWriteData mesh = ctx.Allocate(3, 3);
Vertex[] vertices = new Vertex[3];
vertices[0].position = midPoint + (lineDirection.normalized * distanceFromMiddle);
vertices[1].position = (midPoint + (-lineDirection.normalized * distanceFromMiddle))+(perpendicular.normalized * arrowEdgeLength/2);
vertices[2].position = (midPoint + (-lineDirection.normalized * distanceFromMiddle))+(-perpendicular.normalized * arrowEdgeLength/2);
for(int i = 0; i < vertices.Length; i++)
{
vertices[i].position += Vector3.forward * Vertex.nearZ;
vertices[i].tint = Color.white;
}
mesh.SetAllVertices(vertices);
mesh.SetAllIndices(new ushort[] { 0, 1, 2 });
How can I get the position of a mouse click inside a scrollview content panel?
I want to position a UI item where the mouse is clicking within the scrollView.
hello there
im working on a enemy AI
that patrol on random way points
and should chase the player when get close
the patrol works fine
but it doesn't detect the player tried to debug and nothing shows in the console
here is the code for the AI
https://hastebin.com/share/dirasilapi.csharp
and the Weapon
https://hastebin.com/share/vejiqohupe.csharp
propably Event.current.mousePosition
The PointerEventData parameter you get in IPointerClickHandler's OnPointerClick method contains that information
All of the positions returned are happening in the screen space or world space.
None return a position according to the view of the scrollview.
if you use a Screen Space - Camera canvas, then world space position == canvas space position
if you use Screen Space - Overlay, you have to convert it
Even using Screen space camera, it still returns the screen space position.
All of these clicks show the same position.
"it" being what exactly?
@sly groveAll of these clicks return the same position. I am trying to make my level editor inside of a scrollview, and I need to get the mouse position according to the view of the scrollview.
How can I do that properly?
what position are you talking about? Wdym by "clicks returning positions"? Can we get specific about where you are getting this data?
and then how are you using this position?
I am debugging it.
yes but - you are saying it's incorrect. That presumably corresponds to some particular technique of positioning an object

So in the video, I demonstrate clicking in the same screen corner, with a different view on the scrollview.
Are you using it to set a RectTransform's anchoredPosition?
Setting a transform.position?
I want to use this position to create a tile at that position in the scroll view.
Right - note that the pointer event data contains other concepts of "position" as well. position is the screen space position
There's also
https://docs.unity.cn/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.PointerEventData.html#UnityEngine_EventSystems_PointerEventData_pointerCurrentRaycast
https://docs.unity.cn/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.RaycastResult.html#UnityEngine_EventSystems_RaycastResult_worldPosition
for a screen space camera canvas, I expect you can use the worldPosition, and then set your tile's transform.position from it
Move the code of OnTriggerStay to Update. If you do not know how. #💻┃code-beginner
will try it rn
If I submit a bunch of mesh data to NavMesh.UpdateNavMeshDataAsync(), while the function runs asynchronously, it still locks up the main thread while it does most of the calculation? It seems it's running the vast majority of NavMesh.TileMesh() before the frame even begins rendering? Is this just a known limitation or is there a way around this?
Thank you, PraetorBlue.
I am using
Debug.Log(eventData.pointerCurrentRaycast.worldPosition);```
I've attached a video that demonstrates the debug log output always of roughly 9.8 on the X and -3.9 on the Y, regardless of where the scroll view is panned to.
yes that's fine
and correct
the point is now if you position your block there with transform.position
the other objects have moved
so positioning it there in world space and parenting it will work fine.
You are moving the rest of your UI when you drag
i tried but still the same
even this didnt work
void Update()
{
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
if (distanceToPlayer <= chaseRange && !isChasing)
{
StartCoroutine(WaitBeforeChasing(2f));
}
if (!isChasing)
{
Patrol();
}
else
{
ChasePlayer();
}
}

https://docs.unity3d.com/Packages/com.unity.mobile.notifications@2.1/manual/index.html
Unity only supports preloaded/prescheduled push notifications. My game is multiplayer and I was hoping to be able to create dynamic notifications that could trigger somewhat on demand, even for clients who may not have activated the game in a few days. Is there any sort of solution to this? Any background processing or ability to do so? I could write a web api for the notification content, but I don't know of a way to get the app to call it in the background.
https://github.com/nintendaii/unity-background-service
Maybe this? Or some other background service
At first, it seem to me that the issue could have been a Collider Setup which does not seem like it because you remove it. I do not see anything that it could be quickly. It would require access to the code in a working environment to continue debugging.
You should try #archived-code-general or #💻┃code-beginner. They will be more inclined to help you through the whole process of debugging. Normally, you should be able to find the issue yourself. If you want to do it, there is multitude of ways of doing so.
- Algorithm Trace
- Logs
- Breakpoints
- Find the minimum working code
- Isolate the non-working code
- Reduce the number of parameters
- etc.
Unfortunately, I'm only able to do a partial algorithm trace and I need to guess most of the values which make it near impossible to debug for me.
Also, you should definitely look into StateMachine/Behaviour Tree. A clean architecture helps in debugging.
You probably need actual native push notifications or native local notifications based on native scheduling, depending on what you're doing
okay mate thanks
i posted in Code Beginner
im trying to debug and find a fix for like 7h now and still nothing
i will stick with patrolling until i find a way to make the AI chase or at least Attack the player
That is part of programming :P. Perseverance is one of the strongest qualities of a programmer. I'm sorry to not be able to help you more.
its okay mate
Like @bright wind said, to be able to push notification you will probably need to use directly the functionality of the device. I have not done a lot of Mobile development, but for console like Nintendo Switch, Xbox or PS, you have library that has been create with unity that provides access to the console functionalities.
Yeah. That's what I'm thinking. The library I linked in the OP handles scheduling just fine- so we can do stuff like every time the login, queue up some several weeks of notifications.. but it's the "this user hasn't logged in for several days and we're having a sale or limited time event" and want to be able to truly push that out to the userbase
The issue is also partially that I'd need to build a resilient webapi that can cache and deliver these notifications since the full connection to the game server isn't necessary or appropriate for getting this data
And I don't have that service in my stack yet
I have done Mobile Application directly from Android Studio, and I remember we had some functionalities like that we could use.
This just sounds like basic native push notifications - doing things like Android services for this are not ideal, and you'll have a few bits of headache trying to get stuff to run long after the user hasn't opened in a while etc - your use case sounds more like a push notification, and going that route would also fit well with "hey, I want to start a sale, let me create a notification server side and push it out to all clients" instead of having to push an app update etc
Looking into https://docs.unity3d.com/Manual/android-BuildProcess.html. It seem that if you want to expand the functionalities, you might need to build from Android Studio.
Yeah, I don't particularly want to roll a service just for this. I could probably just say to the content team that they need to queue up sales and limited time events months in advance so we get the clients to connect to the server and download the notifications and schedule them ahead of time, which seems to be easy using the unity library.
I'm not gonna be building from android studio 🙂 Ever, if I can help it.
I have this kinda "pool" with 2500+ colored balls in it, how can i deal with performance? I tried my best but it still goes to around 15-25 fps
What the profiler looks like ?
Are you struggling with the GPU or the CPU ?
How many draw calls you have ?
What is the time per physics update ?
What are the settings on the rigidbody of the Sphere ?
there is no rigidbody on the spheres
its just an idea that i would implement
if performance talking is good
You have 1.6k draw calls...
thank u
You will probably use GPU instancing.
Also, you should look into LoD and Culling Group.
https://docs.unity3d.com/Manual/LevelOfDetail.html
https://docs.unity3d.com/Manual/CullingGroupAPI.html
what do you mean for "use batching tool to regenerate uvs"
If you have multiple object with same materials but different texture. You might need to change the UV to get the correct texture if you merge the texture together.
But, with Unity. You just require to make an Altas.
its only a one color material
it hasn't textures like albedo or normals
normal map*
I think GPU instancing can handle single color.
lemme try
Also, use the Frame Debugger too visualise the draw calls.
even with gpu instancing is laggy
i even tried to enable in the player settings static batching
same thing
even dynamic batching
How many batch do you have now ?
lemme see
oh just one thing
i even removed materials from balls
and its still laggy
same batches
Which mean that it failed to batch it together.
so?
hmm never used it tbh and it's a lil bit complex
like i enable it and it pause the game
Yeah. It is expected.
Then you look at each draw call.
And see why it is not batches with the previous.
Something like
this is the ball
You have 91 batches
this is an object of the playground
Which is fine.
There is nothing more you can do there.
What you want, is use LOD and CullingGroup
maybe i havent rendered the right thing?
bro i make 25 fps with the balls
and without 90+
there is a problem
yes
Unity is not a simulation engine.
So, it is kinda expected to have some draw back there.
Reduce the amount of triangles.
how can i make something like that
ok lemme try
Reduce the amount of balls
Make them bigger
Also, what is your RendererPipeline ? URP, HDRP or Built-in ?
built in
Use URP
But yeah, Unity is not made for such operation. It is going to cost a lot in performance.
How steel wool studios made that in unreal engine for Five Night's at Freddy's Security Breach
By profiling and optimizing.
installing urp could corrupt something of my project? and maybe could i revert it?
Do you use Version Control ?
because i had bad experience with hdrp
Yeah...
and then install urp maybe
It is a most
With URP, you will be able to use SRP.
That being said, it should be the same of instancing.
I would still upgrade to URP.
is there any method to rotate a 2d vector?
like complex number multiplication?
on unity mathematics
You can rotate any vector (2d or 3d) by multiplying it with a Quaternion:
Quaternion myRotation = Quaternion.Euler(0, 0, 45);
Vector2 rotated = myRotation * someVector2;```
@dusty wigeon how can i enable the srp batcher
i searched over the internet and i haven't found a useful tutorial
unity forum is also offline
i installed the urp
everything is purple lol
Evening guys, I've got a question about json serialization, would here be the right spot?
I'll ask and see I guess ^^'
So I'm pulling stuff from firebase and get I'm getting the right json. but when I deserilize, the object "data" remains empty. I've tried googling everywhere but I'm getting nothing. I would really appreciate it if you stumbled upon something like this. Here's the relevant code...
interesting
There is of course no error given btw
I can give more context of course, but so far the code is this simple. I'm not assigning "data" to anything else (and debuging on this line shows that he object is never changed what so ever)
Let me know if any info could help 🙏 I'm losing my mind ^^'
damn what you working on
Probably a mistype, but that's not valid JSON
extra brace on the end there
indeed sorry, it's a misstype
I have a fleet of tablets in a museum with questions about stuff in the museum. There will be some kind of live leaderboard and I need to know the current progress of every tablet
Have you tried JsonUtility just as a test?
yes, I switched to newton by recomendation of in the forums
I also tried only having an int there, to simplify it as much as possible
(thanks for the help, I appreciate it 🙏 )
you debug data right after it is set?
yep, it's immidietly not set, so it's not that I re-assign it after or something like that
straight debug of the convert?
yes
pass in the string you think you're passing in?
you mean hardcoding the json in the convert parameter?
I didn't try that no, I 'll do that now
😮 progress! so indeed, I'm now getting the "scenarioprogress" deserialized but not the simple progress (int)!
You think there is some sneaky characters in there when pulled I can't see in the debugger or log?
Progress should show 27
I`m trying to create a topdown shield block system
the character is red . He is looking at blue (forward) and can block for up to something like +-30deg.
I have position of hit. How can i know if this position lies between +-30deg?
with unity Mathematics
this is what i have now but the angle is not signed ;/
i need signed angle too
I didn't think this was the case, but could it be order-sensitive?
What do you mean? sorry
swap order of answersCount and progress in either the json string or the class
oh man I just realized lol. you havent been telling me the true structure of the json being returned, have you?
? what do you mean?
the real json has a guid key with a SessionData value
that's why there were two braces in the first image
Indeed there is a GUID as the top of the data, here's a screenshot of the firebase:
However I've sent you all that I'm getting as a return from my request!
I wouldn't hide stuff from you haha
Do you think not getting the root reference, but getting the ref from the GUID would help?
would you just paste the json in chat rather than send me images I can't copy?
sure sorry:
{"fc124f8b562641ab84b5591023dd231556d13988":{"answersCount":0,"progress":27,"scenariosProgress":[0,66,0]}}
That's an object with a fc124... property of SessionData.
Okay so instead of root ref I'm now getting the ref(guid).
I'm now getting the same result as with the hardcoded path! so cleaner progress! thanks a lot guys
the progress value is still 0, so maybe there still is an order issue like you mentionned DROD
Is there an easy way to enforce order when serializing/deserializing?
Here is the updated code: (as picture for readablility, but let me know if you need the text)
Result:
Log output:
Data fetched: {"answersCount":0,"progress":27,"scenariosProgress":[0,66,0]}
JSON order doesn't matter
Okay I hoped as much! then what did DROD mean?
You mean if there is no hidden characters or something?
I mean sure that might be one reason it's not working.
Also try directly logging the result of deserialized session data, rather than inspecting it in editor.
ugh that's it
indeed logging it shows the correct 27
To know the side, use the cross product between the forward and direction between your character and its target.
Something like (Untested) :
Vector3 target = new Vector3(targetTransform.postion.x, 0, targetTransform.postion.z);
Vector3 player = new Vector3(playerTransform.postion.x, 0, playerTransform.postion.z);
Vector3 forward = new Vector3(playerTransform.forward.x, 0, playerTransform.forward.z);
Vector3 direction = target - player;
float side = Mathf.abs(Vector3.CrossProduct(forward, direction).y);
so my issue was indeed getting the rootref that included in the GUID but trying to store it in a sessiondata
There is no cross product in 2d, is there any way in 2d?
Thanks a lot guys 🙏 🙂
Yes, cross product is defined in 2D. It will give you a 3D vector, but it is not issue as you use the y value.
This works for me 😉 https://dotnetfiddle.net/4zllFS
Test your C# code online with .NET Fiddle code editor.
Why do you think the inspector was still showing 0 as a value?
some other code setting it 0 perhaps
Does it has a Vector2.Cross or something equivalent?
I'll have a look around. Thanks again for the help! have a great day/night!
float side = math.abs(va.x * vb.y - vb.x * va.y);``` is it fine?
That is what I was trying to write.
Thank you 🙂
I'm still trying to wrap my head around lol.
But yeah, it is something like that. I cant confirm if you have the correct value at the correct place.
angleToHit *= math.sign(va.x * vb.y - vb.x * va.y);
It gives the right result for me
thank you
Yeah, my bad. I meant Mathf.sign but wrote Mathf.abs. Mathf.abs will always return positive, it is kinda the objective of the function.
I was grasping at possibilities since you didn't send me the full JSON string lol
like I said once I saw, it's because of the guid string. SessionData is a nested object in the json. Doesn't match the root you're trying to deserialize into
You could also just use the ToJson command to create a json output of some inspector example values instead of ltrying to load a prebuild json. This way you can compare your json to what unity expects to import from
Hey, so I have this code that generates a wall of cubes from a width and height. As you can see in the first few lines, there's some code to leave a gap within the wall. The question is, what would be a good way to make the code that adds coords to the _ignoredCoords list?
Let's say I want a gap between 5,3 6,3 7,3 5,0 7,0 (x,y) ? (or a better way to handle this all together)
Thanks!
Hey everyone, got a plugin question: Is it not possible to use a statically linked .lib as a plugin in Unity?
I have static libraries for some platforms in and working but it seems the .lib file does not show up as a valid binary to import in the inspector.
You cannot use Static Library in C#. It has to be a DLL.
I've look a bit the Ballpit of Five Nights at Freddy's: Security Breach. It looks like most of the balls are static in 1 mesh with a small amount of ball that are fixed at first and moves only when the player touch them. They do not collide with each other.
I'm not sure what you are asking. What are you trying to do ?
Here are some insight:
- Use a HashSet instead of a list. See table (HashSet being a Dictionary without values)
- Use OOP (Oriented Object Programming) instead of dictionaries. (struct/class Wall)
- Use Vector2Int or any specific struct to represent your data. (Primitive Obsession) https://refactoring.guru/smells/primitive-obsession
Also, we do not comment on style normally, but maybe you should review the way you are structuring/stylising your code. (usage of not useful comment, usage of var instead of explicit type, usage of single line if instead of two lines, no usage of string interpolation, usage of nested constructor/function call) - All of that being personal preference
Otherwise, there is no real "load" in the code your are showing except the Instantiate that could potentially be pooled depending on the context of usage. (At max a 100 of iterations with an handful of "miss/ignored") If you have a lot of misses AND you use a lot of similar loop (for{if(ignored) continue;}), you might want to try to model in function of what you have instead of what you ignore. But I would be surprise that it is the case.
Static library
Has anyone done anything with OpenAI API with unity yet? Just looking at doing a project atm for an App using unity that uses the OpenAi but Just wondering how it went if u did do it and what kind of road blocks you faced doing so. This is purely a code based question in terms of how well it went implementing it
Hi, I need some advice
If I have an inventory item of different tiers. Basically in card games where you combine 3 cards to a 1 better card
Should I have different scriptable objects for different rarity or just one which hold all the details?
Probably cleaner to keep it as a single SO and just check what variables to use when you read it.
chat gpt api are not free anymore so you have to pay for each call you do, about implementing the api there was no problem, there is even a chat gpt wrapper for unity on github
I genuinely meant to know what you meant! because it seemed like you were onto something and didn't want to just ignore advice and didn't know order could affect anything!
Nice! thanks!
I extended a script but it's editor script is hiding my properties from showing up. What should I do?
you gotta add your fields to the editor script or draw the default editor above/below
ok thanks
Is there a build in way to listen for changes on a serializeField? I need to pass the change to a depending class. Since properties do not really work, and fields don't have a way to emit changed (AFAIK), I am kind of stuck. I did find this, but I was wondering for a build-in way: https://stackoverflow.com/questions/63778384/unity-how-to-update-an-object-when-a-serialized-field-is-changed
Did you just try to hook into OnValidate if that already fits your needs?
Or do you talk about an actual observer for one field?
Ah just read the link, you just want the equivalent as a builtin unity thing. I don`t know of any either
How do I go about diagnosing a segmentation fault?
Sounds like a big to me at first.
What exactly is the error?
it could definitely be a bug
Also where do you get it, platform etc
Basically, I load a scene (editor play mode win10), and then it sometimes crashes and gives me a seg fault. Looking down the stack, it appears to originate in a UIElements call, and then somehow ends with URP rendering shadows. It happens after Start(), I think. I don't believe I am loading any UIElements on scene load, since afaik they are in a dontdestroyonload() so they dont get instantiated again
i havent been able to glean a whole lot of info from it other than that since it doesnt provide line numbers and a lot appears to be native
Try to google for that issue about segmentation fault, there are some fixes like disable some GPU checkbox and so on, test that and see if it works. I guess its a bug in the version you are using unless you are doing something special/fancy on your side
ive googled a lot but "segmentation fault unity" is very generic and "unity urp seg fault" doesnt do a whole lot
what about those fixes? https://forum.unity.com/threads/segmentation-fault-core-dumped-in-standalone-app-but-not-in-editor.1226610/
Even if he is talking bout linux, might be worth a shot
didnt work, unfortunately. Havent tested a build. I wonder if regenerating temps would help?
the top of the trace looks like this: ```
Received signal SIGSEGV
Obtained 67 stack frames
0x00007ff75e24c052 (Unity) PrepareDrawShadowsCommandStep1
0x00007ff75e2433f7 (Unity) ScriptableRenderContext::ExecuteScriptableRenderLoop
0x00007ff75d79cd89 (Unity) ScriptableRenderContext_CUSTOM_Submit_Internal_Injected
it's a very generic error and could basically be anything unfortunately, sounds increasingly like a Unity bug if it's happening in internal code with no obvious reason
Maybe just update to a newer version and see if it persists
Maybe. I’m on the latest stable release of 2022, I did update in hopes that would get rid of the bug
Ehhh, it's fine. If anybody ever finds a better way I would love to know. For now I made a property drawer.
Runtime.ObserveChangeAttribute
#nullable enable
public class ObserveChangeAttribute : PropertyAttribute
{
private readonly string _method;
public string Method => this._method;
public ObserveChangeAttribute(string method)
{
this._method = method;
}
}
Editor.ObserveChangeAttributePropertyDrawer
[CustomPropertyDrawer(typeof(ObserveChangeAttribute))]
public class ObserveChangeAttributePropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(position, property, new GUIContent(property.displayName));
if (!EditorGUI.EndChangeCheck() || !Application.isPlaying)
{
return;
}
var observeChangeAttribute = (base.attribute as ObserveChangeAttribute)!;
var method = property
.serializedObject
.targetObject
.GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x =>
x.Name.ToLower() == observeChangeAttribute.Method.ToLower() &&
x.GetParameters().Count() == 0)
.FirstOrDefault();
if (method == null)
{
var fieldName = base.fieldInfo.Name;
throw new Exception($"Method \"{observeChangeAttribute.Method}\" not found whilst invoking change on \"{fieldName}\".");
}
method.Invoke(property.serializedObject.targetObject, null);
}
}
Reproduction steps: 1. Open the user's attached project 2. Open Scene 'Assets/xddxxx' 3. Open 'Window -> Rendering -> Occlusio...
Wow. Thank you, I’ll try that. Google didn’t show me that one.
Ha, I like that actually, will test that out later 🙂
Occlusion culling …
Its just a bug report, not sure it helps you but just watned to tell you, they seem to be aware of it
Bug in the Unity issue is current. In production, it happens multiple time. The way to fix/diagnose is to remove everything till you do not have the error.
I would not go there, but you could do IL weaving which basically modify the source code after the code as been compiled. This way, you modify the way C# works and add your own "definition". https://github.com/ByronMayne/Weaver
i dont even know where to start removing
Load an empty scene.
I understand. I hoped there was a better way that does not involve source generation
Gotta say, this is quite a bit of work for such a small thing 🙃
Why is this not a good solution, by the way?
Because it creates magic, thus it is hard to maintain because it forces other user to learn a "new language" and can behave in unpredictable way. It is always why you should keep reflection low and be sure that it is explicit.
tfw your project is too big to send in the bug report
Also, I do not how well it is implemented and integrated in thing like console or mobile build nor how well it fares with debug tools.
Report project needs to isolate the issue.
Hi, this may be a niche question, but we're using NuGet for some packages (IE BouncyCastle for cryptography). We also have some external packages we use for all our projects. Is there a way to add a NuGet dependency to a certain unity package?
basically no, Unity does not recognise NuGet
Hm, I figured, thats unfortunate
what you can do is use NuGet in an external solution, compile to dll and then copy those dll's to a Unity Assets/Plugins folder
Currently we're just including the Bouncycastle DLL in the package, but was hoping for something a bit more elegant
you can cheat, create a new solution which includes the Unity csproj files, then you can add NuGet packages to the solution without being impacted by unitys sln/csproj system
luckily MS VS sln and csproj files are not too difficult to understand and modify
how is that a small script
my brain doesnt even understand what that is
but complicated
I want to write my grid data to output to a file. (1,2,3,etc being an object placed[ID] in game, 0 empty) so its a "readable-writable" format, file that i can call/load in another scene.
[0,0,0,0,0]
[0,0,1,0,0]
[1,1,1,1,1]
(Gonna put my code in a thread, to save space)
hey, I'm on my first approach of unirx https://github.com/neuecc/UniRx
I want an observer that execute code when a collider becames enabled = false. so I can call the OnTriggerExit that wouldn't be called normally
I added that code inside Awake
but it gets executed only if the entire object became disabled
That description in the documentation is a bit suspicious. Colliders are notoriously not Behaviours and have their own separately defined enabled property.
I wonder if that's related.
so, if instead of collider I would use a custom monobehaviour and it works than it's collider fault?
it doesn't work either with monobehaviours
how is that coding advanced? #archived-urp
oh
i just opened this server and the first visible chat was that
sorry btw
i didnt even notice lol
yeah take some time reading #854851968446365696 for script and #📖┃code-of-conduct about the servers rules
it isn't related. the OnDisableAsObservable add a new component to the gameobject and listen for this component OnDisable. so there is no way it will fire for the disable of a specific component.
im writing a compute shader, where can i see the output of the "printf" statement from inside the shader?
it doenst appear in the unity console
you can't. It runs on the GPU.
you have to use RenderDoc or something
there's no eventful way to listen to a collider's change in enabled status. you can check every frame, or you can modify the code that disables colliders to disable a different monobehavior instead. that script will be responsible for the collider
I tend to use color outputs and other things to creatively debug my compute shaders.
for nvidia cuda you can tho and the HLSL docu says it goes into the general information queue
EDIT: docu also says the command doesnt do anything on machines that dont support it 🤡
thanks, altough i cant figure out how to actually step through my shader, renderdoc looks promising 👍
shame that print doesnt work.
i guess you're learning the most important lesson of all then
🥳
What are the possibilities (and limitations) of having it so Unity can read from external C# files and include them?
Trying to figure out how this could work with my desire to add easy modding support.
Wouldn't be surprised if that isn't possible (or safe) though and it demands my own scripting language and interpreter.
Exposing an interpreted scripting language to mods/plugins is the reasonable approach which allows you to control exactly what the mod-code has access to. It’s also a much more painfree experience overall.
Thoughts on Lua to this end then?
I've noticed MoonSharp is a library for exactly such purposes.
It works well for many projects
Depending on what type of scripting you need, a lisp might be a good option (where code and data are the same)
Hmm, I'll take a look-see
Are you trying to provide modding support for the general public, or is it something you expect only few people will be modding?
General public, which I'm aware will indeed mean a lot of work, but for a text adventure game (to which I've essentially went through the effort to make an engine for by hand) I figure it'll be useful to both me and others
If it’s the former, you should consider a language that’s well known and popular.
Lua seems like my bet then
I can tightly control the scripting environment as well and not expose a buncha shit from my bajillion C# scripts
Most languages that are suitable for scripting have libraries for embedding, you can consider things like Python too.
To my assumption, of course
Lua historical has been the scripting language of choice because it’s extremely close to just plain C code, and the runtime is tiny, both advantages are pretty insignificant nowadays.
I know, it might not be what you are looking for, but if you target specified people to extends your engine. Knows that there is tool available that requires nothing from the developer. https://github.com/BepInEx/BepInEx
I am in the development of a 2d top down environment. I am using netcode for multiplayer, which will only be for a few people. I have setup a network manager and added my prefab as a network prefab. My prefab has a network object component attached to it.
I have setup buttons, so that when I build and run the game I can choose between a server, host and client. I have the host on the main environment and the client on the new window that pops up.
My issue is that when my object spawns on the server side, it does not spawn on the client side as well.
My code looks like this.
Can someone help me?
If you are trying to appeal to novice programmers to mod your game, Lua isn’t exactly a popular language in comparison to things like Python JS etc. But if you expect people who mod your game to be seasoned programmers, this is then irrelevant, I’m sure they can learn whatever scripting language quickly.
In the end it boils down to what audience you are targeting.
As I think on it, python miiight just be the better choice
It's a nicer language on novices and I expect most people wanting to mod for my game are going to be novices
Lua might turn em away
very pleased with my pointcloud 👍
In theory is it possible to use Equipment from one humanoid model into another? is there a way to transfer the rig?
Elaborate on "transfer the rig".
i saw this
transfer the rig mean use equipment from vendor A character on vendor B character
Both humanoids but different armature
Use a skinned mesh for the equipment. Reassign the bones of the skinned mesh. You must use a script to reassign the bones as they are not visible in the inspector.
so im trying to serialize a custom class on with a monobehaviour field in it in a script that will be saved as a prefab, but since i have to use serializereference to serialize the custom class (the classes inherit from a base class so they cant be serialized normally) when i place the prefab in the scene the references still reference the monobehaviours in the prefab instead of the instantiated object. is there anything i can do about this
Is it just this? in theory is it possible to do it on a click of a button?
if bone are humanoids?
Neck is named neck_03_04 on armature 1 but neck_tst on armature 2
can i mix and match? do humanoids have this info
from armature bone to humanoid bone then go back from humanoid bone to the other armature bone
Yeah, with an editor script. You need to copy the bones from the original SkinnedMesh to the SkinnedMesh with your equipment. That being said, you might want to do it in runtime because otherwise you will need to have your equipment in the same hierarchy as your player.
https://docs.unity3d.com/ScriptReference/SkinnedMeshRenderer-bones.html
Personally, I have a script that hold reference to all the bones of my SkinnedMesh (Skeleton) on the player and an other script on my equipment (Rig Binder) which hold the name of the bones that should be use with the SkinnedMesh of the equipment. Whenever the equipment is instantiate, the Rig Binder binds on the Skeleton of the owner of the equipment.
I have a script for this too but what i`m trying to do is to transfer from different rigs, so they have different bones names ;x
Can Someone help me with my script here? I'm trying to load all Correct answers and user name from firestore and use it to make a leaderboard in unity
**UPDATED WITH METHODS AT THE BOOTOM ( COMMENTS TELL WHAT DEBUGS GET TRIGGERED)
https://pastebin.com/qaK9PLDj
Please any help to get this working would be greatly appreciated
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Does it mean that other debugs are not printing?
correct
I'm getting Task.IsFaulted in the last method
public void GetLeaderboard(Action<List<LeaderboardUser>> callback)
{
fireStore.Collection("Users").GetSnapshotAsync().ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log("Error getting documents");
Debug.Log($"Error getting documents: {task.IsFaulted} : {task.IsCanceled}"); ///ADDED THIS
return;
}
foreach (DocumentSnapshot doc in task.Result.Documents)
{
SaveData data = doc.ConvertTo<SaveData>();
users.Add(new LeaderboardUser { userName = data.User, correctAnswers = data.CorrectAnswers });
}
users.Sort((u1, u2) => u2.correctAnswers.CompareTo(u1.correctAnswers));
callback(users);
});
}
Does task have an error code property or something?
Or do you get any additional firestore errors/logs in the console?
What type is task?
You have 2 errors and some warnings hidden. Maybe they're relevant?
Plugins like that usually have some logs that they print on their own reporting the status of operations.
no those are for my notifications and current leaderboard situation (Using DreamLo Leaderboards)
Ok, then what type does the task have?
where do I look for that?
Oh Looks Like I'm trying to get the data in collection Users
Is that not what you wanted to do?
Anyways, I suggest setting the firebase logging level to verbose and looking at the console.
I have a shoot em up game that looks like this, the player is the green ship and in this case the right ship is a boss, what would be the best way to make him dodge my shots?
You probably want to predict the path of the projectile than move according to the prediction.
Something like:
If center of the boss is to the right of the predicted path then go left
If center of the boss is to the left of the path then go right
To know if it is to the right or to the left, use the cross product between (Projectile,Direction) and (Projectile, Center of Boss)
already did something like that but since the player can have high attackspeed (multiple bullets flying towards the enemy) i dont really know how to account for all of them
Use a weighted sum base on how close the bullets are from hitting the ship.
The side that has the maximum value is the side that should be choose
left <= 0
right <= 0
For every Bullets
weight <= How close the bullet is from hitting the ship
If center of the boss is to the right of the predicted path then add to the left value
If center of the boss is to the left of the path then add to the right value
Move according to the max of left and right
Finding the correct weight function would be the way to fine tune the behaviour.
ok thanks ill try it out and let you know how it goes
Man, finding the best way to develop a prototype-based method to create entities in my game, like actors, is very tricky
Previously protected properties and methods can't be protected anymore if the prototype clone needs functions granted to it
tried this I put together from the docs and It only get the first debug
public async void GetAllDocsInCollectionAsync()
{
Debug.Log($"Getting All Docs In Users");
Query allCitiesQuery = fireStore.Collection("Users");
QuerySnapshot allCitiesQuerySnapshot = await allCitiesQuery.GetSnapshotAsync();
foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents)
{
Debug.Log($"Document data for document: {documentSnapshot.Id}");
Dictionary<string, object> city = documentSnapshot.ToDictionary();
foreach (KeyValuePair<string, object> pair in city)
{
Debug.Log($"All Data: {pair.Key} , {pair.Value}");
}
Debug.Log("");
}
}
docs example
Query allCitiesQuery = db.Collection("cities");
QuerySnapshot allCitiesQuerySnapshot = await allCitiesQuery.GetSnapshotAsync();
foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents)
{
Console.WriteLine("Document data for {0} document:", documentSnapshot.Id);
Dictionary<string, object> city = documentSnapshot.ToDictionary();
foreach (KeyValuePair<string, object> pair in city)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
Console.WriteLine("");
}
Try debugging the query snapshot count before the for loop.
@dusty wigeon works surprisingly good, thanks 🙂
I added Debug.Log($"QuerySnapshot: {allCitiesQuerySnapshot}"); before the fir foreach loop and got nothing
Nothing like null?
like didnt print anything to console
Where did you add it? Share the updated code.
If you placed it where I think you did and it didn't print, then there was probably an error thrown before that.
public async void GetAllDocsInCollectionAsync()
{
Debug.Log($"Getting All Docs In Users");
Query allCitiesQuery = fireStore.Collection("Users");
QuerySnapshot allCitiesQuerySnapshot = await allCitiesQuery.GetSnapshotAsync();
-----> Debug.Log($"QuerySnapshot: {allCitiesQuerySnapshot}");
foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents)
{
Debug.Log($"Document data for document: {documentSnapshot.Id}");
Dictionary<string, object> city = documentSnapshot.ToDictionary();
foreach (KeyValuePair<string, object> pair in city)
{
Debug.Log($"All Data: {pair.Key} , {pair.Value}");
}
}
}
So yeah, there's probably an error thrown before/during the log. That's why you shouldn't hide your errors...
maybe I should just move this data to Realtime Database , there tuts on making a leaderboard with firebase
Realtime database? No clue what you're referring to, but I guess that means that we can consider the issue solved?
I'm trying to get all docs in collection Users , get username and correct answers from al and sort most to least
lmao no , I mean Firebse realtime database , Im using firebase firestore
I'll search unity assets and see if I can buy soemthing
I don't have much experience with firebase, but your issue should be fixable by simply debugging it properly.🤷♂️
Hello there, recently I found out that unity asset importer crashes when importing Texture2D (2D sprite format) with over 8000 sprite slices, I am wondering what's the upper limit for the slices a texutre 2d can have.
public async void GetAllDocsInCollectionAsync()
{
Debug.Log($"Getting All Docs In Users");
Query allUsers = fireStore.Collection("Users");
Debug.Log($"Query: {allUsers}");
QuerySnapshot allUsersQuerySnapshot = await allUsers.GetSnapshotAsync();
-----> Debug.Log($"QuerySnapshot: {allUsersQuerySnapshot}");
foreach (DocumentSnapshot documentSnapshot in allUsersQuerySnapshot.Documents)
{
Debug.Log($"Document data for document: {documentSnapshot.Id}");
Dictionary<string, object> user = documentSnapshot.ToDictionary();
foreach (KeyValuePair<string, object> pair in user)
{
Debug.Log($"All Data: {pair.Key} , {pair.Value}");
}
}
}
@untold moth the above debug give this error
look at lowest blue highlight mentions line 206
can someone help me test an in-browser multiplayer feature in your browser?
it's telling you what the error is. you have to give the user permission to modify documents / fields in firebase
if you never logged in (seems likely) you are probably trying to write as an anonymous user
also async/await doesn't really work prior to unity 2023.1.0a14
I log in with facebook
Do you know a lot about firebase?
i know that you have to give a user, role or group permissions to read, write or modify documents
in this case it looks like you're reading
the error seems unambiguous
if you believe you've set up the permissions correctly, it's highly likely you are not actually logged in at the moment you make this call.
because of the way you are using tasks, and the other 3 errors it's printing in there, you probably are not correctly waiting for auth to complete
I'm trying to get all docs in a collection , sort these docs by number of correct answers and get user name and correct answers ... Making a leaderboard with firestore instead of Realtime database
this looks nice. do you have any video?
okay. what do you think "Missing or insufficient permissions" means?
did you use chatgpt to author any of this code or other code in your project, by the way?
lmao , tried that once but no I made it from firebase docs page
so what do you think the error means
Why do you keep on ignoring our questions?
You ignored me mentioning errors before too😅
Its beacuse my rules are set to only read write by user facebook email only ,,, my rule for players to read , write thier own doc and no other
The error is clear, either your firebase setup is wrong or you don't authorize properly. You should check your setup on the firebase side first and if there's no problem there, look into where you authenticate.
not ignoring , looking for info as I'm tryint to learn and not just get the answer
okay, well like i said
you may have set the permissions ocrrectly
but at the moment you call this function you may not have finished logging in
so 50% chance you did not set permissions correctly anyway (you probably did not use the right subject or principal or similar) and 40% chance you are not logging in before you make this call, even though it appears that you are
10% chance everything else
Yeah it's because My rules don't allow reading others users data and that what its trying to do
gotta go!
I'll make a work around , I know how I'll do it
thank you
Hi everyone, I posted this in the editor extension chat last but I didn't get a response so I'm thinking I may have posted in the wrong chat.
My aim is to create an asset that lets you create rail systems, however the way I want to go about this is by playing a manager component on a mono-behaviour and then having that create the rails. The thing I would like help with is this:
I want to be able to give the user the ability to define points in world space and move them around, like a game object, without the need to actually create many game objects for this purpose. I would also like to have it work as something that sits on top / interacts separately to the main scene, kind of like how editing prefabs directly within a scene lets you grey out and show the scene they sit in.
The implementation that I want is for a component to have a button that will "enable edit mode" which will then take the user out of the main scene editing and into the "prefab mode" kind of thing, where they will be able to create and drag positions around. With potentially gizmo's rendering on top.
Does anyone have an idea on how something like this overlayed scene and interacting with positions and such without the need for actual game objects would be done? (Just to explain why I want to do this in the first place, I would like to make something that is contained and causes minimal changes to the actual game scene)
How do you want to get the points? Using mouse clicks? I would then consider using a large collider potentially along the x/z axis and grabbing the point via ray cast then adding them to a list. You can probably then use some spline tool to drag them around perhaps. Not too sure about the prefab editing "scene", which is something I'd like to look into myself when I get back to developing my tool.
yes you can create a single doc that is the leaderboard
and give permissions to modify keys that are prefixed with the userId / subject / principal (whatever they call it)
you can also use an aggregation / trigger / whatever they call it
a cloud function can be called every time a user's score is inserted
and then that cloud function updates the read only leaderboard doc
hey I have a question
I want to call some native functions from C standard library
dll named msvcrt
functions like file and memset and fread and etc
but i dont know if it would work inside unity and on build for android
pls clarify me?
you want to look for Native Plugins in C and C++ if you want to use that and also see, what plugins are available or write your own for whatever you need. But file for example is already there in system.File
Functions that are implemented in unmanaged dll can be called from managed code just fine "As long as you know what you're doing"
whether it would work on said platforms, that's another story ☕
Also don't learn about this stuff on pinvoke.net ... many misleading stuffs there
How to observe value change of custom class or single float using unirx?
As has been said, you can call native functions from a dll in C#. I'm just curious as to why you'd want to call standard API like that, that exist in C# already.
It's like you create a remote car controller just to use it while sitting in your car's driver seat, instead of driving using the actual car controls. It's inefficient and meaningless.
read the docs? I hate unirx due to it comes with a massive bloats
Either way easy to make your own..
//usage var i = new VListener<SomeType>();
// i.value += () => { Debug.Log("changed!"); };
public class VListener<T>
{
private T _value;
public Action value;
public T Value
{
get => _value;
set
{
if (!EqualityComparer<T>.Default.Equals(_value, value))
{
_value = value;
OnValueChanged();
}
}
}
protected virtual void OnValueChanged() => value?.Invoke();
}
I already did with custom callback, but then I found unirx, and from readings it is very impactful for other programmers. So I would give a try instead of reinventing the wheel.
this is my own:
[Serializable][HideLabel]
public class CallbackValue<T>
{
// così tanto zucchero da farti diventare diabetico
public static implicit operator T(CallbackValue<T> instance) => instance.Value;
public Action<T> onChanged;
public CallbackValue()
{
}
public CallbackValue(T cachedValue)
{
this.cachedValue = cachedValue;
}
public T Value
{
get => cachedValue;
set
{
if (cachedValue != null && cachedValue.Equals(value))
return;
cachedValue = value;
onChanged?.Invoke(cachedValue);
}
}
public void ForceSet(T value)
{
cachedValue = value;
onChanged?.Invoke(cachedValue);
}
public void SetNoCallback(T value)
{
cachedValue = value;
}
[SerializeField][LabelText("@$property.Parent.NiceName")] private T cachedValue = default;
}
yours can go south pretty easily, but it's fine bcos you're not going to use it anyway 🔥
you need a proper check there
Also the serialize thingy wont work due to System.Action, should use Unity's ones if you're planning to do so
mmm.. it is actually working
aight, carry on!
Can I ask here how to build a unity project on cloud through AWS CodeBuild?
did you manage to find help for this?
@undone coral yes, just a short video which was poorly made but should give a first impression will be making a new one soon
https://www.youtube.com/watch?v=lHrj_J3iSkc&ab_channel=Astralis
First Trailer to my game!
Play now at: https://unluckygames.itch.io/astralis
Hi there. I'm working on a chess game, where I have a level editor. Here is a video of a problem I've encountered with move generation.
My code generation is pasted here: https://hastebin.skyra.pw/emetagamut.csharp
To explain about the issue, I am trying to make the selected piece (a bishop) only move in diagonal lines.
We can see though, that when selected some squares are also validated that should not be.
I have verified that this validation error comes from the code listed above, so my mistake is most definitely there.
wrapping your link in an inline code block prevents discord from generating a hyperlink
Probably some formulated thing, but at max the bishop only has two move per row it seems
your south east and south west directions are flipped, and in general you're not handling wrapping at edges properly - e.g your South West code for the Bishop on 25 is actually checking square 19, 13, 7, and 1
@obsidian glade It is not supposed to wrap.
Yes, but it's all dynamic because it's a level editor based board.
exactly - but your code does
It makes it a little harder, because all available information on chess is based on an 8x8 grid.
@obsidian gladeI see. I don't understand how, though.
is there any reason why would unity give me all black no matter what i change the color in the material ?
Dave you actually placed any tiles?
yes all those are tiles
and what does the sprite for those tiles look like?
is it black?
no sprite just color
wdym
What kind of thing are we looking at
is this a TileMap?
A SpriteRenderer?
MeshRenderer?
game object "quad" with a material on it to change colors from
and it is rotated correctly
and... a renderer of some kind surely
MeshRenderer?
yea mesh rend
Any lights in the scene?
This doesn't seem like a code issue btw more like #archived-lighting
but I'd guess you simply don't have lights
yes the normal directional light
or no lights hitting the object
from which direction
perp on it
Well, like I said there's probably some alg for it, being row-major or column related, which is probably somewhere out there on google. But, you could always do the lazy way and pattern match/check and in this case I found:
Bishop can make moves in 8 or 6 steps through the matrix indices on a 7x6 board, so if your bishop is on index 25 -> [3][4], then it would decrement to:
6 steps -> [2][5], [1][6], [1][1]```
As we can see, using 6 steps our `i` does not decrement at one of the steps, and our `j` wraps around here.
ok when i disable the light it change nothing
so this is the issue ig ?
what happens when you switch to an unlit shader
it works ty
so it's definitely just a lighting issue 😉
Anyone here familiar with Zenject?
I am trying to write an automated test for a class that instantiates different prefabs that are passed by a parameter, but I'm getting Assert hit! Error occurred while instantiating object of type 'Placeable'. Instantiator should not be used to create new mono behaviours. Must use InstantiatePrefabForComponent, InstantiatePrefab, or InstantiateComponent.
It's weird because my CustomFactory is already using InstantiatePrefabForComponent?
@regal lavaThank you
unirx reactiveproperty. how to fire the observable subscription without change its value?
looks really good
i can test now
4 player
if someone wants to try a new multiplayer framework click that link and join in tested
thanks!
Hi there
I would like to ask for a suggestion
I am working on a stabilizer system for my ship that moves along a track, I already implemented a PID to keep the ship hovering over a distance between the ship and the trak and also implemented a PID to keep the ship aligned to the normal vector uf the face below it by casting a ray
What I can't figure out however is how to keep the ship in track since there are no fences or bolliders on the sides of the track
So I was thinking about a system that pushes the ship to the center of the track based on some raycasts
But I don't know how efficien that would be
take a look at this https://twitter.com/KenneyNL/status/1107783904784715788?lang=en
How the arcade-like car controller was made; big sphere rolling around, car model just copies position. Raycast down to find ground normal for car. Sphere gets force based on car model direction. Tilt/wheel turning/etc. all lerps. #gamedev #unitytips
4057
710
you can attach something to the track and have it roll around on its surface
then attach a spring to that thing and your ship
this would also obsolete your PID... but i think you are discovering the limitations of trying to do something that isn't really physical (a hovercar track) using physics
Yeah, damn limitations
Thank you so much for this advice
I don't know who the ball will behave moving at 800km/h and at 3000km/h
If I set up an accelerator on a server in the internet, are anyone able to access it and read my assets? I want one for my build servers but it's kinda irking me that it's accessible without an username and password
if it's single player / single vehicle, you can use a non-inertial frame of reference, and move the physics world along the track
I am aiming for mp with AI CPU
Hello there
I was told that using AddRelativeTorque in FixedUpdate is not the best practice, but this code works:
private void Stabilize()
{
Vector3 headingError = Vector3.Cross(Vector3.up, transform.InverseTransformDirection(hit.normal));
Vector3 headingCorrection = stabilityPID.Update(headingError, Time.fixedDeltaTime);
Vector3 torque = (headingCorrection * 3000f) * stabilityMultiplier;
rb.AddRelativeTorque(torque, ForceMode.Force);
}
Then I decided to just use AddTorque and came out with this code:
private void Stabilize()
{
Vector3 headingError = Vector3.Cross(transform.up, hit.normal);
Vector3 headingCorrection = stabilityPID.Update(headingError, Time.fixedDeltaTime);
Vector3 torque = (headingCorrection * 3000f) * stabilityMultiplier;
rb.AddTorque(torque, ForceMode.Force);
}
The problem with the second code is that the ship at some point start to slowly rotate to the left
and I don't know why
This is the PID class
using UnityEngine;
[System.Serializable]
public class Vector3PID
{
public float pFactor, iFactor, dFactor;
private Vector3 integral;
private Vector3 lastError;
public Vector3PID(float pFactor, float iFactor, float dFactor)
{
this.pFactor = pFactor;
this.iFactor = iFactor;
this.dFactor = dFactor;
}
public Vector3 Update(Vector3 currentError, float timeFrame)
{
integral += currentError * timeFrame;
var deriv = (currentError - lastError) / timeFrame;
lastError = currentError;
return currentError * pFactor
+ integral * iFactor
+ deriv * dFactor;
}
}
never mind, found my answer, Its not anymore 🙂
I was told that using AddRelativeTorque in FixedUpdate is not the best practice
Huh?
Why would that be bad practice
I was told that
its physx and it belongs in FixedUpdate
if you call your above method in normal update, it gets executed based on framerate, which leads to unwanted behaviour. maybe thats where your issue comes form
Probably, I alwayys call those functions from FixedUpdate
But I can't understand why ot works fine one way and not the other way because in theory it's the same
Is there a channel here to hire people?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
If anyone is familair with Zenject then I would love some help on this issue:
https://stackoverflow.com/questions/75739664/instantation-error-when-unit-testing-prefab-factories-in-zenject
You know zenject is dead and replaced with Extenject right? https://github.com/Mathijs-Bakker/Extenject
They have a gitter you can ask in
There was a whole drama where the author of zenject lost the rights to maintain zenject after leaving his employer, Modest Tree, you can read about it in a blog post somewhere
Anyway, I'd def wanna be on latest extenject before looking for fixes for what may be a bug
Then you can ask their gitter for support.
All these projects look dead actually.
Does anyone know how to debug these? Getting spammed in editor, but none of our code is using jobs/native arrays so it's presumably coming from a plugin.
I guess it tells me how to debug here. Does that mean to launch the unity editor with a flag?
Ah, I see! nvm. I can add CLI args in unity hub
How do you install this
Trying to do it as stated in the manual doesn't work
Says there is no package with that name
Hi @novel plinth,
after 2 days of unirx I found more bugs than help, and this are bugs reported in the git issue from years... with even a proposed solution that haven't been implemented. (just an example: https://github.com/neuecc/UniRx/issues/314).
I'm sad because I like the rx approach.
You are totally right in hating unirx.
I didn't explore the microcoroutine part... It seems super cool, but if it has the same problems of the rest it isn't even worth a try
UniRx isn't being maintained anymore by the creator
the creator made a new account tied to his new company called CySharp
the same dude who created UniTask and MagicOnion
you don't need to, you can get the same behavior with async/await + customYield in Unity
which essentially what UniTask does unde the hood
what you mean with customYield?
oh, it's a way to implement yield return similar to waitwhile and waituntil
this seems so weird to me 😛 First using just IEnumerable and not IEnumerable<T>, second, this seems like it's a constantly running thing and not like a normal yield return for an iteration
is this just a recursion technique?
This is actually an IEnumerator, which is what IEnumerables would call to enumerate. Unity enumerates this using its build in system when you call StartCoroutine, and since these don't return anything there is not really a reason to use the generic variant.
Pretty sure it's all part of base c# and you could add a custom enumerator yourself
And I don't think it's recursive. I assume Unity has a build in state system that checks each frame if the predicate defined in those yield instructions have passed, and it will then call MoveNext() on it.
it just seemed like it yield returns a new instantiation of itself
No, just that yield instruction. I'm not sure why you would create a new instance constantly. I think you can just make a single instance and reuse that, unless there is more behaviour to it
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/WaitForSeconds.cs I don't think there is much to it
So you can probably actually just reuse the same instance
the example i looked at . . i didnt notice the different case
public IEnumerator waitForMouseDown()
{
yield return new WaitForMouseDown();
Debug.Log("Right mouse button pressed");
}```
its just calling this:
public class WaitForMouseDown : CustomYieldInstruction
{
public override bool keepWaiting
{
get
{
return !Input.GetMouseButtonDown(1);
}
}
public WaitForMouseDown()
{
Debug.Log("Waiting for Mouse right button down");
}
}
Different case to what?
case sensitivity... wait vs Wait
They're two completely different things though
Top one is the actual "Coroutine", whilst the bottom one is a yield instruction that can be used within
The Coroutine should also be capitalized but I'm guessing that wasn't done to avoid a conflict in shitty naming
You can FYI
But WaitForSeconds has explicit handling within the coroutine runner: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/WaitForSeconds.cs
if i want to make an easily moddable game / one that encourages modding, should i just use mono or make a custom modding framework and have my game il2cpp
How can I get a count of all docs in Realtime database?
I haven't used firebase specifically for Unity, but AFAIR, their docs were pretty good. I'm sure you can do something like this.
https://firebase.google.com/docs/firestore/query-data/aggregation-queries#:~:text=count() allows you to,to executing the full query.
This is for firestore but I imagine there is an rtdb equivalent
at this stage use unitask
once you are writing custom yield instructions, you can use the better authored ideas in unitask / unirx and the utilities there
it is also hard to represent UX imperatively at this low level
you are also using old input system which will make this much harder
that issue* (there is no bug) is a guy who doesn't know what he's doing
i suppose you can join him... it sounds like you want to trigger things when components enable and disable
we discussed this
it's a code smell
no, he wanted to dispose when the script gets disabled, like the description of AddTo say. but it dispose when the gameobject gets disabled
it doesn't do either of those things
he wanted to dispose when the script gets disabled
that is a code smell
if he wants to do something when a component is OnDisable he can put it in that callback
AddTo does what it says it does
"blissfully unaware" indeed
no offense to that ticketer
if you want a helper for OnEnabledStatusChangeAsObservable, author it
it cannot be authored in an evented way for a target component. we discussed this. it has to check every frame
it should be obvious why - you can only do it in an evented way by writing something in OnEnable and OnDisable, which you can't peak into from another component
BUT it's a code smell
@glacial wedge do you see what i am saying?
i'm reading...
or i suppose you can throw your arms up and you know, use Built in Render Pipeline and Amplify Shader Editor
just think it through. how would you implement this callback without using every frame?
DisposeWhenComponentDisabled(Behaviour targetComponent) or DisposeWhenComponentDestroyed(Component targetComponent)
how can a script "add something" to another script's OnDisable or OnDestroy, if the script is a black box?
it can't
no, it can't ofcourse
it can only check every frame. but that should be telling you it's a code smell
a game object is a container, not a component
the association between components is a game object
that's what the unity architecture is
if you want to destroy things together, you know, you put them on the same game object and destroy the game object
it doesn't make sense to dynamically add and remove components most of the time (that is a little code smell), and it really doesn't make sense to "add behavior" at runtime that needs to be coupled to the lifetime of a specific other component on the game object. those things are just tightly coupled together
anyway
it's your prerogative
this is the worst example of an issue with unirx
it's not a tool for people to write smelly blub code
I'd prefer not to deal with adding/removing trigger components. They take up space in the inspector and their full behavior is inherent in the code we have to write to call them
i mean listen to this guy
the thing that guy is doing makes so little sense
if you have a real bug you should ticket it
add "com.unity.charactercontroller": "1.0.0-exp.2" to your Packages/manifest.json file
also, this is a DOTS package
it is still a dead repo
you gotta get out of this blub coder dead repo mindset now
this isn't web development
that heuristic doesn't apply
it's your prerogative
you are so close to ascending. you said it yourself, you like this
You're Not In Web Development Anymore
i have been using unirx for years, and i have written exactly two extensions (Window and tweaks to Throttle) + fleshed out the reactive collections. i have not yet encountered a bug
you can even see the issues i did ticket
okay, i also authored the unitywebrequest extensions which he merged
that's it
yeah, it's a bad mentality but when the documentation is misleading and there is no support from years become an insecure way to proceed. It could give me to unundestandable bugs
It say behaviour and seems attached to this component when in reality it happen on gameobject
you are right on black box..
you can't use this to blub code
elsewhere in the docs for observableenabletrigger it's clear that it means the gameobject
and Component doesn't have enabled
only Behaviour does
it sounds like you had this one issue
i wouldn't let it get you down
i am saying this docs issue is real
i agree with you
but if docs are getting you down
why are you using unity lol
have you seen the unity docs
I had another bug about the OnEnable, the callback was called only if the gameobject were disabled and reenabled.... I didn't lost too much time on it because ofcourse the callback was set after the first onenable caused by the random execution order of awake
OnEnable and OnDisable was a mistake
wdym? unity docs are great 😮
my first exp was with Lumberyard... switching to Unity was a blessing lol
It's not terrible, but I also wouldn't call it great either.
Is there a way to strip a class of its functionality to use it as a buffer for its variables? I have a system where I want to enable the configuration of multiple instances of different classes, but I don't want to have to pass down tons of duplicate variable names.
Like for example I have a wheel class, this class has a Build() method that creates gameobjects and adds components in the scene using its own variables, and a Mount() method which configures those newly created things. The problem is that some values are shared while others are not, so I feel like I would be weighing the system down by creating a full dummy object to hold my values.
public class Sample
{
// stuff here
}
huh
Container class
A class whose only purpose is to store data. Does not inherit from anything, does not implement interfaces. Can't get more barebones than that
is there a convention for naming these?
I guess if I nest them in the class theyre for I can name them all the same thing
alright, thanks
If you plan on using that class outside of the one it's nested in, it should be in its own file
Conventions? So you don't have to type the full name all the time
well it needs to be different for each object
Will it be used outside of said object?
well ill be using it from the config, then ill pass it down back to the object during assembly
From the config? Assembly?
I have a class that's job is to allow for the configuration of various entities, it then carries out the task of creating those entities using the instructions I provide
In my current situation its for a car
so I need stuff like wheel radius, depth, etc, and all the car dimensions so It knows where to put them and how to configure the components attached
currently all those public variables are separately declared from the objects they represent
which is causing me a lot of running around
but yeah ill try this container class thing
You can mark the container class with a [Serializable] attribute so it shows in the main script's Inspector. You'll be able to collapse it, which will free some space
Pretty much what happens with the Suspension field here
is there a way for me to force implementation of a nested class via inheritance or interface?
No
What I consider great would be that docs can serve as primary material and cover vast majority of what you need, including not just basic usage but higher level things like architectural, best practices, and even trouble shooting common questions, to the point where you mostly don't need to go to third party sites bar very advanced things.
Off top of my head, Vue and Svelte's are both done very well, and as you mentioned, Microsoft's C# docs are excellent (albeit somewhat disorganized). Unity fails at this, it's very much a documentation with one flimsy example if there even is one; often you have to resort to Googling to obtain most of the information. This is not a dig at Unity specifically, most things don't have docs to that level, and not everything is great. If everything was great, that's just the average.
If everything was great, that's just the average.
Yeah that's where I was going 😄 My general exp with documentations makes me feel Unity docs are great. Haven't checked Vue or Svelte's tho tbf, but hadn't had too many complaints from Unity's docs
Unity's docs are far from the worst, well besides content wise, most of my complains about Unity's docs are simply the website itself being very poor.
Searching on Unity's docs site is so bad and slow that using Google to search is faster; except Unity's docs also don't index well on Google, especially that you have to change Unity version with every link you click.
And most of the time when you change versions, it puts you back to the homepage
I think they improved that recently in the newer versions
thankfully that's fixed yeah 😆
Some pages are also practically unusable, eg math class in Unity.Mathematics with all the methods and overloads, that page (at least last time I checked it) would take a ridiculous long time to load and prone to crashing, as well as near impossible to navigate.
oh yeah the 'new' docs 
'oh u a math guy? hier rid tgis bout our lib: https://docs.unity3d.com/Packages/com.unity.mathematics@1.0/manual/index.html gl!1'
literally contains nothing useful lol -- except that it's wip (ok and well that it's similar to SIMD and graphic/shaders math api)
Tbf, most of those methods in math are very self explanatory.
To signify that these types are bultin their type names are in all lower case.
Will they ever stop butchering every existing naming convention lol
Also that lowercase namespace name
when u take sl conventions too far
In C#
intandfloatare considered builtin types.
Yeah but these are aliases toInt32andSingle, which are properly named, so why, just whyyy
I assume all the name convention violations, and I guess most of the questionable things in Unity (like overriding ==) are historic artifacts back when Unity was supporting not just C# but also UnityScript and Boo
still it's pretty cool that they made this compile 😄 I was happy enough to never care about the docs in this case anyway lol
I wish Unity could start over and rid these mistakes, but that's a pipe dream.
how do you guys feel about URP/HDRP?
I sometimes wonder what wonders could've been done in the engine if these 2 projects weren't approved
not saying they're not useful.. just not to me, and kept thinking about it
Don't think I'm qualified to give an opinion regarding those, I've only used the very basics of URP and it works fine for what I need.
Well, there's always the "here's our 3 rendering pipelines, 3 UI solutions, etc" meme.
Yeah that just looks like shader code, or javascript
is it ok to yield return in a coroutine from inside a foreach loop? it seems that is causing problems for me and i'd like to make sure that isn't the root of the problem.
to clarify, the array i am looping over with the foreach loop contains no null values before the loop, but after the first yield return inside the loop, it suddenly contains null values, but i am not altering anything inside the loop.
Switch to a for loop, and see if you can reproduce the issue. Yielding in a foreach loop should not cause any issues
yeah i didn't think it would be the issue, i'll try that and report back
foreach is just an elaborated while loop after all, it compiles to one
still have the issue, but i have an idea what might be happening so i'm checking that first
hmm that wasn't it
well if i remove the yield return it doesn't give me the error and the array remains intact
@fresh salmon
Error? What's the error about?
it doesn't always occur but when it does it's a null reference exception
and it seems that the null reference is the iterator variable from my for loop
as in collider in foreach (Collider collider in colliders)
Can you try with
var e = colliders.GetEnumerator();
while (e.MoveNext())
{
Collider collider = e.Current;
// contents of loop go there
}
Essentially the compiled version of foreach. Then place a breakpoint and step through line by line, inspect the contents of the variables
i doubt that will work bc the stack trace for the error says something about MoveNext
i'll try setting breakpoints with my current code
Depends on which MoveNext it's talking about, because there's two. One that iterates the foreach loop, and another that the compiler generates for your iterator method (which is translated to a full class), called by whatever runs the iterator
If the class name is really weird, then it's the iterator's MoveNext throwing
ah i see
ok i'll try what you suggested
ok lots of weird things are happening so i think this is most likely a result of a series of other less related bugs in my code so i'm gonna go find those first
sorry to bother you
@fresh salmon fixed it, turns out the issue was i was assuming that destroy would destroy the object immediately but in reality it isn't actually destroyed until the end of the frame
so i added yield return new WaitForEndOfFrame(); after calling destroy and it works now
Does anyone know what this error is trying to tell me:
NullReferenceException
at (wrapper managed-to-native) UnityEngine.CanvasRenderer.get_cull(UnityEngine.CanvasRenderer)
at UnityEngine.UI.GraphicRaycaster.Raycast (UnityEngine.Canvas canvas, UnityEngine.Camera eventCamera, UnityEngine.Vector2 pointerPosition, System.Collections.Generic.IList`1[T] foundGraphics, System.Collections.Generic.List`1[T] results) [0x00021] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.UI.GraphicRaycaster.Raycast (UnityEngine.EventSystems.PointerEventData eventData, System.Collections.Generic.List`1[T] resultAppendList) [0x00272] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.EventSystems.EventSystem.RaycastAll (UnityEngine.EventSystems.PointerEventData eventData, System.Collections.Generic.List`1[T] raycastResults) [0x00030] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.EventSystems.PointerInputModule.GetMousePointerEventData (System.Int32 id) [0x00090] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.EventSystems.StandaloneInputModule.ProcessMouseEvent (System.Int32 id) [0x00000] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.EventSystems.StandaloneInputModule.ProcessMouseEvent () [0x00000] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.EventSystems.StandaloneInputModule.Process () [0x00032] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
at UnityEngine.EventSystems.EventSystem.Update () [0x000b7] in <e0bc12d6d4684ff9a2af6711575bbd24>:0
Something in a raycast is giving a null result but then trying to do something with it as if it's not, by the looks of it.
Hmm. But it would be a raycast for the events sytem in the UI?
Seems so since it's on a Canvas.
God I wish I could figure out what triggers it. Only seems to happen in windowed mode build.
I think it has happening after I do an attack pressing a key or mouse button
I thought it was going to be the floating text for damage, but this seems to not be that.
Do you have any other UI events firing on an attack?
Nothing else uses the input for the attacks. Other then the inventory, which uses the ipointer events for drag and drop
But the inventory isn't open when this happens
Did the error only just start happening or has it been present for a while?
Only just noticed it.
It's very hard to make it happen, so I don't know if it has been around for a while
But when it goes off, it kills the FPS
Ah, okay. Reason I asked was that if it were a recent thing it might be traceable to something you just added, but if you can't be sure about that it could be anything.
Yeah. It doesn't seem to happen in editor testing, so it may have flown under the radar
Just a guess, but could it be that a canvas is being destroyed at some point?
Oh, good shout.
Hmm. That is possible.
I have a canvas on monsters/players for displaying hp bars etc
And it's probably destroyed at some weird timing. Like during a pointer event handling.
When they go out of range they get destroyed
Or something like that. Since the event system tries to raycast to it, but it seems to be null at that point
Assuming that's really what's happening
Okay. I do have a raycast to the camera
From the object with the cavnas for line of sight
Where do you destroy it?
And dist
So this is a client server setup. When they get about 100 units away the network despawns/destroys on the client.
Which is wrapped up on the network logic
Can you be more precise? At what point in the program execution is Destroy called?
Is it destroyed via an rpc or something?
Yes. It is an RPC call from the server
So I'm working on modding support for my game through Lua and MoonSharp, but some assets modders will need to make are inevitably going to be Unity assets (such as animator controllers). Is it possible to fetch Unity assets like this during runtime with a file path?
Hang on the method is to big to not be txt file
Use a paste site
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
//If to destroy.
if (destroy)
{
MonoBehaviour.Destroy(nob.gameObject);
}
This is a network call from the server.
But I think you may be on to something with the Canvas and the raycast
I do have an idea where to look
I just wish I could trigger it reliably to know if it is fixed.
What framework are you using for networking? Do you know where in the execution loop does it call the rpcs?
I'm using FishNet
It is probably happening here.
private IEnumerator UpdateVisiblity()
{
while (true)
{
yield return _wait;
if (Vector3.Distance(_cameraTransform.position, transform.position) > ViewDistance
|| Physics.Linecast(_lineOfSight, _cameraTransform.position))
{
SetCanvasVisibility(false);
continue;
}
SetCanvasVisibility(true);
}
}
Nah, that's a physics cast. I don't think it's related
So you think it is unitys event system trying to ref a canvas that just get despawned?
That's how it looks like from the callstack
Hmmm. That makes this more complex.
Well I really should move the canvas off the gameobjects anyway and just have one canvas get updated to display player name and hp bar.
This may just make me do it sooner.
The only way I see that you can do that is by using AssetBundle.
I was thinking the same. So AssetBundle it shall be.
I'm not sure if its possible to build AssetBundles outside of the editor though. Unless you know the format of the file?
I am only asking if it is possible,
but Assuming I launching an application from within unity, (and that application tries to read the camera)
is there a way to direct a unity camera to that application, instead of it trying to read from the laptop camera?
Not possible. Might be possible the other way around. If you embed unity into the other application.
No, but I am trying to make an application read a camera from unity, without doing
Inter-process communication.
That's not possible.
dlich, crushing people's dreams since 2019.
I mean,it's not entirely impossible. Just not they way they want to achieve it.
I have a post processing volume override that I want to modify with code.
However, the code below is returning a Component with a null material:
GetComponent<Volume>.sharedProfile.TryGet(out s)
I can see the effects of the component in the game, so there's a component out there somewhere with a material. How do I access it?
What is the type of s?
Where exactly are you trying to get the material from?
I am using the existence of the material as a kind of proof that I have the correct component. The type of s is Shockwave, a custom post process order that I have @lament salmon
public sealed class Shockwave : CustomPostProcessVolumeComponent, IPostProcessComponent
m_Material is being populated automatically by HDRP
I can see it when debugging
I was hoping for something like this:
var process = new process();
process.redirectCamera = UnityCamera
or something like that.
But I can't seem to access it in a monobehavior
Maybe you want to access the profile instead of sharedProfile?
That's impossible. What happens in Vegas process, stays in process.
That has no effect. I see the effect in the game world, and I can put a breakpoint inside of Shockwave.cs and see the material being there. But I can't seem to get it in my monobehavior.
What are you trying to accomplish with this?
Hmm. None of the code you showed is faulty, so it's hard to speculate further without seeing the rest. Like how are you accessing the material and how is it declared
Hack some app and substitute the camera input👀
This is literally all I'm doing:
Shockwave shockWave;
bool got = GetComponent<Volume>().profile.TryGet(out shockWave);
Debug.Log(shockWave.m_Material);```
doing ML detection on a camera feed, through unity.
(without using IPC, trying to see if it is possible to make it all happen inside unity)
Are you sure this code runs after HDRP has populated that m_Material field?
Sorry not much to work with here so its all I can think of.
Absolutely, I can see the effect on the screen while the console is logging "null"
I can also put a breakpoint inside of Shockwave.cs Render and see the correct material.
It's almost as if TryGet is returning some kind of empty copy
In the debugger, it does have the word (Clone) in parens Shockwave(Clone)
You could use Spout or Syphon
Are you referencing the prefab perhaps?
@ancient rivet Alright so I just tried to replicate your issue in my own project.
End result: It also prints null for me
Even though the PP effect itself works fine
I am not referencing a prefab. I am simply following https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@14.0/manual/Custom-Post-Process.html
@lament salmon are you saying you were able to reproduce the issue?
Yes.
So, what can we do?
What are you trying to do though? Why are you accessing the material directly?
Well, so I can load the shockwave positions and times for any explosions occuring dynamically on screen
It looks really sweet, when I input it from the Unity Editor
but it needs to come from code
I believe it has something to do with that HDRP has to instantiate the material for every camera, so there's no "one instance" to access, I could be wrong though
Try using sharedProfile🤔
Tried that first, no effect
I mean, somehow people pass dynamic uniforms into shaders, right?
But in any case, you are not really supposed to access the material directly, but use the ColorParameter, FloatParameter etc. variables inside your post processing effect
Yes, yes, I am only using the material as an indicator of the issue
Because, the real issue is, it's a different instance. Setting its properties has no effect
try it on your machine
Are you talking about the material?
no, I am talking about the VolumeComponent, Shockwave
Are you sure your component is defined correctly? Should it be sealed?
Can you share the whole script?
I simply modified the default file that HDRP generates