#archived-code-advanced
1 messages · Page 93 of 1
but I'm doing shader graphs for my UI elements so I needed to upgrade
since fsr it took them that long to realize they needed it lol
does anyone have an answer to this? I've been stumped for a while on it
rah TMP is such a pain in the ass, I know ppl had to poke at the hlsl
frick
I'm having some trouble with package dependencies. I'm trying to get unity package manager to automatically install the dependency (LimitedObjectScrollList) from git, if not present, when installing the dependent (FilePanel) package from git.
But when I try this it gives me an error saying it cannot find the dependency.
I've tried a whole bunch of variant urls, as I'm pretty sure the problem is in the dependent's manifest file, but I'm just kinda guessing and finding conflicting info on what URL I SHOULD have in there.
Can anyone set me straight?
here are the relevant files...
Dependancy package
https://github.com/glurth/LimitedObjectScrollList/blob/main/package.json
Dependant package
https://github.com/glurth/FilePanel/blob/main/package.json
https://github.com/glurth/FilePanel/blob/main/manifest.json
I found the hlsl file that it uses, but I'm not really that good at hlsl, if there was a way for me to use a graph, that would work
TMP usually don't need much noodling, what are you trying to do? maybe you can layer
Installing via git doesn't read dependencies afaik. It's not a package registry so it'll just be ignored
I made a Chromatic Aberration shader and I'm trying to make a TMP version of it
I know I could just cheat it by making 3 different text objects or something but this solution should theoretically be able to apply to any text object since I'm gonna be using it a lot
The TMP shaders are all there in your project and you can happily modify them. But they're using SDFs and have tons of layers, so it's not easy
I found the shader that I need to base it off of and it's not actually even that long, I just have no clue how I would change it since I'm not that good at HLSL
should be pretty easy to hlsl that thing, just copy the 3 RGB offset to the end, just before it returns the pixel value
it does seem to know about the dependancy from the json file- and it show up in package manage.. but sounds like that's insufficient, even if I give it the github url? darn.
But how do you know what value is next to yours to do this RGB offset
something like
out = sdf stuff
out = mangle out with RGB offset
return out;
was thinking uv offset
it's split into 2 functions, PixShader and VertShader. For a TMP object, would it be Pix? I don't think I'm modifying any vertices
oh but that'd need an output to some rendertexture... meh yeah that won't work
yeah I think it would be idk why I asked lol
is there any way to use my sub-graphs on a regular shader?
that's a question for jason boothe, he'll go on half an hour rant then will prob tell you nope
lol
well I guess I'm learning more about HLSL now
fun.
man I've spent like 5 days at this point on this single UI lol but at least it's gonna be really polished
bloody pain in the ass: it's like Unity don't like easy stuff anymore, everything is so tortuous
5 days for this isn't worth it, either you do what you said and tripple your TMP, they're cheap anyway, or you render them to a 3D camera and put a RGB offset post effect on that
well I haven't spent 5 just on this part, but the whole UI
I've made like 8 shader graphs for this UI already, a Skew component that skews any TMP_Text or Graphic, and spent 2 days alone just doing the design and doing a bunch of iterations
oh ok
the Skew component alone was a pain in the but lmao
since TMP doesn't use the IMeshModifier like all the other Graphics do
here's how the whole thing looks so far
doesn't? it's all in SDF shader?
there's no way to skew TMP built-in and it doesn't have the same way to modify the mesh like Graphics do (even though it is a Graphic)
could skew it in the vertex shader?
I could, but I'm intending to have other shaders like the chromatic aberration one I'm trying to make so I wanted to make it a component so I could just slap it onto something that needs its shader
yeah, stack a vertex shadergraph on top of the sdf thing
why would chromatic aberration be applied to the mesh
thats something you will be doing on the whole screen
not the mesh, the Images
I also have a Glow shader which some things will be glowing but also skewed so if it was a shader, I couldn't do both since Images can't have multiple materials
it really sounds like you are implementing thigns into the per object shaders that really should be done in post processing
like glow i would just do via bloom, with a above 1 threshhold
maybe he wants a per button effect
If you were publishing it for the public I would use OpenUPM. But you really need to add some Readme's
the skewing the characters i would do on the shader that is applied to the TMP object
yeah but I think that's a bit more expensive and also not as customizable
the bloom doesn't give the effect I want
I want a Photoshop Layer Effect-style glow
expensive is late stage consideration, unless your hardware target is something weak.
I wanna be able to target as many computers as I can
yeah don't worry about it dude, that's a form of procrastination
OpenUPM.. cool will check that out, thank you.
just do your thing for a 2060 target then optimize if players complain
or you're never done noodling
I mean it didn't take that long and I still think it's better than the post-processing approach
Quest 2 would be another story, PC, players are used to shit framerate
this lets me put the shader on things specifically rather than just everything that has a high glow
you can mask out stuff
yeah but I think that's a bit more troublesome than this approach
this is just putting a shader on things, versus having a layer for what needs to be glowing
ok
also that glow shader took like half an hour, it didn't take as long as the other stuff
weird, my 2022 won't compile on script change by default, where is that setting?
I'm taking a poll: Should I rotate the items in the shop, skew them, or have them be flat (no rotation or skew)? Pretend the image with skew has shadows like it's supposed to lol
This is not a code question.
Personaly, I would go for a simpler approach if what you tried havent work such as redesigning the UI.
True
How so?
Remove the necessity to skew the text.
So you think it shouldn't be skewed or rotated?
If you are not able to make it in a reasonable amount of time, yes.
Well I mean I think it would be easy, I just have to remove the skew components from everything, but I like having some sort of motion to the design. I'll still consider it when I get the results of the poll though
I'm trying for something like persona but less crazy
The time you use on this aspect could be used else where. It really a question of how much you want it or not more than what is better in my opinion. (Given that you seem to struggle to make exactly what you want)
I don't really struggle, it just takes a while since Unity doesn't have the Skew as part of its transform already. Now that I have the component, I can skew anything so time really isn't an issue. I've been working on this project for a while and fully anticipate to spend a lot of time polishing it as much as I can
If I have a goal, I'm gonna achieve it. I'm not gonna settle for good enough just because it takes less time
This is pretty much almost exactly how my Figma design looked
That is really not a good way to approach game development, but you are free to do whatever you want. We all have different view, but keep in mind that you sacrificing a lot in pursuit of perfection.
How? I want to make a good game and I know how to do the stuff. Polish is one of the most important parts of a game
I have a timeline to complete the game by and I'm still approaching it steadily
skew is a simple matrix multiplication in a vertex shader. but i think what simfoerce is trying to saying is you should move on and get the whole flow of the game going. before trying to apply alot of polish to 1 small part
Do you not realize that everything has a cost. When you are doing a specific things such as that, you might leave other more important aspect. This one of the main reason why a lot of people tends to abandon project midway.
Well I know it's simple in matrix multiplication, but I had to do stuff with TMP meshes and I couldn't just manipulate the transform matrix. I'm trying to make a vertical slice, not a horizontal one
It's not leaving the other aspects, it's just doing one thing and completing it before moving onto another
This has only taken me a few days, it's not like it's taken weeks
I probably won't have to spend more than a couple more days on it, if even
If I had spent like a month on it then I could see your point, but the amount of time I've spent on this compared to the other stuff is very small
This is by far not the only part of the game I've worked on
And while I'm working on this, the rest of the team is still doing their thing so it doesn't halt production of everything else
I really hope you just reflect on what you said.
The following is simply wrong on many level in my opinion:
It's not leaving the other aspects, it's just doing one thing and completing it before moving onto another
What you have done could have been such things that are not important (I do not have all information on hand), I was simply giving advice on how to manage your project base on what I understood of your question. Anyway, it seem you get it.
But sure, it is also important to keep in mind that a game is a collection of little details. Just keep in mind that everything has a cost.
What is the best way to force a pixel game to act as if it's on a specific resolution (i.e. 384x216) but still fill the whole screen regardless of what monitor resolution it's played at, while not messing up the UI?
Reason I ask is I've noticed Text doesn't align perfectly with most of the methods I've tried. It ends up having some floating point error and ends up off of the pixel grid I'm trying to establish. Normally not noticeable, until the Text is next to or on top of an Image.
Unless I build the project in 384x216 windowed mode, then it's on the grid. Only problem is its tiny on any modern display, so that's useless for what I need.
The font is a bitmap font, so it should be pixel perfect. I've tried other bitmap fonts and have gotten similar results, so I know it's not the font. It's something about how Unity places Text when the screen size of a pixel isn't 1x1, but instead 5x5 or some other scale.
To show what I mean, here's a test screenshot in a build, where I overlaid a checker pattern that matches the intended resolution. The background neatly is aligned, as are the buttons, but the Text in the buttons on the right is not aligned. No matter what anchors, positions, or alignment I set on the Text, it's not behaving.
The 'About' button (4th down) comes closest, but zooming in shows it's got some slivers of a pixel showing on the b on o that shouldn't be there
Did they remove the mono.simd.dll from the editor now? if so, proly it won't be compatible anymore if I'm going to borrow it from official mono?
Hacky workaround ended up not involving any recoding of anything, but to use a magic number of 1.0125 for the line spacing, to counteract what unity was doing in the Text component
Can someone give me a example of how to convert reflection.MethodInfo to unityevent, I just couldn't get it to work thanks in advance
that is a bit of a weird ask, what are you trying to do
also you could just make a lambda that calls invoke on your method info
_myUnityEvent.AddListener(() => _methodInfo.Invoke(target, args));
i do this in my game for my cheat menu, have a CheatAttribute i add to things in need in the menu, and it builds it via reflection for me
im so mad ,i fogot that AddListener wouldnt update the inspector but it is added🤡
Hi! Does anyone know how to get all scores from a bucket leaderbord in js unity cloud?
I use const getScoresResult = await leaderboardsApi.getLeaderboardScores(projectId, "LDBBucket"); and the result: "detail": "Score submission required to view the scores of this leaderboard",
Hi, i have a very niche problem, i am not a good coder, I am trying to make a deformable terrain using the Unity terrain system. The system uses a height map stored on the computer to make the height of the terrain. my aim is to create a mining system in which you use a ray cast to target the ground and that will then deform the terrain at the point. However, the nothing i am doing seems to work. I can link the code if that helps and im just getting a bit lost. I am able to get the data from my point on the terrain but i cannot use that data to then deform the terrain.
you should provide the code, but also, if you are using the terrain SetHeights method, keep in mind that the heights passed in need to be numbers from 0 to 1 and not a actual heights.
private void Mine(Vector3 point)
{
int mouseX = (int)((point.x / terrainData.size.x) * heightMapRes);
int mouseZ = (int)((point.z / terrainData.size.z) * heightMapRes);
float[,] ModifyHeight = new float[1, 1];
float y = heights[mouseX, mouseZ];
y -= strenght * Time.deltaTime;
if (y < 0)
{
y = 0;
}
ModifyHeight[0, 0] = y;
heights[mouseX, mouseZ] = y;
terrainData.SetHeights(mouseX, mouseZ, ModifyHeight);
}
This is the code that effects the terrain but i cannot figure out how to get the height function to work be between 0 to 1.
I believe you want to divide the result by your TerrainData's heightmapScale.y before setting it
so, in other words, translating from normalized height to real height (and back) would be like
var terrainHeight = terrainData.heightmapScale.y;
var realHeight = heights[mouseX, mouseZ] * terrainHeight; // from 0-1 to 0-terrainHeight
var newHeight = realHeight - strength * Time.deltaTime;
heights[mouseX, mouseZ] = newHeight / terrainHeight; // from 0-terrainHeight to 0-1
Anyone know of a good way to call a method on a script once an animator state finishes? Preferably without using animation events since adding them to each animation isn't really an option
could use a StateMachineBehaviour
AnimatorStateInfo
yeah but unfortunatly they cant access the scene and I want this to be as general as possible
they kinda can actually, since you have access to the animator from them, which can get stuff on the same object as it
otherwise you can read the state info in a update and wait for its change
well yeah but what i want is for the method to be selectable from the inspector
and the animator reference only exists during runtime
okay i will try that thanks
how do I initialzie newly created scriptable object, to have it reference some other assets without manually selecting them everytime an SO asset is created in the project?
I've searched through the web and no help found
It probably works if you select the SO file and then change the values on that instance, that should serve as defaults
Or you can create your own custom creation function that sets things
I mean during the first asset creation in the project
yeah, like that. But where do I write it when I have a SO attributed with [CreateAssetMenu]. I saw one answer with custom editor and doing it the OnInspectorGUI, but I fear it won't trigger if the inspector is closed.
Don't use CreateAssetMenu
why not?
[ContextMenu] that is then, I guess
probably because it doesn't seem to have any exposed mechanism for something like "OnAssetCreated"
If you want to do custom behaviour on asset creation, then you have to implement it yourself
IIRC if you check the reference source, you can find their implementation and copy it
I didn't find anything that happens on asset creation. For example on this page, Initialize has to be manually called from [MenuItem], that is by using UI to assign asset defaults... which sounds pretty dumb https://docs.unity3d.com/ScriptReference/ScriptableObject.html
for now I did it like so:
public class Preset : ScriptableObject {
private void Initialize() { /* initialization of defaults here */ }
// based on mechanism from shader-graph package
[MenuItem("Assets/Create/...")]
private static void CreatePresetAsset() {
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
CreateInstance<CreatePresetAction>(),
"preset.asset", null, null);
}
private class CreatePresetAction : EndNameEditAction {
public override void Action(int instanceId, string pathName, string resourceFile) {
var preset = CreateInstance<Preset>();
preset.Initialize(); // <-- initialize once
AssetDatabase.CreateAsset(preset, pathName);
AssetDatabase.Refresh();
Selection.activeObject = AssetDatabase.LoadAssetAtPath<Preset>(pathName);
}
}
}
I guess you mean scriptable wizard, not scriptable editor?
yeah, that's called a wizard: https://docs.unity3d.com/ScriptReference/ScriptableWizard.html
But that's not what I need. I have some fixed defaults and all the other things are just created at use-site. The wizard adds a bunch of needed complexity to that. this works OK for now.
there is another problem though, when I update something in my SO, other assets that depend on it don't refresh in editor.
https://docs.unity3d.com/ScriptReference/ScriptableObject.Reset.html this guy should get called when the object is created.
I'm having an issue where some fields of my class are not serializing, while others are, and I cannot figure out why. The fields in question are public, and are simple types like float and bool. Any ideas why some fields would serialize, and some do not?
Do you have any compile errors in the console, for ANY code (not just this code)?
nope
Then show your code and explain which fields aren't serializing and how you checked if they are or aren't.
Ah I got a field to serialize, althought I don't fully understand why it wasn't before.
I have a separate editor script, and for the fields that were working properly, I was doing
EditorGUILayout.PropertyField(serializedObject.FindProperty("myField"), new GUIContent("Label", "Tooltip"))
For the fields that were not serializing, I had used a different way to add them to the GUI:
MyClass myObject = target as MyClass;
myOject.myField = EditorGUILayout.Slider("Label", myObject.myField, 0.0f, 1.0f);
After switching everything to the first form, it is serializing properly
that's not an issue of the field being serialized, that's just it not being drawn in the inspector due to your custom inspector for that object. the field was still being serialized despite not being drawn in the inspector
The fields were in the inspector in both cases, and changing the slider affected my object in both cases, however, saving the scene and reloading it would lead to the fields using the second form to not have the correct value, they were always reset to their defaults upon reloading the scene
Looks like the reason was actually because I was not calling EditorUtility.SetDirty(); in the second case. So the fields would have serialized just fine, but I wasn't flagging the object as dirty so I guess they never got serialized
Seems like using the EditorGUILayout.PropertyField() method calls SetDirty automatically under the hood
Yeah this isn't a lack of serialization, you just didn't mark the SerializedObject as dirty. The fact you were using a custom editor would have been pertinent information when asking the question.
Indeed. Luckily I was able to figure it out after rubber ducking here.
Honestly I am not sure what your response adds to the discussion here. You summarize my own findings back to me as though it is new information. If I had known that the custom editor was part of the problem when asking the question, I would have included that. But thanks anyway!
I'm using steamworks, and I can't figure out how I would kick a player. What I've tried doing is when someone clicks the kick button, it fires a ClientRPC, which then all clients get it, and if they have the CSteamID that was sent in the ClientRPC, then they will call SteamMatchmaking.LeaveLobby(), but it doesn't seem to work, and I don't want to put a NetworkIdentity on the gameobject holding it.
not sure i totally understand the problem here, is this NGO with steamworks or some other framework? in NGO you can send a custom message if you want to send a messaage to all clients but it's not related to a specific network object
What is NGO?
unity netcode for gameobjects
I'm using FizzySteamworks w/ Mirror, and using netcode for gameobjects too
ok, sounds like you want a custom message then?
Yeah, someway to send messages between them.
oh i mean the actual feature named custom messages: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages/
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
But does this require any Network Components on the object recieving/getting custom messages?
there's no object involved, custom messages is a system totally separate from rpcs
you just need a reference to the network manager somewhere!
Ah ok, could I pass parameters through it such as a CSteamID
why and also how are you using two networking libraries? 🤔
Maybe I'm confused, but I think I meant I'm using Mirror's network objects
you can send whatever you like really, but with custom messages you have to do more of the reading/writing yourself! steam ids are just a number though so that should be no problem
the docs have some examples of using FastBufferWriter/FastBufferReader
I think they are a type of ulong but I don't really know
yeah its a 64 bit ulong it says
yup!
okay so that is not unity's Netcode for GameObjects package. so you'll want to check mirror's docs to see if they allow custom RPCs like n4go does
steamworks is matchmaking, mirror is the transport, ngo is the framework
mirror is a networking framework akin to ngo. it's based on unet
I got to go now, but thanks for the help simonp. I'll look into it soon.
Mirror was named that because it is a "mirror" of unet afaik
🤷 i don't understand this stack at all then, luckyecho you should probably check whether you're actually using mirror or ngo lol
Mirror as the transport, using NetworkManager from mirror, and FizzySteamworks for multiplayer
mirror is the network library, fizzysteamworks is the transport https://mirror-networking.gitbook.io/docs/manual/transports/fizzysteamworks-transport
Thats what I am meaning.
i guess this is what you want then https://mirror-networking.gitbook.io/docs/manual/guides/communications/network-messages
hey does anyone have a tutorial on an advanced 1st person fps, Im trying to create an fps game and need help with the realistic arm movements and weapon bop arm bop and such. sounds vague but will go into more detail if anyone DM's me
see if these help:
(and that sounds like a question for #🏃┃animation )
https://www.youtube.com/watch?v=CXFLu8cityA
https://www.youtube.com/watch?v=7t0hLZd_8Z4
In this 2015 GDC session, Bungie's David Helsby shows how Bungie creates high quality first-person animation that supports Destiny's cutting edge gameplay.
Update: Due to a technical error, the last portion of this talk is not currently available on YouTube or the GDC Vault. We do apologize for the inconvenience.
GDC talks cover a range of d...
In this 2017 GDC talk, Blizzard's Matthew Boehm dives into the artistic and technical challenges of creating personality in first person animation for the robust and varied cast of Overwatch.
GDC talks cover a range of developmental topics including game design, programming, audio, visual arts, business management, production, online games, an...
Regarding Asynchronous loading of assets via AssetBundles, if I asynchronously load an asset, and said asset has dependencies (such as containing an array of unity objects), do these dependencies load asynchronously as well or synchronously?
Hi, is there a way to get all defines that will be applied in the build, prefferably during build pipeline or right before it?
I know i can use PlayerSettings.GetScriptingDefineSymbols - but that only gives those that are explicitly defined by user, it excludes the unity build-in ones like UNITY_ANDROID or unity versions etc.
there is also EditorUserBuildSettings.activeScriptCompilationDefines but that returns the current ones, so if i build different target then the current one then its not correct. Also when i apply PlayerSettings.SetScriptingDefineSymbols just before checking activeScriptCompilationDefines then its not up to date and i have no idea what callback to wait for so i get the correct ones.
I was thinking if maybe someone knows some unity callback that will give me the defines so i can write them to build somewhere.
Hey guys, I am far into multiplayer fps game development with Unity. I have been lately debugging my lag compensation code and it looks like one box collider is offseted little bit on server in comparison to client. (or my box collider drawing code does not work)
I am drawing using object's (which got the collider) position, rotation, lossyScale, and also box collider size + center. It also seems like lossyScale is different by about 0.001 even though it should be (100, 100, 100) on both.
My question is: how can I 100% accurately log a box collider into console? Do I just need box collider's center & size, and then the object's world to local matrix, instead of using lossyScale etc?
Sounds like inaccuracies with float objects?
If you want it to be super precise you might be able to instead pass a decimal value rather than a float type
I don't think that is the case.
My player got the following box colliders: head, legs, arm1, arm2 and torso
it seems like only torso's position/rotation/scale is offseted little bit. all other colliders are pixel perfectly where they should be.
Two questions:
- Is there a way to know if my code is run inside a Unity Job?
- Is there a way to know if my code is run inside Burst (even if it's not actually Burst compiled, ie: a managed code called from Burst using function pointers)?
The question is because I want to call a method when possible that can only be called in the Unity thread. And if we are not in that thread, I want to not call it.
I was checking the managed thread id and the synchronization context, but this doesn't seems to work all the time, at least for the (2) point it doesn't work.
can you put the unity-specific part in a method annotated with [BurstDiscard]?
[BurstDiscard] only works if the method is compiled with Burst. But if you have a burst-compiled method, which performs a function pointer call, you can call managed methods which are not burst-compiled
ohh right i see... what didn't work with checking the managed thread id?
It didn't, I don't understand why but checking the managed thread id seems to not be enough
🤔
what do you mean it didn't work though?
I tried to compare current managed thread id with the main one, and if different, not call the Unity method.
But when called from a managed method, called as a function pointer from a burst-compiled one, the function is still called and it throws a not catchable exception.
hmm, i guess because jobs aren't running on managed threads 🤔
it would probably be easier to pass the information through from the burst job if that's an option, if you can add a parameter to the function pointers being called? then you'd be able to use BurstDiscard etc
Not exactly an answer to your question, but maybe have two versions of the code, one for Burst one for not. Code duplication can be solved just like any other code, by extracting and reusing the common parts. Might be easier even if less elegant.
there is also no problem with a bit of code duplication and if means less other problems to solve
I guess I could have two methods, but the idea was that the consumer of the method doesn't need to know where it's currently running
I've had enough.
public static Object ReliableReference(this Object obj) => obj == null ? null : obj;
public static Object RR(this Object obj) => obj.ReliableReference();
```_I'm taking my nullity operators back._
"Fuck you! *Unimplements your null check override*"
Wasn't sure where to put this but i'm making a Unity plugin packaged as a .dll and I was just curious if anyone knew of a way to trigger an assembly reload in an active unity editor instance via a postbuildevent
rn i copy over a build to my unity project as a post build event and in a perfect world it would be cool if i could tell it to start reloading at the same time yknow
I THINK this is advanced? Not sure XD
I've basically stuffed an array inside of another array. One has a size of 7, the other has a size of 6. And what I do with these is I calculated a semi random coordinate for an island on my map, stuff the coordinates, name it, and attach an object and an image to it. My problem is, I have no clue how to save it. Because PlayerPrefs only saves ints, floats, and strings. I'm being told I should save it using a json and save that as a string. But that has come out as not working lol.
This paste bin contains all the main functions
https://pastebin.com/KD2kKmC6
"Quick" explanation:
When the game starts the first thing that runs is the SaveManager. Which on awake loads any saves and sets the variables within SaveManager, to those saves.
THEN MapController loads, and in the start function it sets the islandArray as the islandArray from the SaveManager. If it turns out to be null or 0 (no saved islandArray) then it creates islands and saves that array. I've added a couple debug logs checking the length of the array to make sure it's not null or incorrectly saved.
After running and closing the game twice, my debug logs show that when the islandArray is loaded in the SaveManager the length is 0. So then MapController goes to create new islands, does so correctly. Then when it attempts to save the array, SaveManager says the array taken from MapController has a length of 7, which is correct. And for redundancy I checked if the islandArray in SaveManager after setting it's value to the value of the islandArray in MapController is the same, and it is, 7.
But even though the saves SEEM to check out, at least the lengths of the array, the length never checks out when loaded/transferred from json
Please help XDDD
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.
its a limitation of json utility
can use the Newtonsoft Json Unity Pacakge
its much more full featured
also i would not save it to player prefs
this gives you a path you can save files to and read from
yayyyyy more learning XDDD
Time to learn how to manually create a file that I can put an array, and turn back into an array XD fun times
Thanks lol
File.ReadAllText and File.WriteAllText
just have to build the file paths from the persistientDataPath and your file name
Or reorganize your data structure to not use an array of arrays. Or serialized it manually.
if its simple for 2d grid data or something similar
its possible to use a 1d array, and some math to convert a x, y coord to a index into it
I just decided to go with 2 arrays because I need the inner array to contain a string for the island name, it's coordinates relative to my 2D map, and the game object and image object it's attached to. And then ofc I need multiple islands, so I need that array to be inside another array.
Unless I'm just making my life harder on myself
if the width of the map is knowen its possible to use 1d
i = row * colCount + col
would let you take a target row and column and get a index into a 1d array for
you might want to learn about objects and classes
https://learn.unity.com/tutorial/classes-5#
I'm dealing with pointers/memory addresses and having an issue with just doing it right. I keep on getting an error telling me that a field initializer cannot reference the non-static fields, method, or property Hoverboards.test. I don't know of any other way to do this.
well, the error tells you what you need to do. Which is not reference non-static fields, properties, or methods in field initializers. Use a constructor. Your snippet is nonsensical anyways
But I've written code like this all the time:
? Value isn't a class field there, apples and oranges
That makes a lot more sense now. Thank you.
pointer is code advance but you may need !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
btw the error tells you field initializer
You've (hopefully) heard this before, but unless you're dealing with native libraries, direct hardware, or extremely high performance systems there's normally no point using pointers in C#. They're not meant to be used like they are in C/C++.
In my VoiceParticipant script I have for Vivox (Version 16), I have a void that handles participants being added in order to add a participant tap to them. However, I don't currently know how to go about parenting the tap to it's corresponding player, since the function is only called on the local player's VoiceParticipant script and I don't know how to get another game object from just a participant.
I see you calling SetParent in that code.. what is it your not clear on?
Using Microsoft Speech SDK, when i stop playing i get an error: "Cannot dispose a recognizer while async recognition is running. Await async recognitions to avoid unexpected disposals." Problem is that the natural place to do this disposal is in OnDestroy ? making my Dispose function async won`t be ideal if in OnDestroy?, so kinda lost on this one.
how to get final velocity of a projectile after penetrating an armor plate?
this is not built in to unity... are you just looking for suggestions on formula? if so, what kinda parameters do you have?
i have, plate thickness, impact angle, bullet mass, bullet velocity, and demarre formula
cool! not sure what that formula is.. looking it up now
about more realistic projectile penetration
this one?
this is super hard
what?
this is what I found searching for that formula... does it match what yo are expeting?
that isnt demarre
idk the formula, i need a formula for final velocity of an projectile that penetrated the armor
but you have it
I'm confused, if you dont know the formula what akes you say the one I posted isn't correct?
im not searching for demarre formula
im searching for a formula for final projectile velocity after penetration
ah, ok happy to suggest something to get you started, but no idea how accurate iot would be.. Final V = ( ( (bullet mass * bullet velocity)/(plate Thickness^2) ) * impact angle/90 )/ bullet mass
if impact angle=0 then v=0?
^ was trying to show it would NOT penetrate at angle 0, it would "ricochet".. but your right.. not an ideal expression.
@tiny pewter
doesnt work
top values are velocities
left ones are angles
bullet weight doesnt even affect the equation
what are values in the table?
final velocity of an projectile
I dont get it.. looks like they are higher than the initial velocities.
i will just substract the "final velocity" with ongoing velocity, but idk why projectile mass doesnt get afected
are the initial(top row) and final velocity(entries) in different unit's perhaps? It definatly should NOT be going faster after impact.
Hi glurthy 👋
❤️
i believe manufacturers tested penetration depth (not speed) of different amours under different shells/distances/angles/weather but ofc impossible to get such tables online and offline
you can refer to other games to see how they calculate it
ah, and that formula I found/posted before was indeed penetration depth.. (failed to read the page properly before)
I'm using the jobs/native collections and am getting the following warning whenever my collections are left untouched for a few frames.
Internal: JobTempAlloc has allocations that are more than the maximum lifespan of 4 frames old - this is not allowed and likely a leak
However all of my native data is allocated from OnEnable with the persistent allocator, and disposed in OnDisable so I don't know why I'm getting this warning. Any ideas? Here's the main script, but I can share more if needed https://hatebin.com/vgcygaucjd
Hey does anyone have experience with Facepunch library for using Steamworks API in C#/unity?
I am running into a wall bc apparently I can't access static class in another member function...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Facepunch : MonoBehaviour
{
public static Facepunch Instance;
// Start is called before the first frame update
void Awake()
{
// start of new code
if (Instance != null)
{
Destroy(gameObject);
return;
}
// end of new code
Instance = this;
DontDestroyOnLoad(gameObject);
try
{
Steamworks.SteamClient.Init( 2687800 );
Debug.Log("steamworks initialized");
}
catch ( System.Exception e )
{
// Something went wrong - it's one of these:
//
// Steam is closed?
// Can't find steam_api dll?
// Don't have permission to play app?
//
}
}
// Update is called once per frame
void Update()
{
Steamworks.SteamClient.RunCallbacks();
}
void OnApplicationQuit() {
Steamworks.SteamClient.Shutdown();
}
public void TriggerAchievement(string achievementId)
{
if(SteamClient != null)
{
SteamClient.Achievements.Trigger(achievementId);
SteamClient.Stats.StoreStats();
}
}
}
The last method TriggerAchievement is what causes error when trying to reference SteamClient
Assets\Facepunch.cs(51,12): error CS0103: The name 'SteamClient' does not exist in the current context
However, it is a static class so shouldn't I be able to reference it anywhere?
If it is a static class, it always exists and can't be checked for null
true, I think the issue is that I was looking at code examples from older libraries in Facepunch, with similar class names. oops
there was apparently one called Client before but its not there in the source files now that i look
SteamClient.Achievements doesnt exist at all anymore apparently
so that's fun
I'm honestly baffled that Valve/Steam doesnt have a native .NET library for integrating their API into Unity... and that these 3rd party wrappers have such little support :/
like isn't this something that hundreds of thousands of devs do each year for their games?
Hover over the error and click the light bulb icon that appears. You might just be missing a using directive.
good idea, but sadly the library doesnt appear to exist in the example i was looking at anymore 😦
It's a feature integrated in your code editor
You do not need access to docs to figure out which namespace it's declared in, VS can resolve that for you
Clicking the light bulb icon will show a list of actions, with hopefully one that prompts you to add a using directive
Hi guys, sorry for being annoying, does anyone know how I can fit these dungeon rooms into just one square?
like this
nothing
Your code editor doesn't seem configured at all, errors should be underlined red
!vscode
Follow the guide above and come back when it's working properly
Lol. I get red underlines. My VSCode works fine
thanks anyway, i'll solve it on my own
What? The snippet you showed would error on its own
except line 52 should be a compile error so you clearly aren't
if i mess up any other code in any other file, this happens
so yea, my vscode isnt broken
its a symbolic link between unity and vscode maybe
Well it hasn't loaded for your file
Restart it, because the error you get in the console clearlypoints to line 52, which doesn't have one underline
I just followed the instructions on the Facepunch page, to include the .dlls into my Assets folder
but maybe that's the issue
it's not. it makes no sense to compare a type to null like that. and you even had the github page for that type up and should have clearly seen how you are supposed to check whether it is valid or not
That's purely a VSC issue, as Unity reports the error correctly
As I said, I combined borrowed code from a different library. It was my mistake for copying the code, but removing that line didn't fix it either bc those libraries dont exist anymore
VSC issue?
what "libraries" do not exist? because from what i see line 52 should be the only issue. i use FacepunchSteamworks and have no issues with it
well aside from the one issue i posted in the github
do you have a code example of how you set achievements?
that would be a huge help to me
It's just a missing using directive at the top
so you want me to put using Facepunch.Steamworks at the top?
I want you to restart VSC so it loads the analyzer properly for the file, then use the Quick Actions lightbulb to solve it
I think there is a problem with the analyzer, I should look into that
I tried restarting and I'm not seeing it checking my project anymore (it used to)
regenerate project files
(In fact you already use SteamClient in the same file, but it doesn't error because you fully qualify the name by putting the namespace before - is this really an advanced code issue?)
thanks I forgot where to go to do that, it had reset my external tools for some reason in Unity
Ok fixed that
the analyzer works now in VSCode again
as for how to trigger an achievement, the SteamUserStats class has a list containing all Achievements. there is no Achievements.Trigger method that takes a string
so now, it does have the red line, but as I said the Achievements do not exist in that library
right
it was in an old library
ok so we're on the same page, I'll try using SteamUserStats
why are you blaming "old libraries" on this when this is a matter of you not reading the documentation
this documentation? https://wiki.facepunch.com/steamworks/Achievement_Unlocked
void Awake()
{
//
// Tell Steamworks to call this function when something happens
//
Steamworks.SteamUserStats.OnAchievementProgress += AchievementChanged;
}
private void AchievementChanged( Steamworks.Data.Achievement ach, int currentProgr..
point to the line where is shows an Achievements.Trigger(string) method
haha I also saw the subtle "thanks for not helping" message directed to me that was deleted seconds later. bad faith much
sorry honestly i'm just very frustrated with the documentation on their page
and this simple task has been taking way too long
I guess the page you linked tells you how to run code whenever an achievement is unlocked, not how to trigger one
you have two options for getting an Achievement object, you can construct one by passing the name to the ctor (which, yes, is not listed on the actual docmentation page but intellisense and github both show that), or there's the list of all Achievements in the SteamUserStats class which is documented
https://wiki.facepunch.com/steamworks/SteamUserStats.Achievements
https://wiki.facepunch.com/steamworks/Data.Achievement
thanks. I lost my mind for a bit there. I'm sorry for being beligerant with both of you. I'll take a break and recompose myself. appreciate your help
This is my first time packaging anything. I'm trying to package an SDK I made and get it ready for distribution through personally hosted scoped registry. I have managed to host it using verdaccio and am able to download the package.
The issue I'm facing is when I'm done importing package to my new unity project; if i try to drag in a Prefab from the package, it seems to not hold any script references it had in the original project. When I try to manually drag in a script from the package on the prefab, it gives me this error
I have a feeling I havent constructed this package the right way... probably need to make a .asmdef file for the package?
But I've done that too and when I import the package to unity, it doesnt seem to have the .asmdef file in it for whatever reason. If i download the package as tar.gz from the repository, I can see it still has the .asmdef file in it. So for some reason it looks like Unity doesnt add that when importing package? Could be because I didnt make the .asmdef file the right way.
your packages should typically include an asmdef. but you need to make sure you are including meta files
ok so this is my asmdef but unity doesnt add it along with the package ```asmdef
{
"name": "ArcanaSDK",
"rootNamespace": "ArcanaSDK",
"references": [
"VoltstroStudios.UnityWebBrowser"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
are you including meta files
here's the package imported on unity, and here's the package once downloaded manually on file explorer
ya it has meta files 
do you happen to know what an AssemblyInfo.cs file is for?
I was trying to copy how this other package is packaged and it had an AssemblyInfo.cs
dont know if its necessary or not 
this is what it looks like
AssemblyInfo.cs is what is used by the C# compiler when making a .dll. Most of the information ends up in the properties of the dll and in Reflection. I would say you don't need it however the last 3 lines show that internal classes are being exposed to other dll's and this could be important
This AssemblyInfo.cs is for another package from someone else
I was just looking at the structure to see how i would package my SDK
my sdk does utilize this package but i dont think that needs AssemblyInfo.cs
Also please do let me know if there's more info i could provide on this problem 😄
why not just build a dll and have done with it?
hmm but I do have some prefabs inside this package that have preconfigured "examples" to use the sdk
not sure i could have prefabs in my package if the package was just a dll 
the package is not a dll, the code could be
seems like you are lacking a lot of knowledge to be doing this stuff
i am 😄
Ok I'm back so I'm confused by this section of code in their example:
public void CreateAchievement() {
Steamworks.SteamUserStats.OnAchievementProgress += AchievementChanged;
}
How would I signal which achievement is being added by this call? I haven't seen calls like this before, and the AchievementChanged method appears to take in an achievement as it's parameter
I think this warning is given if any job takes longer than 4 frames and isn't related to the NativeArrays passed to it or what allocation they use.
https://forum.unity.com/threads/jobs-lags-jobtempalloc-has-allocations-that-are-more-than-4-frames-old.513124/#post-3366232
that is not a call it is subscribing to a delegate or event
Hmm. Good to know, thanks. Though all my jobs are started in Update and completed in LateUpdate so that shouldn't be happening 🤔
In the documentation it says this should be the code for that event:
public void AchievementChanged( Steamworks.Data.Achievement ach, int currentProgress, int progress )
{
if ( ach.State )
{
Debug.Log( $"{ach.Name} WAS UNLOCKED!" );
}
}
I'm unclear on how this would do anything?
[ExecuteAlways, DefaultExecutionOrder(-1)]
public class PlexusManager : MonoBehaviour
{
public static List<IPlexus> Instances = new();
private JobHandle _handle;
private void Update()
{
var handles = new NativeArray<JobHandle>(Instances.Count, Allocator.Temp);
for (int i = 0; i < Instances.Count; i++)
{
var instance = Instances[i];
if (instance == null)
continue;
handles[i] = instance.Schedule();
}
_handle = JobHandle.CombineDependencies(handles);
handles.Dispose();
JobHandle.ScheduleBatchedJobs();
}
private void LateUpdate() => _handle.Complete();
}
like Steve said, this is subscribing to a delegate. it is also mostly irrelevant to triggering an achievement. I gave you the two ways you can get an Achievement object to then trigger it, stop ignoring that
the delegate you are seeing is a callback for when there has been progress on an achievement triggered by other code
https://wiki.facepunch.com/steamworks/SteamUserStats.OnAchievementProgress
result of a request to store the achievements for a game, or an "indicate progress" call.
that is not the code for the event. that is the code that will be executed when the event is invoked
This? I clicked on that link, it doesn't explain how to trigger an Achievement...
I see, ok thanks
no, but it shows how to get an Achievement object which you can then call Trigger on.
what you linked does not show how to trigger an achievement either
because, again, it is an event that is invoked when an achievement is unlocked or progress increases on an achievement.
Is this happening in edit mode, playmode, or both? The [ExecuteAlways] feels like a prime suspect to me.
Without wishing to appear rude, I think you really need to go and learn some c# concepts in order to be able to understand this stuff
Indeed, it hasn't been happening in play-mode so your suspicion is warranted
I am almost positive I never ran into this developing Deform, which runs in edit mode as well. I wonder what's different this time 🤔
Looks like in Deform I did not have a manager batching all of the jobs in edit-mode and let individual components update themselves immediately. I don't remember why 😅, but that's the only difference I can think of.
// Deformable.cs
#if UNITY_EDITOR
protected void Update()
{
if (!Application.isPlaying)
{
PreSchedule();
Schedule().Complete();
ApplyData();
}
}
#endif
For the plexus effect the manager batches all the instances' jobs in edit-mode and play-mode.
Can you see if the warnings go away if you move the _handle.Complete() to the end of the Update? That breaks the async processing, but at least lets you confirm whether the LateUpdate is the problem.
Surprisingly, it still happens!
It always happens after I deselect the game-object with the plexus component and particle system which seems important?
edit: I also tried commenting out the manager and scheduling/completing immediately from with the plexus update method. no luck still
Ok so if I want to get the Achievements, I could do
var achievement = (Steamworks.Data.Achievement)Steamworks.SteamUserStats.Achievements.Where(a => a.Identifier == "ACH_TEST").ToList()[0];
achievement.Trigger();
?
instead of using Where and then ToList, just use First
or just create the Achievement object by calling its constructor
what is your preferred method for dealing with the Editor keeping your game in "Play" mode on your Steam client when working on your game? do you have an Editor flag you set or something?
i just ignore it because it means almost nothing 🤷♂️
Alright I'm pretty sure it's a Unity issue. I enabled this diagnostic setting and I don't entirely know what I'm looking at, but it seems it seems to be related to the particle system geometry. I removed my plexus component which was on the same game-object as a particle system, and I'm still seeing the leak warnings when deselecting the game-object
hmm its causing an error to show in my Editor that forces me to restart intermittently
that shouldn't be causing any errors in the editor. whatever error you are seeing is likely unrelated.
ah ok weird...
also, probably doing this wrong but this is my code in Awake()
Steamworks.SteamClient.Init( 2687800 );
Steamworks.SteamUserStats.RequestCurrentStats();
It's not erroring, but the results are empty when I check the Achievements?
Hmm. Maybe it doesn't like having GetParticles called when it isn't actively simulating? Though, then I would expect issues before you select it as well.
I thought the same thing and tried removing that call, but still get the warnings.
However I'm not getting the warnings in a blank scene with a default particle system, so could still be something on my end *sigh*
doesn't sound like an issue with your code then
uuuh okay im not getting the warnings after returning to the original scene either. jeez. i have noticed the particle system editor starts to eats shit over time. like way more than the usual perf his it adds. might be related.
gonna move on for now. thanks for helping troubleshoot/sanity-check
Hmm well it worked creating the new Achievement from constr with your suggestion, guess I'll just go with that method! Man thanks so much for your patience.
TBH I had an edible last night, and skipped breakfast & coffee this morning... my mind was in a complete haze. Bad news. Thanks again
Vivox Participant Tap thing
Hey one more question when you get a chance. I've got a solution that works, but I want to not Trigger after the Achievement has already been reached. Is this concern really a non-issue because we would need to poll the achievement status anyway? Or is there a more efficient way of doing my conditional?
Mainly jwing if there is any danger to Triggering achievements that have already been triggered again, over and over?
else if(type == "Hammer") {
Steamworks.SteamUserStats.AddStat( "HAMMER_DAMAGE", damage );
Steamworks.SteamUserStats.StoreStats();
var hammerDmg = Steamworks.SteamUserStats.GetStatInt( "HAMMER_DAMAGE" );
if(hammerDmg >= 200 && hammerDmg < 500) {
Facepunch.Instance.TriggerAchievement("ACH_HAMMER_NOVICE");
}
else if(hammerDmg >= 500 && hammerDmg < 1000) {
Facepunch.Instance.TriggerAchievement("ACH_HAMMER_TRAINED");
}
else if(hammerDmg >= 1000) {
Facepunch.Instance.TriggerAchievement("ACH_HAMMER_EXPERT");
}
}
Looking for someone who knows how to convert what is 'seen' on screen to an image/sprite. I will need to engeneer a tool to acomplich this task. need help figuring out the right approach.
for example:
imagine in 2d a sprite of a white square and a yellow triangle overlapping slightly. then a zigzag line is created with line renderer over the two shapes. Now, screen capture this design and convert to sprite multiple.
ask your questions.. i know you may be confused lol
Render the scene with a camera to a render texture
It's a pretty common task
hmm. will that allow me to chop up the render texture into smaller pieces, like a jigsaw puzzle?
https://docs.unity3d.com/ScriptReference/Camera.Render.html
example in here shows how to render 1 frame to a RT
cutting it up, i would do by creating sprites out of the texture with masks
also once you have the render texture with the frame on it, you can just create regular Texture2D and copy ranges of pixels to them
Sure why not, it's a texture like any other. You can make sprites from it
The slicing part is a totally separate step from actually creating the texture
If you want jigsaw pieces using Masks would be the simplest way yes.
if i had to think i would have a grid a sprite i make with it that all overlap a tiny bit
then have a jigsaw like mask for each sprite
when you confirm my questions i have more to ask lol
there has to be a more effecient way than to have each minor piece mask their own image... is there a way to mask multiple objects then have them all retain there pizel data while moving seperatly without having each piece have a copy of the image?
wait wait.. hear me first
Sprite is a rect on a existing texture
and you can have many sprite reference pixels from 1 texture
That's how sprites work. The pieces don't have "copies" of the image, they all reference the same texture data
i want to be able to dynamically change the reference image (solution image) with line renderers and shapes.. so i understand how to make sprites mask to a basic jigsaw puzzle. i need this to be automated on a frame by frame situation
Yeah... We're telling you how to do exactly that
would take a bit of messing about to get it polished
but this would be a very easy thing to automate
oh your saying i sould make a sprite and create multiple sprites from that main one?
No you'd make a texture and create multiple sprites from it
you can make the multiple sprites from a texture
its like you already got the picture for the puzzle and the sprites are cutting the pieaces out of it
ok but i'm not seeing how i can dynamically update all the sprites to render new textures by frame
The masking bit btw would be separate from the sprite slicing. Sprite is always a rect. To get jigsaw shapes that would be another texture that has jigsaw shapes that you'd be masking the sprites with
Just... Write the code to do it
You'd make the sprites in code
With Sprite.Create
ok so its reasonable to create sprites and rewrite them every frame by using a render texture?
Why every frame?
also you could you could even have them of a video
because it is needed for a mechanic
You can render to the texture every frame no problem and leave the sprites alone, that would work fine
they are not coppies of the texture
they are referencing it
its literally a rect and a pointer to the texture
so if you modify the texture in place
Like if you want a video jigsaw puzzle that's easy enough with a render texture
the sprites will update as well
Lol, is that an original idea?
You might be onto something
I mean from this conversation yeah
Kind of interesting actually
Unlocking lots of game possibilities in my head lol
ok so yes this is essencialy what i want to do, but i need each jigsaw piece to understand its pixel composition.
Wdym by understand
You need to do some analysis on the pixels? That can be done programmatically easily enough too
Actually accessing the pixels is straightforward. Dunno what you want to do with them though
so i'll just share my idea.. so you understand a bit better.
imagine a 10x10 grid of squares. these are the jigs.
the solution image would look like an abstract shape collage.
once one of the shapes (in the main solution) is completed in the collage, the shape will shrink till it disappears, leaving the jigs to determine how they should update.
this is a very basic pitch
so the puzzle becomes "less chaotic" as you solve, leaving the player feeling some dopamine for small task completion.
imagine it like this
a puzzle of a farm with a variety of animals,
correctly placing all the "horse" pieces makes the horse disapear from the main solution, and the player 'collects' the horse as an acheivement for example.
so i need some way for the jigs to know where they belong on the main grid, as well as, the small group they belong to within the grid.
Hi, I'm not sure what this is called so I've not been able to simply google it, but does c# in Unity have that programming syntax where you only call a method on an object if that object is not null?
So instead of
if( myObj != null ) { myObj.MyMethod(); }
You can do something like
myObj ? .MyMethod()
it depends on what myObj is
if its a regular C# object sure that will work
if its somethign like a MonoBehaviour it will cause your pain later due to how unity fakes null on things
it's called a "null conditional operator" if that helps in future!
I have been stuck with this issue for a couple of hours now, and im almost bald. In my scene, i have six different gameobjects with a simple ObjectiveOnGameObject-script that lets me choose an Objective and a RoomHandler (A simple cube that i want to change color on).
The problem i got is, the ObjectiveManager can choose randomobjectives for me, and the roomhandlers connected to my gameobjects via the ObjectiveOnGameObject are changing colors to red, just as i like them to. But when the player interacts with one of the gameobjects, do use the ObjectiveManagers CompleteObjective-method, the last "used" roomhandler is the one getting a color-change to black, and not the correct one.
I have quadupplechecked so each of the six gameobjects in the pictures, have the corresponding roomhandler set in the script. The room handler is supposed to represent the room and if there is an active objective in that room so the player easily can see where there is an objective :).
See the picture below and the script aswell. What am i doing wrong?
https://gist.github.com/Lillbirro/8a2e22d06b9d4b61d7e9b5295fb29e93
there's a lot of game logic to try and understand here based on that description, but giving this a quick read i see you're modifying which objective an object points to on line 91/118, is that intended? you search by objective reference for the one to turn black, and that's the only place i can see you changing those objectives at runtime, so if they don't match what you expect in editor, i'd start there
Well, i think that they are similar since one is being used if the tag != null, and the other if its null, in the ChooseRandomObjective(string tag = null).
I agree with Simon - this is a lot of code to try to digest, and you can (should) improve a lot of the readability here: like firstly, your ChooseRandomObjective() has this huge if/else statement where most of the code within appears the same? if you're copying and pasting code you're doing something wrong - just do the part that's different within the if/else. I'd also probably read up on programming calesthenics and try to early-out in your if statements instead of wrapping all the meat in an if statement - ie:
if (something == null) return;
// vs
if (something != null)
{
// a bunch of code
}
I'd also avoid doing the foreach (var pair in activeObjects) use of 'var' because activeObjects isn't defined near the foreach loop, so it requires someone (me/you/whomever) to hold that trivia in their brain (and scroll up/down in the file to try to figure out what it is).
Don't embed classes like this unless it's an internal class (which it isn't, it's public). I get what you're trying to do but it's kind of obscuring the problem. I do like this class, but it should be in it's own file, and should probably have more data in it to identify it - like an ID. I'd also name these fields/properties properly - PascalCase and not camelCase so that lines like #99 are easier to debug and verify you're doing what you think you are. It should be activeObjectives.Add(new ObjectiveRoomPair { Objective = selectedObjective.objective, RoomHandler = roomHandler });
I'd probably also move away from your use of == for game object comparison since unity objects have overloaded operator== and it doesn't always work like you might expect (an object can exist but be destroyed and UnityEngineObject.CompareBaseObjects will return "true" for nullness. Most of the time it's the same thing, but not always.
That being all said - the code looks fine from what I can understand, but you're likely going sideways by not passing in the correct Objective in CompleteObjective, OR you've linked the wrong objective accidentally to the room handler.. This script doesn't show how your objective with tag's .roomHandler property is set.
I'd start debugging this by adding some IDs to your gameobjects, displaying the ID in-game (either via the game object .name or draw some floating text on the object itself) and either adding debug.logs to all your methods (especially CompleteObjective but also ChooseRandomObjective ) to make sure the right room is being stapled to the right objective and then go from there.
GL!
Cheers for your input, yeah this script in particullar is a huge mess, cause i think i tried to do to many things at the same time, henche the huge chunk of meat in the ChooseRandomObjective.
Ill take a step back, and see if i can approach this another way. Thanks alot for the input!
All good... Yeah, I mean, I've looked at this code for the last 15 minutes and no obvious bugs pop out to me, but .. it's written in a way that's a little hard to read.. but I mean, I think it's sound
I'd just make sure that when you add your items to the dict of lists that you're adding what you think you're supposed to be - if rooms have an id and objectives have an id, then you could just toss a line like this into the mix and you'll quickly see if you have a bug:
// Add the ObjectiveRoomPair to activeObjectives
activeObjectives.Add(new ObjectiveRoomPair { objective = selectedObjective.objective, roomHandler = roomHandler });
Debug.Log($"Added a new objective to {tag}: ObjId: {selectedObjective.Id}, RoomId: {roomHandler.Id}");
And then when you complete the objective, same deal - spit out the id of the objective, tag, and room, and make sure everything is sane
but your problem likely isn't in this script
I found another bug, perhaps
in your else statement in ChooseRandomObjective() you don't seem to be adding it to the list of active objectives
which again, is why you shouldn't copy and paste code 🙂 .. lemme refactor it for you
I think it should look more like this: https://pastebin.com/1FBBymJP
actually hang on
Anyway, you get the idea - trim all the copied and pasted code so you aren't missing something that only happens in one of your if/else blocks (unless you intend to)
I'm working on a VR game with non-euclidean architecture. For that system to work, we've created a system with different layers per room. It works great! But now I have the following issue: The scientist in this screenshot needs to be able to spot the player. In all the other levels I'm using raycasts for this, but the scientists are behind a glass window. The window will cause the raycast to be blocked. I can't set the window to Ignore Raycast Layer though, because it wont get rendered then in my current room setup. (In fact I cant change it to any other layer). Any idea on how I can solve this? It's only the windows that should be ignored.
A fun little hack is to change the layer, do the Raycast, then change it back
Including references from the scientist to all the windows he might look through? That will be messy 😩😄
do the windows need to have colliders at all, or could they just be visual?
So, I ran into a bug and reported it and it was confirmed for the Unity SRP in 2023 versions and later (it cant blit quads)
My org is kinda breathing down my neck about it because it all works in studio but doesnt work in published games - is there something I can do here?
Make them get the enterprise license and fix the bug yourself.🤷♂️
Or make your higher ups contact unity and negotiate a patch or something.
Or find a walk-around.
Yeah I jiggled stuff for a week to get a workaround, I dont think im capable of finding one
renderdoc just said "its not emitting quad geometry here" so I was like 🤷♂️
Can't help you any more than what I said without knowing the details of the issue.🤷♂️
btw, how would I be able to do a cutscene using instantiated objects?
Use https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html and sort the list to find the player
Better yet use the non alloc version https://docs.unity3d.com/ScriptReference/Physics.RaycastNonAlloc.html
I dont understand the question
If that's the right channel for your question.
I need help with my procedural world generation
It won’t take my code and there is no errors
I see you decided to ignore the suggestion of asking in #archived-code-general 😅
You were linked to the #archived-code-general channel, and you came here.
Ah I see. They also linked this channel too.
I was linked to all the code channels but I just clicked this one
Anyways, what doesn't work?
Does the code run?
Yes
wdym by "won't take my code"?
Look at the #854851968446365696 on how to ask. It shouldnt be troubling to find out what your issue is
Tbh idk just won’t run my code In unity
Does it run your code anywhere else?
And how do you confirm that it doesn't run your code?
Yes I ran the game and it did not take and do anything
then your code doesnt run, have you debug it first
Yes
I have doubts this is gonna be a code advanced question. Definitely gonna be a more "this isnt my code and idk how to run it"
Sorry about the way I worded things never good at questions
That doesn't answer my question. You say that it doesn't run your code in unity. That implies that "something" runs the code somewhere else?
No it’s my code
Yes in vs it ran with no errors
Then give short summary of what it does and where it is run from?
So I’m a little lost
You "ran it" in vs?
Yes
How?
It ran with no errors
How did you run it in VS?
Testing for errors do it with all my codes
Big like it displayed anything just ran it to see if it displayed any errors or not
How did you test for errors?
Ok now you’re confusing me
How did you run it in VS?
I clicked the start button
To run a code you need to compile/build it and execute the program. Is that what you did in VS?
In VS?
It's unity project, right?
Yes
Do you know how to run any code in unity..?
This?
Like hello world
Yes
it doesn't run the code
Yes
it is just attach a debugger not playing
It attaches the debugger
So to summarize: you didn't run the code anywhere. And you don't have a confirmation of wether the code runs or not?
What "they"?
White and red green blue yellow
Please use screenshots. It's supper annoying to try and understand anything from a photo of a screen
These look like read only or non serializable fields. What do you expect to happen with them?
Ok wait it says waves is missing the class attribute extension of native class
This is my first time coding something like this so it’s not perfect but it works still working on it
We can't help you unless you start sharing details of the issue properly. Like code and screenshots of the errors.
Check #854851968446365696 on how to ask questions properly
I’ll figure it out tomorrow it’s fine Ty tho
Maybe try a hello world first as well so you can see how to actually run code in unity
It should be extremely trivial for you to see why your code isnt running then. Since you also said you debugged it above
Watching what? A debugger?😅
reimport ur script
Presh🙏
have you changed ur script's name?
THanks for your reply yesterday, i only just saw it. So it sounds like I shouldn't use the 'null conditional operator' then , because it will cause problems with MonoBehaviour grabage collection or object lifecycle?
you can make an extension to make it work correctly if you want to use that syntax
using UnityEngine;
public static class UnityExtensions
{
public static T OrNull<T>(this T unityObject) where T : Object
{
return unityObject == null ? null : unityObject;
}
}
Then use it like:
if (unityObjectThing.OrNull()?.Func())
And you can't just use ? directly as that doesnt query the C++ side to see if the unity object still exists.
when you check with == that operator has been overridden for the Unity Object base type, so it correctly asks the C++ side:
? cannot be overridden, but the above work around does the correct check which then allows you to use ?
Like, my RPG party's charcaters are DDOL objects. How could I make a cutscene involving them, since you can't move them around with the timeline
-
Create a different object using those sprites, and hand animate them in timeline.
-
Create a robust system in timeline that will let you move the actual characters through waypoints to move or to call specific animations.
-
Do #2 without timeline and do the entire cutscene in code inside of a coroutine so you can yield to things like waiting for characters to reach a point, or for a dialogue popup to complete before proceeding to the next moment in the cutscene.
Perfectly safe for non unity objects. But yeah for unity objects you need to do a null check using the equality operator
Anyone know if there's a faster way to get the current color/size of shuriken particles 
I can't find any way to get the data besides iterating over every particle on the main thread.
Would love to at least be able to get them all in one batch. I'm open to doing weird stuff if necessary.
// So frustrating to have to do this, but we can only access each particles current color and size
// one at a time on the main thread
for (int i = 0; i < ParticleSystem.particleCount; i++)
{
_particleCurrentColors[i] = particles[i].GetCurrentColor(ParticleSystem);
_particleCurrentSizes[i] = particles[i].GetCurrentSize(ParticleSystem);
}
I'm doing this for a plexus effect and everything is nicely jobified except for getting the particle sizes/colors.
Do particle system jobs not help here?
https://docs.unity3d.com/ScriptReference/ParticleSystemJobs.ParticleSystemJobData.html
Looks like you can get current sizes, but only start colors for some reason. But if you use a custom attribute instead of color, you can get that in the job.
Or if you can make assumptions about how the color changes, like if you know the Color over Lifetime module is being used, you can get the gradient from that ahead of time and use the particle age to get the current color.
That does look like the best way, thanks!
Am I crazy or is ShaderUtil.GetShaderMessages not working at all? I have a Shader asset and it displays errors on inspector, but this function and ShaderUtil.GetShaderMessageCount returns zero
How to query shader errors and warnings that are normally displayed in shader editor?
According to this, the shader inspector uses that method to get the errors and warnings.
https://github.com/Unity-Technologies/UnityCsReference/blob/1b4b79be1f4bedfe18965946323fd565702597ac/Editor/Mono/Inspector/ShaderInspector.cs#L371
hmm, seems like the ShaderUtil.FetchCachedMessages(shader) inside OnEnable in the source you linked is essential, but it has internal scope... I called it in a debugger and indeed the message count and messages are detected properly after this
ShaderUtil.ShaderHasError and ShaderUtil.ShaderHasWarnings both call this internal method and are themselves public.
this seems like a public API bug on unity's part then
and it indeed works if I trigger one of the methods above, that trigger FetchCachedMessages indirectly
Hi all! Hoping to find some camera experts here!
I'm trying to build my own camera view type thingie (MS Paint picture attached) here but I'm lost at both ends:
A: I don't know how to build my own unity camera view where I can actually edit or modify these parameters
and
B: I don't know what kind of parameters I'd be changing to produce my desired effect.
Anyone here have a good starting point for this sort of thing? I've tried googling around but am only getting methods of moving the camera itself and not warping its viewport.
Here's what I want to do: as the distance from the camera increases on the Z axis, I'd like the view angle to bend towards the Y axis. This will hopefully produce a "rolled world" effect similar to how Animal Crossing games look. I know there are ways of moving the actual WORLD downwards to create this desired look, but that solution requires a shader on every single object in the scene and also messes with volumetric lighting. This sort of camera thing SHOULD be possible, right? I'm totally lost, though, so please let me know if you have a good starting point for this!!!
so this cant be done with camera projection alone, most games that do it are doing it via a vertex shader they use on all objects in the game, that offsets things as they get further away from the screen
the kinda stuff you can do with camera projection is really limited to what you can represent in a 4x4 matrix multiplication iirc
dang, that's the one thing I wanted to avoid
it feels like it should be easier to bend the camera than it would be to move everything but the camera, you know?
is there a way to merge multiple camera projections together? like what if I do something like this, where based on the distance from the main camera, I use the projection from a different, linked camera?
hopefully someone else knows more then me, but dont think so and not sure how you would combine that
either way where the transformation is actually take place is in the vertex shader
UnityObjectToClipPos is called in the vertex section of all shaders
its what is doing the transformation
I'm trying to avoid having to set a shader on every single object I ever make. plus the vertex shader route messes with lighting projections.
I appreciate you stopping by either way, this was helpful even if there's no easy solution
its taking UNITY_MATRIX_MVP and multiplying it by objectPos
ah, so you're saying there'd be a way to interrupt the vertex displacement portion of shader processing and handle the displacement globally?
really dont think its as big of a deal as you think to swap the shaders, the new vertex function can just be written once and included where needed
it's a huge pain in the ass, not to grouse about it too much but it's quite frustrating as a process 😦
moreover, though, my thinking was... what's easier. move the camera or move everything else. yanno? 😛
Well, matrices cannot be bent, they can only be skewed. Composing a scene using enough cameras at different depths sounds expensive as all hell
have done it before, you just automate it
if it's not possible it's not possible, I totally get that
also there is no difference between moving the camera up, and moving the geo down, all the camera projection is happening in the vertex shader to start with
its just hidden from you since its reusing the same function in all existing shaders
does anyone know either some existing resources or if theres' a unity specific way to handle UI dispatch for world space UI's? specifically it's a VR Game with several world ui "frames" and trying to finalize the design on a ui dispatch so the Ui designer can iterate in parallel to UI code being written, and they can just be wired up via id registration either via enums, strings, etc whatever. our studio has tried like several iterations on a system and there's always some major drawback that needs to be addressed, and it feels like addressing one exposes another. For example, our current system is reliant on prefabs that both coders and designers have to touch, which means we have to be diligent about locking, passing prefabs back and forth, and it's just friction we don't want.
the ideal workflow would be like, the ui designer sets up the whole UI, adds the script stubs for controlling the UI, wires up the references, adds a ui dispatch component and registers it with some ID, and the whole while the programmer is working on the controllers, and hooking it into the game logic, saying something like UIDispatch.LobbyScreen.Show(myNewViewID);
and if the artist submits their work first, no biggie, if the programmer commits their work first, it will attempt to show the UI but say, fire off a warning saying "no View Registered with provided ID" which is no problemo, and when the artist commits, it'll just work
big wall of text, but having a system like this would be unbelievably helpful. just feels like very difficult to make that full experience cohesive
Okay, I actually did a 3 camera test and I think this might work
Game View. Note the foreground higher than the background.
Scene view. Note the cubes and planes on the same axis
not entirely sure what you're trying to accomplish exactly. read your previous messages. you want something like
crap. like the end scene of the matrix where neo is bending the walls?
I want something like Animal Crossing: New Leaf, where the world appears to roll as you walk across it. Right now all of the places I look are suggesting that I write a depth-based shader that does vertex displacement, which has its own problems display-wise and doesn't actually produce the exact effect I'm looking for.
Here's another MS paint drawing. As you can see, displacement produces some weirdness that I don't want. Plus it's a huge pain in the butt to have to attach a shader to everything. And it messes with lighting.
hmmm I probably will need 1 camera per pixel to make this look smooth
so multi cam overlay approach... probably not feasible
You can do the latter in a vertex shader
There's nothing stopping you from doing any distortion you want apart from the number of vertices
Please kindly help me, I want to find out how I can make a better save/load system. I don't know, I've tried my method. Does anyone have examples or can give me concrete advice?https://gdl.space/cetetehipi.cpp
not sure if it is code advance or general, btw
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
```this is how dictionary stores the key and value, you can ignore the next field, it is just pointer of linked list
https://github.com/microsoft/referencesource/blob/master/mscorlib/system/collections/generic/dictionary.cs
why
string jsonValue = JsonUtility.ToJson(value);
if (!data.ContainsKey(key))
data.Add(key, jsonValue);
data[key] = jsonValue;
Also why Dictionary<string,string> instead of Dictionary<string,object> and leave all the serialization to the Save method
how to refernece CinemachineVirtualCamera in code? I tried using Cinemachine and using UnityEngine.Cinemavhine, non is working
The Namespace is Cinemachine, if VS is not picking it up you may need to Re Gen your project files
can you please give me an example, maybe I don't see the general concept, or I'm getting confused at the moment, I apologize
I simply wondered why, when you have a new key you add the key/value and then you update the value with the same thing
also if you use a Dictionary<string,object> there is no need to update the dictionary at all
Hello, I'm trying to address something when it comes to creating maps for my game: You need to make a scene, seperately. I was thinking of making it so that when I create a ScriptableObject ScriptObject_Map, it'll automatically creates a scene asset and attaches itself to it. I know how to do that, however, there doesn't seem to be a simple solution for ScriptableObject OnCreation or so, and some people online were saying I should use Awake when creating an asset, and then switch a private variable to true and have the awake set to stop if it is true, but I am not sure if I should 100% do that
At some point you have to do a ScriptableObject.CreateInstance/AssetDataBase.Save to create the asset. There's your oncreation right there
How would I call that?
normally SO's are created via a menu option
I meant more like
It should be a function called within the scriptableobject file itself, yes?
normally yes, with a Menu attribute
Does anyone know what's wrong here? I have everything installed as can see, but when compiling I get some errors.
The first error is below, and the gradle erroris attached as a TXT file
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':unityLibrary:mobilenotifications.androidlib:compileReleaseAidl'.
> Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-33 Android SDK Platform 33
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html
Using Android SDK: C:\Program Files\Unity\Hub\Editor\2022.3.20f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2m 57s
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
Second error is attached as TXT file due to the length
https://cdn.discordapp.com/attachments/497872424281440267/1208695289813139466/image.png?ex=65e43835&is=65d1c335&hm=1a354e29fa8708264ffe28c3f0035fbed31b59352743ee9e38566aa1716777f3&
Do NOT cross post, chose the relevant channel and stick to it
What an interesting problem! It indeed seems hard and there could be many approaches. Doing some kind of space transformation in vertex shader that you include in other shaders seems to be the most foolproof way to bend vertices of geometry. Using some rotation around a far radius on the -y axis should do the job.
Alternatively maybe something like division not by z by z² (?) using some advanced perspective projections of homogenous coordinates. But then I bet there is no simple way for your shader to automatically perform perspective divide and you would have to do it yourself.
I am not sure if that's simply possible with matrices
It might be difficult to explain, so here is a graphic:
what you could possibly need is a space transformation, that would work as a "curved frustum"
it would be up to you to limit the portion of this "bent frustum"
for example only to the upper half
something a'la discard the red part
but.. well, this is how it would probably look like, it could make it seem to as curved but bend weirdly
personally I think that's a big gamble if that would work and if this was even a) easy b) performant c) maintainable
imo bending coordinates in vertex shader could be better
how can i implement camera collision?
how would i go about recreating this type of destruction in unity??
and i dont mean just chop the wall up into small peices, i mean make it procedurally fracture the wall when i shoot it
https://www.youtube.com/watch?v=Q5gdOfH7bIw&ab_channel=GAMEPHYSICSBYDNMN
#unrealengine #rainbowsixsiege #videogames
Today I kept on testing Next Gen Destruction and layered multiple destructible walls. Almost looks like Rainbow Six Siege's destruction system...
Pretty happy to create own assets with it that I'll be using in my game.
Video test made by DNMN (c) 2023.
https://gitlab.com/dima13230/unity-libre-fracture or https://github.com/dgreenheck/OpenFracture or buy https://assetstore.unity.com/packages/tools/game-toolkits/rayfire-for-unity-148690
I’ll check these out later because it’s 2 am right now but Ty
Honestly your best bet is just to buy rayfire
Fracturing is easy, its the clustering and structural destruction that is hard
that might work as well! I'm reading up on multi camera compositing, I think if I can get the views of foreground/midground/background to merge it'd work... but would have a "crease" instead of a bend
Just have in mind that multi-camera compositing could be an equivalent of x3 rendering performance penalty
hmmm, that's a very valid concern
Okay, further updates. I'm poking around in URP's fullscreen post-processing flow. I think I can potentially do vertex displacement as a fullscreen shader. That being said, even my test material/shader isn't applying. Is there some step I'm missing here?
This is not possible purely in the camera, because you can't create a non-linear projection matrix. This is a limitation of GPUs. They can't render curved lines. They only render triangles with straight edges. So the only options are to either estimate it with vertex displacement, like Animal Crossing does, but then you need enough vertices to estimate curves, or you can bypass the triangle rasterizer entirely and render everything in the scene with something like raymarching.
I have the following function, where I grab the data computed by my compute shader.
{
if (output != lastCallStreamoutput || writer == null)
{
if (writer != null)
writer.Close();
writer = new BinaryWriter(output, System.Text.Encoding.UTF8, true);
lastCallStreamoutput = output;
}
AsyncGPUReadbackRequest requestPos = AsyncGPUReadback.Request(particlePositionBuffer);
AsyncGPUReadbackRequest requestTem = AsyncGPUReadback.Request(particleTemperatureBuffer);
// Debug.Log("Starting data request");
yield return new WaitUntil(()=> requestPos.done && requestTem.done);
try
{
posDataBytes = requestPos.GetData<byte>();
temDataBytes = requestTem.GetData<byte>();
// Debug.Log("Data received. pos data:"+posDataBytes.Length+" bytes temData:"+ temDataBytes.Length+" bytes");
writer.Write(posDataBytes.ToArray());
writer.Write(temDataBytes.ToArray());
}
catch (System.Exception e)
{
Debug.LogError("Exception thrown will reading GraphicsBuffer data, or writing to file: " + e.Message);
}
// Debug.Log("Data written to fileStream");
}```
The code waits until the AsyncGPUReadbackRequest’s are “done”, but still, very occasionally (I’d estimate less than 1 in 500 runs), it generates the following exception:
``Exception thrown will reading GraphicsBuffer data, or writing to file: Cannot access the data as it is not available``
Any thoughts on what might be causing this- how to avoid it? Am I checking that the data is ready improperly?
good info, thank you!! Any idea on why my post-processing isn't post-processing?
which line throws the exception?
not actually sure, my console shows the Debug.Log line, AFTER I caugt it, but I'd assume one of these : posDataBytes = requestPos.GetData<byte>(); temDataBytes = requestTem.GetData<byte>();
ah... well you can see the stack trace in the error message
you are waiting until both are complete, but the data is only available for one frame. Unless they both always finish on the exact same frame, one of those GetData calls will fail
hmm.. it doesn't.. lemme try Debug.LogException instead.
I dont understand. The compute shader computes both those arrays as output in a single pass.
Empirically it appears that's what's happening though
Agreed, but I dont see how. I wait until BOTH array are ready- or I though I did.
and that's the problem
unless they finish on the EXACT same frame, you are guaranteed that one of those GetData calls will fail because the data has been lost by that point
hmmm,, if that's the case how does it EVER get pst this line: yield return new WaitUntil(()=> requestPos.done && requestTem.done);?
499 out of 500 times, they finish on same frame
and when the dont.. why doesn't the && make the result false, and not let it pass?
(sorry I'm not usually this thicl)
because they are both done... one of them was just done earlier (previous frame), so data is no longer available 🙂
let me repeat: when AsyncGPUReadbackRequest is complete, you have one frame to access the data. You can't wait for anything else https://docs.unity3d.com/ScriptReference/Rendering.AsyncGPUReadbackRequest.html
"so data is no longer available" but .done remains true? ok- that I was not expecting.
thanks guys I'll re-code it to grab EITHER one thats ready, and THEN wait till both are done before "finsihing".
+1 thanks from me, I didn't know it's only available for a frame 🙂
newver @long ivy@fallow echo https://hatebin.com/zauhventyu gonna give this a go now- thanks again!
I think I'll take a crack at making a guitar hero type game. If anyone has good resources on the best way to go about it. I'd prefer no videos. Also I haven't worked with fmod but I know it adds some audio versatility. If that's something that would be helpful
Hi, I'm looking for some advice on Meshes (I'm new to this 🙂 ) - I am generating two faces to fill the end of a bezier path as shown. I originally had an issue where the normal of the second face, was drawn rendering inwards towards the path. I solved it by reversing the order of the triangles, but unsure if this is a good or bad practice with meshes? Thanks
Nothing 'bad practice' about that. Triangles indices need to be in clockwise order.
Relative to the path, the start face and end face should indeed be in different orders
You are doing it correctly
Cheers. Although I'm not clued on the Bezier maths just yet, this appears to always work for any path I draw :). I assume unity will render counter-clockwise ordered vertices in the opposing direction? Thanks
Yes, or well, it will completely skip triangles that face away from the camera
I see
If you are new to working with meshes, this is a decent resource https://catlikecoding.com/unity/tutorials/procedural-meshes/
Google failed me, GPT is useless as always - Discord, can you help me?
I want to read values out of a depth texture of a specific camera. I'm on the builtin render pipeline btw.
So I have multiple cameras and I only care about one of them. And I want to shoot raycasts, but my obejcts can't have colliders, they only have depth.
And instead of rendering the whole scene with a custom shader again, which costs a lost, I just want to grab the depth texture and read there.
It's OK to copy values over to another texture using Graphics.Blit() or something.
This doesn't work:
using UnityEngine;
public class DepthTextureReader : MonoBehaviour
{
public RenderTexture depthTexture;
public Texture2D depthTexture2D;
private void OnPostRender()
{
depthTexture = Shader.GetGlobalTexture("_CameraDepthTexture") as RenderTexture;
if (depthTexture == null)
{
Debug.LogError("depthTexture is NULL");
return;
}
int width = depthTexture.width;
int height = depthTexture.height;
if (depthTexture2D == null)
{
depthTexture2D = new Texture2D(width, height, TextureFormat.RFloat, false);
depthTexture2D.name = "depthTexture2D";
}
else if (depthTexture2D.width != width || depthTexture2D.height != width)
{
depthTexture2D.Reinitialize(width, height);
}
RenderTexture.active = depthTexture;
depthTexture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
// Access depth values (example: print the depth value at pixel 100,100)
float depthValue = depthTexture2D.GetPixel(100, 100).r;
Debug.Log("Depth value at (100, 100): " + depthValue);
}
}
can any one help me with my cosmetic script
#854851968446365696 Please provide all the required context
So basically every time i try to use the script it never works, im making a fan game. It always has errors, and when some scripts dont give compiler errors, they dont work as they supposed to. The cosmetic that is supposed to come to my hand when i click a button doesnt work.
This is not an advanced issue. Configure VS so you get error highlighting, and post in #💻┃code-beginner
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
okay thank you
is there a function or a delegate what execute when you duplicate or copy/paste a object in the scene view?
https://docs.unity3d.com/ScriptReference/EditorApplication-hierarchyChanged.html not sure if this is what your looking for- this class has a bunch of other events too.
thx i found something different
ObjectChangeKind.CreateGameObjectHierarch
interesting.. looks tricky- do you have to moniitor the ObjectChangeEventStream with that?
yeah indeed you get a stream where you can get the object from that
Does anyone know of any 3D Delaunay tetrahedralization libraries/plugins? I need to find all non-overlapping triangles/tetra between a set of 3D points. There's lots of stuff out there for 2D Delaunay triangulation, but I can't find anything for 3D
Dont know any libs for that. Getting a set of non-overlapping triangles from a random set of points could potentially lead to many solutions, at least if you ONLY have points- or do you have a mesh?
I have exploited lightprobe tetrahedralisation before I think...
There's
https://docs.unity3d.com/ScriptReference/Lightmapping.Tetrahedralize.html
but editor only.
Man, soon as I get over my impostor syndrome, you guys post something like that and boom, I'm back to "you know nothing Jon Snow". What does the lightmapping stuff do with with/ why does it need, tetrahedrons? To best light the center of it?
There was a GDC presentation about it. Unity has a unique solution for handling light probes by using tetrahedrons and barycentric interpolation. It's a good presentation.
https://www.gdcvault.com/play/1015312/Light-Probe-Interpolation-Using-Tetrahedral
Naive light probe solutions use uniform grids to quickly find the nearest probes and interpolate between them with trilinear interpolation. But that means you can't hand place probes in the scene with more density where it matters. Quickly finding and interpolating between the nearest probes when they are arbitrarily placed is a more complex problem. Unity solved it with tetrahedrons.
It's the reason why Unity draws these lines when you have a Renderer selected in a scene with light probes. It's visualizing the four vertices of the tetrahedron the renderer is contained in.
@abstract folio Just points. As a super informal definition, I want to do something similar to 2D delaunay triangulation (see gif) in 3D, but instead of finding a 3D hull, I want to "fill" the 3D hull with tetra so I can find non-overlapping triangles and lines between the 3D set of points. It does sound like how Unity tetrahedralizes light probes for interpolation is basically what I'm looking, tho my use case likely makes piggy-backing off of that functionality difficult.
@sage radish @austere jewel Thanks for pointing me at the light-probe thingy. Unfortunately my use-case involves running this over a set of points from an arbitrary particle system, so it needs to work on a changing set of points at runtime which is probably not what Lightmapping.Tetrahedralize is meant for? For further context, I want to use this to find facets/lines connecting the points for a realtime plexus effect. I have the lines working using a nearest-neighbor search, but I also want to draw triangles connecting the points. I tried doing nearest-neighbor for this as well, but it was quite messy/erratic. I figure if I use delaunay tetrahedralization I could use the data for lines and triangles. And it would be more stable and provide flexibility in how it's rendered. Tho this may be unfeasible/beyond my ability to pull off performantly. Either way, thanks for taking a look yall 🙂
Reference: https://youtu.be/cbO4VsXUVZM?t=302
One fast way to quickly create awesome motion graphics for your projects is by using Plexus in After Effects. Plexus allows you to easily create a spectrum of lines and dots to design sci-fi compositions. I normally don't use plugins in my tutorials, but this tutorial will be helpful when you do use this plugin. It's fun to use and there are man...
Maybe you could convert a 2D Delaunay triangulation implementation to 3D. This one looks promising:
https://github.com/andywiecko/BurstTriangulator.
It'll probably be a bit more work than just Find & Replace float2 -> float3, Circle -> Sphere, but my understanding is that the underlying algorithm being used here (Bowyer–Watson) works for any dimension.
Or maybe it's just easier to implement the algorithm from scratch.
Thanks for the link, I'll take a look 👍
Does IL2CPP, optimizes typeof(T) == typeof(U) when one of both is a value type?
typeof() returns Type which is a class. Though if those are generic type parameters, the compiler is smart enough to sometimes elide entire blocks of code where the condition cannot be true.
In CLR, I can do for example typeof(T) == typeof(U), and the JIT is able to replace that with a constant boolean if at least one of both is a value type as the methods are specialized. But I don't know if Unity does the same
For example, if (typeof(T) == typeof(int)) is automatically propagated
Making it zero-cost
Good question, and there's probably not much impact. Are you experiencing a performance drop on that very specific part?
No => Don't worry about it
That depends if you are using it in a hot path
So that would mean "no". Compilers are smart and you shouldn't worry about these. IL2CPP may not do optimizations itself, but whatever it uses after that to produce machine code would surely get rid of the unnnecessary code paths.
If i am using a tilemapcollider with composite collider, is it possible to get the "composite piece" i collided with in script?
aiming to get coordinates of rectangle corners
I would say it depends on which IL2CPP code generation option you are using. If you're using this option:
https://blog.unity.com/engine-platform/il2cpp-full-generic-sharing-in-unity-2022-1-beta, then value type generic instances will share the same code, so the compiler cannot optimize this sort of comparison. Whereas if you are using the other option, IL2CPP will generate a separate C++ class for each value type generic type, where the compiler might be able to spot this sort of constant expression. But that depends entirely on how IL2CPP implements the typeof expression.
You can inspect the IL2CPP code that is generated in the debug folder that is generated with your build.
I want to be able to set the depth buffer based on my 2d sprites to order them correctly. Can you help?
Should I use SRP and write custom render pipeline?
Using sort order by axes does not work very well.
I want to consider my 2d sprites like a 3d object when rendering
it sounds like this might be a lot easier if you could just use 3d objects then 🤔 why do they have to be sprites?
Hello, I have a question. I have a prototype I want to test on my phone so I started android build. I have a pretty powerful pc but I have never had build take this long. The project is fairly small so It makes no sense to me why it is taking so long. It is the first build of this project but still. Any ideas? Unity is 2021.3.0
Unfortunately, it is not my decision
I agree with you. Surely, 3d objects would be OK
I should mention sprites I mean 2d items have known 3d size and I want to use it and calculate depth value for each pixel and update depth buffer.
The game is a side game with 2d sprites with almost isometric shape. You can see top surfaces.
Items can be placed on top of each other
hey y'all, who's familiar with Behaviour Tree, Behaviour designer in unity, i need help
sorry yeah wait
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
using Character.ScriptableObjects;
using Character.Survivor;
using MoreMountains.Feedbacks;
using System.Collections;
using UnityEngine;
namespace NPC.Tasks.Killer
{
public class Attack : Action
{
//[SerializeField] private PlayerStatus _playerStatus;
public int liveCount = 2;
public Transform Killer;
public KillerChase killerChase;
private bool isAttacking = false;
public override void OnStart()
{
killerChase = gameObject.GetComponent<KillerChase>();
Killer = GetComponent<Transform>();
//_playerStatus = gameObject.GetComponent<PlayerStatus>();
}
public override TaskStatus OnUpdate()
{
RaycastHit hit;
if (Physics.SphereCast(Killer.position, 4f, Killer.forward, out hit, LayerMask.GetMask("Survivor")) && isAttacking == false)
{
StartCoroutine(Attacking());
Debug.Log("Attacking");
return TaskStatus.Running;
}
else if (killerChase.distance > 4f && isAttacking == true)
{
isAttacking = false;
return TaskStatus.Failure;
}
if (liveCount == 0)
isAttacking = false;
return TaskStatus.Success;
}
public IEnumerator Attacking()
{
while (liveCount > 0)
{
isAttacking = true;
yield return new WaitForSeconds(3f);
liveCount--;
Debug.Log(liveCount + "hearts left");
}
isAttacking = false;
}
}
}
Why is my liveCount decreasing at the start of the game, even tho the action attack wasn't called yet
also when liveCount is less than 0 the attack action keeps running
also, liveCount decreases like crazy, like 40 times a second
this is a code-beginner question - your liveCount is decreasing because it's public and serialized in the inspector
i don't know exactly what OnUpdate is from the task library you imported, but if it's not synchronized to unity's update cycle it's.. gonna run many times before the unity coroutine does
nothing in your code here looks like you need another library.. this is just pretty basic programming.. put all that junk in the overridden methods into Update() and Start() and clean it up and it should work just fine: make the public liveCount private, put brackets around your if statements, etc:
if (liveCount == 0)
isAttacking = false;
return TaskStatus.Success; // No!
lastly - just a unity discord thing.. learn how to paste large code blocks or someone less kind than me will .. tell you. 🙂
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm a boomer, thanks anyways
no excuse? i'm 45, that's boomer territory i think
That's on the young cusp of Gen X (44 to 59 in 2024)
Boomers are 60-78
You're closer to a millennial (28-43) than a boomer 😸
gasp, insults
I suppose I identify more as a boomer since .. offtopic, I play "boomer jund" in MTG. Bob/Lily for life.
Doesn't change anything you said though haha
(I hear "OK boomer" at least once a week)
who cares about the labels, especially in a domain like programming
Oh I was just teasing. It only came up because the user above used being a boomer as an excuse
#archived-code-advanced message
i'm not i was just kidding btw
being a real boomer is not an excuse, it's a badge of honour
#📦┃addressables would be the best place to ask
Cam we Implement a custom Depth test in srp?
Is unity server down? i cant log in on unity hub on linux they say the servers are unresponsible, tried to download a new version of the hub and turns out that the unity hub download page is unavailable.
I can log in on windows tho
Not a code question, check Unity Status https://status.unity.com/
Authentication was down, but got resolved 4 hours ago.
Unity Services's status page provides information on the current status and incident history of Unity Services.
Sorry for wrong chat question. I'm still trying and isn't working by the way.
Can you try hitting the public API endpoint that returns the available editor versions?
https://services.api.unity.com/unity/editor/release/v1/releases?limit=1&offset=0
See if you get a success response as well as some valid JSON
Is that the expected output?
Also: Im trying to login on unity hub on linux and its saying me the servers are unresponsive, Cant run my research experiments bc of a license validation on a online server. On my windows devices tho is working fine but I need access on linux hub. The download page of unity is also down.
Yeah I get the same data. Seems like a Linux issue if it loads fine from Windows. I confirm that the Hub download page is accessible to me (win 10)
For me it shows the hub download like that:
Actually just accessed it, the hub, had to install other version that wasnt compatible , had to instal a library and install a most recent version of the hub in order to access it Much appreciated for the support @fresh salmon 🙂
anyone know how to implement your own OnComplete type thing, i have avoided coding these my whole time, not even sure what its called, a delegate maybe
something like: StartCoroutine(doAPIAction(() =>
{
Debug.Log("onComplete");
}));
and doAPIAction might be IEnumerator doAPIAction( Action onComplete)// = null)
{
_("doAPIAction");
yield return new WaitForSeconds(2);
onComplete.Invoke();
}
the idea is that once the doAPIAction is finished it calls the code where i have printed onComplete
just looking for docs but hard to search for when u dont know the terms 🙂
sure you pretty much had it in that latter one
pass in a delegate
call the delegate at the end of the coroutine
thanks! yeh but im getting a null somehow
wdym by "getting a null"?
at least i know what its called now
in the console it shows nullReferenceException at this line StartCoroutine(doAPIAction(() =>
NullReferenceExceptions are always the same
Since we're in #archived-code-advanced i would expect one to know how to investigate and solve them tbh
trust me i do but i have never tried to use delegates
you are dereferencing a null reference on that line
i cant understand what is null
been a long time since i used a debugger 🙂
On that line nothing can be null so either your actual code is something else or the error comes from a different line
if you're doing all this in a one-liner, it could either be in the actual StartCoroutine line OR the lambda itself
Show the actual code and the full error message
hard to say without seeing the actual code and error yea
pretty much just this https://pastebin.com/msKqPYPp
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.
Looks like you';re creating a MonoBehaviour with new based on this little snippet
yeh that is the code, error is NullReferenceException
UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at <cd86b0d4df634b6a8fd612065f941dcd>:0)
FlowValetSDK.login () (at Assets/FlowValetSDK.cs:27)
FlowValetMain.doLogin () (at Assets/FlowValetMain.cs:21)
UnityEngine.Events.InvokableCall.Invoke () (at <cd86b0d4df634b6a8fd612065f941dcd>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <cd86b0d4df634b6a8fd612065f941dcd>:0)
UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
that's a big nono
oh yeh!
lol.... forgot it was a mono
thanks
perfect it works, been shying away from that syntax for ages
Hey guys. I've been looking for a method that loads all assets from a folder but I haven't found one.
So I've made my implementation. What do you think? Is it optimised?
private T[] LoadAssets<T>(string path) where T : Object
{
string[] foundAssets = AssetDatabase.FindAssets($"t: {typeof(T).Name}", new[]{ path });
string[] assetPaths = foundAssets.Select(AssetDatabase.GUIDToAssetPath).ToArray();
List<T> result = new List<T>();
for (int i = 0; i < assetPaths.Length; i++)
{
var loaded = AssetDatabase.LoadAssetAtPath<T>(assetPaths[i]);
if(loaded is not null) result.Add(loaded);
}
return result.ToArray();
}
there's a lot of unnecessary copies and allocations here, it's editor code so it doesn't matter too much but there's lots of room for optimization
So I can use LINQ Chaining to prevent unnecessary allocations?
LinQ does not work that way
well, you are collecting stuff to an array unnecessarily, so you could save a bit of allocation that way, but it's not just that
How about this?
public static T[] LoadAssets<T>(string path) where T : Object
=> AssetDatabase
.FindAssets($"t: {typeof(T).Name}", new[] { path })
.Select(s => AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(s)))
.ToArray();
OMG. May I suggest, as you seem to be concerned about performance and memory, you learn how c# actually works
that's better than the previous version, you're missing your null check from before though
collecting to an array is generally less efficient than a list, so i'd probably make it return a list
this optimization is probably completely irrelevant compared to the cost of actually loading an asset from disk though
But list has an array under the hood.
right, but you need to know the exact size to allocate an array, so ToArray is building a list out of your sequence of unknown length, then allocating a new array to copy the results into
@umbral bloom One thing you need to learn, writing less code, which is what you appear to want to do, actually usually means writing less efficient code
"It's 2020 outside and everyone is using .NET Core 3.1 so I decided to run some benchmarks with Benchmark.NET.
TL;DR: ToArray() is better performance-wise and does a better job conveying intent if you're not planning to mutate the collection"
https://stackoverflow.com/a/60103725
maybe it is faster these days, but you'd have to benchmark this in unity which is very much not using the latest and fastest version of .NET 😅
actually that answer also corrects itself too:
the accepted answer is actually correct: ToList is faster in the general case, because it doesn't have to trim the empty space from the allocated buffer.
The results confirm that ToList is in most cases 10% - 15% faster.
Let me do some benchmarks for netstandard2.1 moniker
Notice that .NET Standard 2.1 implements .net Core 3.0, 3.1, 5.0, 6.0, 7.0, 8.0
you'd probably want to test using unity's specific version of mono
What should I use for testing (benchmarking) purposes? UTF?
there is the performance testing extension for unity tests, don't think i've used it myself though
Ok, so here are results:
ToList() tests:
Test #1: Time = 00:00:00.0229824
Test #2: Time = 00:00:00.0027152
Test #3: Time = 00:00:00.0023752
Test #4: Time = 00:00:00.0020658
Test #5: Time = 00:00:00.0020083
Test #6: Time = 00:00:00.0018940
Test #7: Time = 00:00:00.0018348
Test #8: Time = 00:00:00.0018031
Test #9: Time = 00:00:00.0020304
Test #10: Time = 00:00:00.0022544
ToArray() tests:
Test #1: Time = 00:00:00.0235454
Test #2: Time = 00:00:00.0026466
Test #3: Time = 00:00:00.0021596
Test #4: Time = 00:00:00.0018184
Test #5: Time = 00:00:00.0018447
Test #6: Time = 00:00:00.0021216
Test #7: Time = 00:00:00.0018633
Test #8: Time = 00:00:00.0017630
Test #9: Time = 00:00:00.0018470
Test #10: Time = 00:00:00.0022610
Stopwatch stopwatch = new Stopwatch();
StringBuilder sb = new();
sb.AppendLine("ToArray() tests: ");
for (int i = 1; i <= 10; i++)
{
stopwatch.Reset();
stopwatch.Start();
var loadedPrefabs = AssetLoader.LoadAssetsToArray<GameObject>(pathToMaps);
stopwatch.Stop();
sb.Append("Test #").Append(i).Append(": Time = ").AppendLine(stopwatch.Elapsed.ToString());
}
EditorUtility.DisplayDialog("Performance testing", sb.ToString(), "Ok");
The same i did for ToList() method.
@stuck plinth
Hey everyone,
I'm currently working with colliders in my Unity project and I'm trying to implement a system where I use callbacks to trigger certain actions when objects enter or exit a collider. However, I seem to be encountering an issue where the callbacks are being invoked, but nothing is happening in my scene.
Class 1 :
Action<InteractableBase, bool> _action;
public void Init(Action<InteractableBase, bool> action)
{
_action = action
}
private void OnTriggerEnter(Collider other)
{
if (!Utils.Helper.CompareLayerMask(other.gameObject, _layerMask)) return;
if(other.TryGetComponent(out InteractableBase interactable))
{
_action?.Invoke(interactable, true);
}
}
Class 2 :
private void Start()
{
inRangeInteractionCollider.Init(ManageVisible);
}
private void ManageVisible(InteractableBase item, bool add)
{
item.IsVisible(this, add);
}
Any insights or suggestions on what might be causing this issue would be greatly appreciated! Thanks in advance!
please insight me 🥹 🥹
hahahaa
no.....have you checked the method is being invoked first
@tiny pewter yeah it as been invoked
but it never enter in the method :
but i think i correctly setup everything so i dont understand
What does IsVisible do though?
how are you calling a private method from a different class?
you can by passing it as Action
I meant this
private void Start()
{
inRangeInteractionCollider.Init(ManageVisible);
}
Init is private
oh sorry i mess up when i was writting this message (i rewrite the method for more visibility)
it change an UI element
but guys i think i found the error
I didn't want to polluate my scene so did that :
GameObject visibleCollider = new GameObject("Visible Collider");
InteractionCollider visibleInteractionCollider = visibleCollider.AddComponent<InteractionCollider>();
visibleInteractionCollider.Init(visibleDistance, interactableMask, ManageVisible);
Instantiate(visibleCollider , _orientationTransform);
yep, that would do it
it made dupplicates, may be some reference got lost lol
you need to use a delegate so you can add to the action rather than replacing it
do you have an example sorry 😄
No idea why, but when I try to add a row to DataTable, it seemingly violates the uniqueness constraint on a column. I have a bunch of classes inheriting from base class Property, and when I try to add second property, it throws:
ConstraintException: Column 'property' is constrained to be unique. Value 'me.tooster.sdf.Editor.API.Property`1[System.Single]' is already present.
what's going on?
It's worth mentioning that I only used DataTable for the first time yesterday
here is how I currently set the table up:
DataColumn propertyId = new()
{ ColumnName = "property", DataType = typeof(Property), Unique = true, AllowDBNull = false, ReadOnly = true };
DataColumn propertyControllerColumn = new()
{ ColumnName = "controller", DataType = typeof(Controller), Unique = false, AllowDBNull = false, ReadOnly = true };
DataTable propertiesTable = new DataTable("properties")
{ Columns = { propertyId, propertyControllerColumn }, PrimaryKey = new[] { propertyId } };
// later
foreach(var controller in controllers)
foreach(var property in controller)
propertiesTable.Rows.Add(property, controller);
so if the uniqueness is not determined by reference, then by what is it determined?
is is serialized in some way?
by toString()?
maybe the type's IComparable or IEquatable implementation?
that's how most system libraries work
I'm not sure if I'm even using a proper tool for the job. The data I have mostly fits "something like a table", because there are a bunch of other columns, so using a bunch of Dictionaries seemed weird — I also wanted to perform some sort of joins and use the feature of auto-incremented primary key.
Usually, you do not want to use Database locally because it goes agaisnt OOP principle.
But, yeah, usually.
the Property and derived classes are pretty basic and don't implement any IComparable or IEquatable directly, the only thing that might be of concern is possible [Serializable] annotation, but I will see in a jiffy if that's the core of the problem
i would expect for something used as a table index you'd probably need to make it comparable anyway, if you haven't implemented it that might be why you're getting false duplicates
I am not using a db locally, I just wanted to store runtime important data in "something like a database" in memory, in the simplest way possible
I mean, not exactly sure how you are phrasing it but it really seem like a simple save system.
Are you having multiple people using the same database ?
it's rebuilt either way (for now) each time a hierarchy changes (used in editor only). My main and only use case was to store and access cached data from a hierarchy of game objects and their components
only me, and it's only a single DataTable, used for a single component running in the editor
maybe more info on why I even try to use it:
Yeah, exactly my points. I feel like the database is way overkill. Why cant you not just use POCO ?
I have a game objects with a script that defines a kind of "root". There are a bunch of child game objects with some kind of Controller derived component, and "root" collects them in the editor, assigns some unique data for each one (like a unique but human-readable ID for each one), a cache of all properties defined by children and which child defines them (for quick access), some metadata for them as well (again some unique under the root, human readable ID, an auto-incremented ordinal number for each one) and possibly other things as well. So I tried modeling it first with a bunch of Dictionaries/HashSets and POCOs, but looks like a bunch of them have to be created and some things have to be done manually. For example sometimes I want to quickly lookup by Controller instance, but other times I need to quickly look up by Property. This looked like a good use case for DataTable with primary keys, especially when I sometimes would need to join the data like Controller x assigned property IDs
Unless I'm missing some context, your querying requirement doesn't require anything specific of database, LINQ works regardless of the underlying storage.
yeah, I'll use regular dictionaries/sets and POCOs instead of DataRable for now. I'll them until I learn more about them.
Given a NavMeshPath, how can I know if it contains OffMeshLinks?
I can only thing of one way, calculate the path twice, once with links enabled and once without and compare the paths generated
That is terrible 😨
haha
Is there any other way?
yes, it is
I thought about using NavMesh.RayCast on each corner and if there is a hit, then there is a link. But that is not perfect and I noticed several false positives and positive falses.
well, yes, but it's even worse
What thing?
check every corner in the path, find the corresponding gameobject and then check for a NavMeshLink component
How do I find the corresponding gameobject?
I guess I should take the start, end point and width of each link and check for each point it it's in the start or end line of the link?
That sounds kind of expensive and error prone?
expensive, yes, error prone, not so much, worth doing it, I doubt it
Ok
question. why do you want to know this?
Then it won't take me much time because I already have a code that does that to get the NavigationLink (custom class of mine) from a OffMeshLinkData. So I should adapt it a little
When my enemies patrol, they move to random locations, but I don't want to move then to a random location if that requires jumping. Instead I want get a different point.
then just set the agent to not use navmeshlinks, then you will get a partial path back if links are necessary
- How do I make
NavMesh.CalculatePathto not use links? - My links also contains custom data, so I don't want to just know if it has a link, but which one, so I can read tha data and take decisions with it.
tbh what I would do is add a trigger collider to your links and then let that tell you if it's been hit
I want to know this before getting hit. I want to know if during the planning of the path
not possible unless you implement a custom version of A*
my first option might be your only solution but even that wont work if there are multiple links to traverse
I will iterate over each corner of the path, and iterate over each navigation link and check if the start and end point are in the start or end lines of the links
I remember reading somewhere that you can store the link positions in a List and then check each path corner and see if they match any link's position
Haven't tried that myself but it's worth a try
Yeah, that is what I will do
Oh I missed your latest message, sorry
hey guys, i made an android game and i wanted to publish it on google play store, but when i tried to put the aab file it says that its bigger than 200 mb and doesnt let me, to avoid this i now use addressables, but now i want to get the addressables from a server, is there a way to use addressables with play asset delivery ? if not can anyone help me make the unity cloud content delivery work ? i have made the code to load the addressables and stuff i just need help with getting it from the server, its giving me an invalid URI: invalid port specified, even though i chose the correct loadpath that unity gave me in the addressables profile
do not cross post
I'm making a multiplayer game and I can't use any singletons for my WorldManager instances because the server unity instance has multiple worlds loaded and running in parallel. I'm thinking of just having every gameobject call FindObjectOfType<WorldManager>() to get their scene's local WorldManager but i feel like there is a better way I'm just not seeing.
Hi all,
I'm working on a custom package, it has 2 dependencies; Input System and TextMeshPro. I've successfully got the package downloading the dependencies, however, it appears that the files know nothing of the packages. To address this I have added GUID references in the assembly file. (Unity.InputSystem, and Unity.TextMeshPro). This resolves the TextMeshPro errors, but I am still getting an error for the Input System ( error CS0246: The type or namespace name 'PlayerInputActions' could not be found (are you missing a using directive or an assembly reference?)). For context I had developed this in the Assets folder successfully, then moved it into the packages directory which has caused these issues to show. I've also got it setup on github so I can use git url to install it.
Are the gameobjects created by the worldmanager?
is PlayerInputActions not your own class generated by the new Input system?
Are you sure "PlayerInputActions" isn't a generated c# class from your input actions asset? because I don't think anything in the inputactions system uses that exact type or namespace.
ah yeah, I think you guys are right 😅
I had it in the samples folder 🤦♂️ I guess this just shows that my package still needs some work. Thanks!
They aren't, but I have considered instantiating all the gameobjects through the worldmanager and then having it assign itself to them something like
Transform newObject = Instantiate(prefab)
newObject.GetComponent<IWorldObject>()?.SetWorldManager(this);
Maybe you could create an event within your spawner/setup script and have the worldmanager subscribe to it's spawn event and setup the dependency through there?
Serializing whatever references you can and assigning dependencies on instantiate is probably the way to go. Unity also has events for scene loading and methods for getting the objects within that scene, so you can also do this across scenes to facilitate multi scene setups.
I guess I'll stick with that then. I've also toyed with the idea of a static dictionary for references, but that would probably overcomplicate things.
Hi, I'm trying to set the "build configuration" setting from the WSA build settings option via code. I seem to be wanting to use Environment.SetEnvironmentVariable, but I can't seem to find what the variable is named for me to reference. Could anyone help me out? Thanks
hey all from where i can learn advance coding
You do not "learn" advance coding. You learn coding and after a certain amount of time and situation encounter you know advanced concept.
In other words, learning things that you do not use is pointless.
oh from where i learn basic
means from where i star
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hi again,
I made a sample for my package, but upon moving it into the proper folder layout (Within the packages folder, next to the Runtime directory), the prefabs have broken themselves, possibly because the scripts used in the prefabs derive from the Core files, but are located in the Samples folder. Is there a way to move the prefabs without breaking the link?
Really strange, usually prefab are linked through .meta files meaning that as long as you move everything it should not break.
whats lost prefab references, or the componets on them broke
Hi It must be common to have a list and then realise you often want to find elements of that list by Id so you add a dictionary (because you still want a list for fastest traversal from start to end). Is there not a typical List/Dictionary combo container?! Must you choose...
c# dictionary is open hash table with single linked list.....
afaik uthash use double linked list so you can traversal the hash table at exactly theta(number of item) time
but ofc, double "pointer" (actually is integer type) space
I know the basis for a dictionary, but I must test the speed of looping through dictionary items vs a list to see if not worthy of keeping a list. Ideal data container would have [index], fast iteration, find by Id/key!
Honestly I would not bother, if you are worried about it because of performance, have you profiled it and positively identified the iteration is the performance bottleneck? Otherwise, it feels very much like premature optimization.
There are also information missing. You mention that you want to look up items by id, and want to iterate over the items, but you didn't specify 1) how many items we are talking about and 2) do you need to iterate over the items in any specific order (eg insertion order?). It will change the answer.
you are right I will benchmark, also 90% it actually does not matter which I use as not significant!
there's SortedList, which is kind of both, although it's not necessarily as fast for lookups as a dictionary
also does order even matter for you
assuming not, that its lookup by key, or you just want to loop them all
Exactly, the amount of items and the iteration order are two important piece of missing information.
toss a few million things in a dict, and a list
measure how long to iterate it all
there is your answer
thanks I think since <1000 there is little issue - BENCHMARK!
write it in a way it does not get optimized out
so pass it to something each iteration
but do the same thing in both examples
1000 items is trivially small, and you still haven't specified what iteration order you need.
If you don't care about iteration order, keep in mind you can literally just foreach the dictionary. Whatever you do with each item will likely far outweighs the cost of iterating that tiny 1000 item dictionary that I wouldn't even bother benchmarking it.
the amount of worry feels more like procrastination then anything to me
would not worry about 1000 iterations, would just try and ensure you are not doing work more times then required
The components on them have broken. For example, "MenuManager.cs" is part of the Samples directory, while this is within the Assets directiory, all is fine, as soon as I move it to the packages directory the references are lost, and it appears the code is not being compiled while in the folder. Sorry for the delayed response!
This is my first time making a package properly so I've probably made a rooky mistake somewhere tbh!
just in case, did you move the metafiles too when you moved the scripts?
yeah, I moved the entire Samples folder from under assets to packages (well the custom package within packages). I was trying to mirror it so moving it would cause no issue.
it feels like your asmdef references are messed up
I have "auto referenced" ticketed and "Use GUID" with the input system being included.
but that asmdef is in the runtime folder, should there be one in samples?
is there scripts in the samples folder?
yes'
could try tossing one in there, then explicty creating a reference to your main asmdef
i have not done pacakge stuff in like a year i forget if the samples folder in it would act differently or not
compared to just a folder in assets
I think it is defo acting differently, but when I look at the docs, it doesn't mention having a asmdef file in there, I will try it tho
ok, it's sorted out the linking and I can open it in vs studio again, that was defo part of my issue. So I guess, whenever code/prefabs are included in the samples, it would be common practice to include an asmdef file?
I need help setting a line renderer that always draws its points to the same target regardless if its game object rotates or not.
(Pic 1)Here I have a bunny ninja moving towards the player and the line renderer is pointing to the right direction, but were he to rotate to move around an object, the line renderer rotates, too. So it's always pointing forward. How to calculate it in a way that it accounts for transform's rotation?
If it makes life easier, he will only ever rotate on the Y-axis.
set your LineRenderer to use World Space instead of Local Space
and just set the points according to the world space positions desired
alternatively, continue to use local space but convert the desired points into local space before assigning them to the LR
the key is just to be consistent and not mix up world space and local space positions
Oh, dang! I didn't even notice the boolean there. Thanks! 😂
Working properly. Thanks!
Hey, I have a question about UnityEvent and dynamic parameters. I am setting up a statemachine that uses UnityEvents. Say the event is UnityEvent<float>OnSomeEvent. When the state matches what the listener is waiting for then the event is fired and sends a float value from a list of choices based on the current state. This all works but I not want to tween to the float that is sent from whatever the current value of the dynamic parameter is. Is there no way of getting access to the dynamic parameters? I tried the getpersistent target and such but there is no way to get it there without knowing all the possible types that could be used.
Generally the invoker of an event should not care what the listener wants to hear. Therefore this whole design, while based on unity events, is flawed. They superficially look like editor assigned method calls, but really they are an implementation of the observer pattern.
In your case it would make sense to make a custom state-message-bus-type thing that’s suited to your design.
why not just have the receiver figure out how to tween the values?
the invoker's job is to announce a target value
there‘s definitely a use case for a state injecting behavior into listeners, say for agents that want to interact with a widget.
but only in the abstract ofc
That would require an additional script for the listener
right now its just a component that listens and can responds by setting the values of the dynamic parameters defined in the event (in editor). allows me to keep the relevant items in one place. Though I am not opposed to changing things up which I may have to. IT sucks because all I want to do is figure out what the current value is.
Oh well. Can't haqve everything
This is an example of what I am testing now. But default value means that I have to set some arbitrary value
float duration = dataTarget.duration;
Vector2 defaultValue = Vector2.zero;
DOTween.To(() => defaultValue, x => defaultValue = x, targetValue, duration).OnUpdate( delegate { _vect2Event?.Invoke(defaultValue); });```