#archived-code-advanced

1 messages · Page 93 of 1

frozen ravine
#

yeah

#

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

dapper cave
frozen ravine
#

frick

abstract folio
#

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

frozen ravine
#

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

dapper cave
austere jewel
frozen ravine
#

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

austere jewel
#

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

frozen ravine
#

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

dapper cave
abstract folio
austere jewel
dapper cave
#

something like
out = sdf stuff
out = mangle out with RGB offset
return out;

dapper cave
frozen ravine
#

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

dapper cave
#

oh but that'd need an output to some rendertexture... meh yeah that won't work

frozen ravine
#

yeah I think it would be idk why I asked lol

#

is there any way to use my sub-graphs on a regular shader?

dapper cave
frozen ravine
#

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

dapper cave
#

bloody pain in the ass: it's like Unity don't like easy stuff anymore, everything is so tortuous

dapper cave
frozen ravine
#

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

dapper cave
#

oh ok

frozen ravine
#

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

dapper cave
#

doesn't? it's all in SDF shader?

frozen ravine
#

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)

brisk pasture
#

could skew it in the vertex shader?

frozen ravine
#

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

dapper cave
#

yeah, stack a vertex shadergraph on top of the sdf thing

brisk pasture
#

why would chromatic aberration be applied to the mesh

#

thats something you will be doing on the whole screen

frozen ravine
#

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

brisk pasture
#

it really sounds like you are implementing thigns into the per object shaders that really should be done in post processing

frozen ravine
#

how would I do skewing in post-processing?

#

and why would I?

brisk pasture
#

like glow i would just do via bloom, with a above 1 threshhold

dapper cave
#

maybe he wants a per button effect

austere jewel
brisk pasture
#

the skewing the characters i would do on the shader that is applied to the TMP object

frozen ravine
#

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

dapper cave
#

expensive is late stage consideration, unless your hardware target is something weak.

frozen ravine
#

I wanna be able to target as many computers as I can

dapper cave
#

yeah don't worry about it dude, that's a form of procrastination

abstract folio
dapper cave
#

just do your thing for a 2060 target then optimize if players complain

#

or you're never done noodling

frozen ravine
#

I mean it didn't take that long and I still think it's better than the post-processing approach

dapper cave
#

Quest 2 would be another story, PC, players are used to shit framerate

frozen ravine
#

this lets me put the shader on things specifically rather than just everything that has a high glow

dapper cave
#

you can mask out stuff

frozen ravine
#

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

dapper cave
#

ok

frozen ravine
#

also that glow shader took like half an hour, it didn't take as long as the other stuff

dapper cave
#

weird, my 2022 won't compile on script change by default, where is that setting?

frozen ravine
#

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

bleak citrus
#

This is not a code question.

dusty wigeon
frozen ravine
dusty wigeon
frozen ravine
#

So you think it shouldn't be skewed or rotated?

dusty wigeon
#

If you are not able to make it in a reasonable amount of time, yes.

frozen ravine
#

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

dusty wigeon
#

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)

frozen ravine
#

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

dusty wigeon
frozen ravine
#

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

brisk pasture
#

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

dusty wigeon
frozen ravine
#

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

dusty wigeon
#

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.

flint wind
#

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

novel plinth
#

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?

flint wind
sharp verge
#

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

brisk pasture
#

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

sharp verge
#

im so mad ,i fogot that AddListener wouldnt update the inspector but it is added🤡

terse oyster
#

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",

vague raven
#

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.

verbal temple
vague raven
#

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.

verbal temple
#

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
solar parcel
#

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

brisk pasture
#

could use a StateMachineBehaviour

solar parcel
#

yeah but unfortunatly they cant access the scene and I want this to be as general as possible

solar parcel
#

thank you

brisk pasture
#

otherwise you can read the state info in a update and wait for its change

solar parcel
#

well yeah but what i want is for the method to be selectable from the inspector

#

and the animator reference only exists during runtime

brisk pasture
#

so read the AnimatorStateInfo,

#

detect when it changes and execute what you want

solar parcel
#

okay i will try that thanks

hardy jacinth
#

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

flint sage
#

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

hardy jacinth
hardy jacinth
flint sage
#

Don't use CreateAssetMenu

fresh vortex
#

why not?

hardy jacinth
#

[ContextMenu] that is then, I guess

hardy jacinth
# fresh vortex why not?

probably because it doesn't seem to have any exposed mechanism for something like "OnAssetCreated"

flint sage
#

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

hardy jacinth
#

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);
    }
  }
}
hardy jacinth
#

I guess you mean scriptable wizard, not scriptable editor?

hardy jacinth
#

there is another problem though, when I update something in my SO, other assets that depend on it don't refresh in editor.

proven halo
#

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?

sly grove
proven halo
#

nope

sly grove
#

Then show your code and explain which fields aren't serializing and how you checked if they are or aren't.

proven halo
#

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

thin mesa
#

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

proven halo
#

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

proven halo
#

Seems like using the EditorGUILayout.PropertyField() method calls SetDirty automatically under the hood

sly grove
proven halo
#

Indeed. Luckily I was able to figure it out after rubber ducking here.

proven halo
sleek moat
#

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.

stuck plinth
sleek moat
#

What is NGO?

stuck plinth
#

unity netcode for gameobjects

sleek moat
#

I'm using FizzySteamworks w/ Mirror, and using netcode for gameobjects too

stuck plinth
#

ok, sounds like you want a custom message then?

sleek moat
#

Yeah, someway to send messages between them.

stuck plinth
sleek moat
#

But does this require any Network Components on the object recieving/getting custom messages?

stuck plinth
#

there's no object involved, custom messages is a system totally separate from rpcs

#

you just need a reference to the network manager somewhere!

sleek moat
#

Ah ok, could I pass parameters through it such as a CSteamID

thin mesa
sleek moat
#

Maybe I'm confused, but I think I meant I'm using Mirror's network objects

stuck plinth
#

the docs have some examples of using FastBufferWriter/FastBufferReader

sleek moat
#

yeah its a 64 bit ulong it says

stuck plinth
#

yup!

thin mesa
stuck plinth
sleek moat
#

Well actually

#

Fizzysteamworks is the transport

#

for me

thin mesa
sleek moat
#

I got to go now, but thanks for the help simonp. I'll look into it soon.

half swan
#

Mirror was named that because it is a "mirror" of unet afaik

stuck plinth
sleek moat
thin mesa
stuck plinth
polar rivet
#

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

cursive horizon
# polar rivet hey does anyone have a tutorial on an advanced 1st person fps, Im trying to crea...
GDC

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...

▶ Play video
GDC

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...

▶ Play video
white pulsar
#

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?

grizzled valve
#

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.

gleaming rock
#

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?

random dust
#

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

gleaming rock
# random dust Sounds like inaccuracies with float objects?

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.

mellow plinth
#

Two questions:

  1. Is there a way to know if my code is run inside a Unity Job?
  2. 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.

stuck plinth
mellow plinth
stuck plinth
#

ohh right i see... what didn't work with checking the managed thread id?

mellow plinth
#

🤔

stuck plinth
#

what do you mean it didn't work though?

mellow plinth
#

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.

stuck plinth
#

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

scenic forge
#

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.

brisk pasture
#

there is also no problem with a bit of code duplication and if means less other problems to solve

mellow plinth
#

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

kindred wyvern
#

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._
plain abyss
#

"Fuck you! *Unimplements your null check override*"

exotic trout
#

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

tawdry sentinel
#

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

brisk pasture
#

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

tawdry sentinel
#

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

brisk pasture
#

File.ReadAllText and File.WriteAllText

#

just have to build the file paths from the persistientDataPath and your file name

tawdry sentinel
#

Oh, easier than I thought

#

Thank you ❤️

untold moth
#

Or reorganize your data structure to not use an array of arrays. Or serialized it manually.

brisk pasture
#

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

tawdry sentinel
#

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

brisk pasture
#

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

cursive horizon
jade solar
#

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.

long ivy
#

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

jade solar
#

But I've written code like this all the time:

long ivy
#

? Value isn't a class field there, apples and oranges

jade solar
#

That makes a lot more sense now. Thank you.

tiny pewter
#

pointer is code advance but you may need !learn

thorn flintBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

tiny pewter
#

btw the error tells you field initializer

valid shale
silk inlet
#

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.

abstract folio
thin jackal
#

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.

grave raft
#

how to get final velocity of a projectile after penetrating an armor plate?

abstract folio
grave raft
abstract folio
#

cool! not sure what that formula is.. looking it up now

grave raft
abstract folio
#

this one?

tiny pewter
#

this is super hard

grave raft
abstract folio
#

this is what I found searching for that formula... does it match what yo are expeting?

grave raft
#

that isnt demarre

abstract folio
#

ok, please give the formula you are trying to implement

#

demarre

grave raft
#

idk the formula, i need a formula for final velocity of an projectile that penetrated the armor

tiny pewter
#

but you have it

abstract folio
#

I'm confused, if you dont know the formula what akes you say the one I posted isn't correct?

grave raft
#

im searching for a formula for final projectile velocity after penetration

abstract folio
#

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

tiny pewter
#

if impact angle=0 then v=0?

abstract folio
#

^ was trying to show it would NOT penetrate at angle 0, it would "ricochet".. but your right.. not an ideal expression.

#

@tiny pewter

grave raft
#

top values are velocities
left ones are angles
bullet weight doesnt even affect the equation

tiny pewter
#

for such kind of physics and material simulation

abstract folio
grave raft
#

final velocity of an projectile

abstract folio
#

I dont get it.. looks like they are higher than the initial velocities.

grave raft
#

i will just substract the "final velocity" with ongoing velocity, but idk why projectile mass doesnt get afected

abstract folio
#

are the initial(top row) and final velocity(entries) in different unit's perhaps? It definatly should NOT be going faster after impact.

modest lintel
#

Hi glurthy 👋

abstract folio
tiny pewter
#

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

abstract folio
#

ah, and that formula I found/posted before was indeed penetration depth.. (failed to read the page properly before)

subtle river
#

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

modest badge
#

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?

subtle river
#

If it is a static class, it always exists and can't be checked for null

modest badge
#

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?

fresh salmon
#

Hover over the error and click the light bulb icon that appears. You might just be missing a using directive.

modest badge
fresh salmon
#

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

warm charm
#

Hi guys, sorry for being annoying, does anyone know how I can fit these dungeon rooms into just one square?

#

like this

fresh salmon
#

Your code editor doesn't seem configured at all, errors should be underlined red

#

!vscode

thorn flintBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

fresh salmon
#

Follow the guide above and come back when it's working properly

modest badge
#

thanks anyway, i'll solve it on my own

fresh salmon
#

What? The snippet you showed would error on its own

thin mesa
modest badge
#

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

fresh salmon
#

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

modest badge
#

I just followed the instructions on the Facepunch page, to include the .dlls into my Assets folder

#

but maybe that's the issue

thin mesa
#

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

fresh salmon
#

That's purely a VSC issue, as Unity reports the error correctly

modest badge
#

VSC issue?

thin mesa
#

well aside from the one issue i posted in the github

modest badge
#

do you have a code example of how you set achievements?

#

that would be a huge help to me

fresh salmon
#

It's just a missing using directive at the top

modest badge
#

so you want me to put using Facepunch.Steamworks at the top?

fresh salmon
#

I want you to restart VSC so it loads the analyzer properly for the file, then use the Quick Actions lightbulb to solve it

modest badge
#

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)

thin mesa
#

regenerate project files

fresh salmon
#

(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?)

modest badge
#

Ok fixed that

#

the analyzer works now in VSCode again

thin mesa
#

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

modest badge
#

so now, it does have the red line, but as I said the Achievements do not exist in that library

modest badge
#

it was in an old library

#

ok so we're on the same page, I'll try using SteamUserStats

thin mesa
#

why are you blaming "old libraries" on this when this is a matter of you not reading the documentation

modest badge
thin mesa
#

point to the line where is shows an Achievements.Trigger(string) method

fresh salmon
modest badge
#

sorry honestly i'm just very frustrated with the documentation on their page

#

and this simple task has been taking way too long

fresh salmon
#

I guess the page you linked tells you how to run code whenever an achievement is unlocked, not how to trigger one

thin mesa
modest badge
#

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

heavy saddle
#

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.

thin mesa
#

your packages should typically include an asmdef. but you need to make sure you are including meta files

heavy saddle
#

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
}

thin mesa
#

are you including meta files

heavy saddle
#

here's the package imported on unity, and here's the package once downloaded manually on file explorer

#

ya it has meta files Hmm

#

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 hmmGe

this is what it looks like

upbeat path
heavy saddle
#

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 😄

upbeat path
#

why not just build a dll and have done with it?

heavy saddle
#

not sure i could have prefabs in my package if the package was just a dll hmmGe

upbeat path
#

the package is not a dll, the code could be

#

seems like you are lacking a lot of knowledge to be doing this stuff

heavy saddle
#

i am 😄

modest badge
sage radish
upbeat path
subtle river
modest badge
subtle river
# subtle river Hmm. Good to know, thanks. Though all my jobs are started in Update and complete...
[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();
}
thin mesa
# modest badge Ok I'm back so I'm confused by this section of code in their example: ``` p...

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.

upbeat path
modest badge
thin mesa
sage radish
upbeat path
# modest badge I see, ok thanks

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

subtle river
#

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.

sage radish
subtle river
#

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

modest badge
thin mesa
#

instead of using Where and then ToList, just use First
or just create the Achievement object by calling its constructor

modest badge
thin mesa
#

i just ignore it because it means almost nothing 🤷‍♂️

subtle river
modest badge
thin mesa
#

that shouldn't be causing any errors in the editor. whatever error you are seeing is likely unrelated.

modest badge
#

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?

sage radish
subtle river
#

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*

thin mesa
subtle river
#

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.

subtle river
modest badge
# thin mesa doesn't sound like an issue with your code then

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

silk inlet
#

Vivox Participant Tap thing

modest badge
# thin mesa doesn't sound like an issue with your code then

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");
    }

}
hearty pelican
#

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

sly grove
#

It's a pretty common task

hearty pelican
brisk pasture
#

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

sly grove
#

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.

brisk pasture
#

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

hearty pelican
brisk pasture
#

they dont

#

Sprite is not its own texture

hearty pelican
#

wait wait.. hear me first

brisk pasture
#

Sprite is a rect on a existing texture

#

and you can have many sprite reference pixels from 1 texture

sly grove
hearty pelican
#

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

sly grove
#

Yeah... We're telling you how to do exactly that

brisk pasture
#

would take a bit of messing about to get it polished

#

but this would be a very easy thing to automate

hearty pelican
sly grove
#

No you'd make a texture and create multiple sprites from it

brisk pasture
#

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

hearty pelican
#

ok but i'm not seeing how i can dynamically update all the sprites to render new textures by frame

sly grove
#

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

sly grove
#

You'd make the sprites in code

#

With Sprite.Create

hearty pelican
#

ok so its reasonable to create sprites and rewrite them every frame by using a render texture?

sly grove
#

Why every frame?

brisk pasture
#

also you could you could even have them of a video

hearty pelican
#

because it is needed for a mechanic

sly grove
#

You can render to the texture every frame no problem and leave the sprites alone, that would work fine

brisk pasture
#

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

sly grove
#

Like if you want a video jigsaw puzzle that's easy enough with a render texture

brisk pasture
#

the sprites will update as well

lament salmon
#

You might be onto something

sly grove
#

Kind of interesting actually

#

Unlocking lots of game possibilities in my head lol

hearty pelican
sly grove
#

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

hearty pelican
#

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.

wraith storm
#

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()

brisk pasture
#

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

stuck plinth
past silo
#

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

Gist

GitHub Gist: instantly share code, notes, and snippets.

stuck plinth
# past silo I have been stuck with this issue for a couple of hours now, and im almost bald....

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

past silo
misty glade
# past silo Well, i think that they are similar since one is being used if the 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!

past silo
misty glade
#

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

misty glade
#

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)

radiant wave
#

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.

sly grove
radiant wave
#

Including references from the scientist to all the windows he might look through? That will be messy 😩😄

cursive horizon
#

do the windows need to have colliders at all, or could they just be visual?

junior stone
#

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?

untold moth
#

Or find a walk-around.

junior stone
#

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 🤷‍♂️

untold moth
#

Can't help you any more than what I said without knowing the details of the issue.🤷‍♂️

spiral swift
#

btw, how would I be able to do a cutscene using instantiated objects?

livid kraken
regal olive
#

Yo

#

Can I get some help

untold moth
regal olive
#

I need help with my procedural world generation

#

It won’t take my code and there is no errors

untold moth
regal olive
#

Wym?

#

I was told to come here

untold moth
#

Ah I see. They also linked this channel too.

regal olive
#

I was linked to all the code channels but I just clicked this one

untold moth
#

Anyways, what doesn't work?

regal olive
#

My procedural world generation

#

It won’t take my code

untold moth
#

Does the code run?

regal olive
#

Yes

untold moth
#

wdym by "won't take my code"?

tall ferry
#

Look at the #854851968446365696 on how to ask. It shouldnt be troubling to find out what your issue is

regal olive
#

Tbh idk just won’t run my code In unity

untold moth
#

Does it run your code anywhere else?

#

And how do you confirm that it doesn't run your code?

regal olive
#

Yes I ran the game and it did not take and do anything

tiny pewter
#

then your code doesnt run, have you debug it first

regal olive
#

Yes

tall ferry
#

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"

regal olive
#

Sorry about the way I worded things never good at questions

untold moth
regal olive
untold moth
#

Then give short summary of what it does and where it is run from?

regal olive
#

So I’m a little lost

untold moth
regal olive
untold moth
#

How?

regal olive
#

It ran with no errors

untold moth
#

How did you run it in VS?

regal olive
#

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

untold moth
#

How did you test for errors?

regal olive
#

Ok now you’re confusing me

untold moth
#

How did you run it in VS?

regal olive
#

I clicked the start button

untold moth
#

To run a code you need to compile/build it and execute the program. Is that what you did in VS?

untold moth
regal olive
#

Yes

#

In vs

untold moth
#

It's unity project, right?

regal olive
#

Yes

tall ferry
#

Do you know how to run any code in unity..?

untold moth
tall ferry
#

Like hello world

regal olive
#

Yes

untold moth
#

it doesn't run the code

regal olive
tiny pewter
#

it is just attach a debugger not playing

untold moth
#

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?

regal olive
#

They don’t appear they’re just gray for me

#

That’s what I mean it won’t work

untold moth
#

What "they"?

regal olive
#

White and red green blue yellow

untold moth
#

Please use screenshots. It's supper annoying to try and understand anything from a photo of a screen

untold moth
# regal olive

These look like read only or non serializable fields. What do you expect to happen with them?

regal olive
#

Ok wait it says waves is missing the class attribute extension of native class

regal olive
untold moth
#

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

regal olive
#

I’ll figure it out tomorrow it’s fine Ty tho

tall ferry
#

Maybe try a hello world first as well so you can see how to actually run code in unity

regal olive
#

I know how to run code in unity

#

It’s not rocket science

tall ferry
#

It should be extremely trivial for you to see why your code isnt running then. Since you also said you debugged it above

regal olive
#

Yeah I’m watching one now

#

It’s probably something really simple I just overlooked

untold moth
#

Watching what? A debugger?😅

small gull
regal olive
#

Ok

#

Yeah that worked

regal olive
small gull
#

have you changed ur script's name?

regal olive
#

Yes

#

When I first added it

#

Should have waited tbh

wraith storm
stiff hornet
#
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())
stiff hornet
#

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 ?

spiral swift
humble leaf
#
  1. Create a different object using those sprites, and hand animate them in timeline.

  2. Create a robust system in timeline that will let you move the actual characters through waypoints to move or to call specific animations.

  3. 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.

brisk pasture
subtle river
#

Anyone know if there's a faster way to get the current color/size of shuriken particles cringe
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.

sage radish
#

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.

subtle river
hardy jacinth
#

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?

hardy jacinth
sage radish
hardy jacinth
#

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

frigid cloud
#

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!!!

brisk pasture
#

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

frigid cloud
#

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?

brisk pasture
#

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

frigid cloud
#

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

brisk pasture
#

its taking UNITY_MATRIX_MVP and multiplying it by objectPos

frigid cloud
#

ah, so you're saying there'd be a way to interrupt the vertex displacement portion of shader processing and handle the displacement globally?

brisk pasture
#

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

frigid cloud
#

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? 😛

austere jewel
#

Well, matrices cannot be bent, they can only be skewed. Composing a scene using enough cameras at different depths sounds expensive as all hell

brisk pasture
#

have done it before, you just automate it

frigid cloud
#

if it's not possible it's not possible, I totally get that

brisk pasture
#

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

humble loom
#

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

frigid cloud
#

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

humble loom
#

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?

frigid cloud
#

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

austere jewel
#

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

tacit harbor
#

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

tiny pewter
#

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
GitHub

Source from the Microsoft .NET Reference Source that represent a subset of the .NET Framework - microsoft/referencesource

upbeat path
#

Also why Dictionary<string,string> instead of Dictionary<string,object> and leave all the serialization to the Save method

fickle inlet
#

how to refernece CinemachineVirtualCamera in code? I tried using Cinemachine and using UnityEngine.Cinemavhine, non is working

upbeat path
#

The Namespace is Cinemachine, if VS is not picking it up you may need to Re Gen your project files

tacit harbor
upbeat path
#

also if you use a Dictionary<string,object> there is no need to update the dictionary at all

charred drum
#

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

upbeat path
charred drum
#

How would I call that?

upbeat path
#

normally SO's are created via a menu option

charred drum
#

I meant more like

#

It should be a function called within the scriptableobject file itself, yes?

upbeat path
#

normally yes, with a Menu attribute

amber pier
#

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&
upbeat path
hardy jacinth
# frigid cloud Hi all! Hoping to find some camera experts here! I'm trying to build my own cam...

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

royal zealot
#

how can i implement camera collision?

olive anchor
#

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.

▶ Play video
livid kraken
# olive anchor how would i go about recreating this type of destruction in unity?? and i dont m...
GitHub

Open source mesh slicing/fracturing utility for Unity - dgreenheck/OpenFracture

Get the RayFire for Unity package from RayFire Studios and speed up your game development process. Find this & other Game Toolkits options on the Unity Asset Store.

olive anchor
#

I’ll check these out later because it’s 2 am right now but Ty

livid kraken
#

Honestly your best bet is just to buy rayfire

#

Fracturing is easy, its the clustering and structural destruction that is hard

frigid cloud
hardy jacinth
frigid cloud
#

hmmm, that's a very valid concern

frigid cloud
#

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?

sage radish
# frigid cloud Hi all! Hoping to find some camera experts here! I'm trying to build my own cam...

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.

abstract folio
#

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?
frigid cloud
fallow echo
abstract folio
# fallow echo 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>();

fallow echo
#

ah... well you can see the stack trace in the error message

long ivy
abstract folio
abstract folio
long ivy
#

Empirically it appears that's what's happening though

abstract folio
long ivy
#

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

abstract folio
long ivy
#

499 out of 500 times, they finish on same frame

abstract folio
#

and when the dont.. why doesn't the && make the result false, and not let it pass?

#

(sorry I'm not usually this thicl)

fallow echo
#

because they are both done... one of them was just done earlier (previous frame), so data is no longer available 🙂

long ivy
abstract folio
#

"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".

fallow echo
#

+1 thanks from me, I didn't know it's only available for a frame 🙂

abstract folio
full ledge
#

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

hybrid belfry
#

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

lament salmon
#

Relative to the path, the start face and end face should indeed be in different orders

#

You are doing it correctly

hybrid belfry
#

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

lament salmon
#

Yes, or well, it will completely skip triangles that face away from the camera

hybrid belfry
#

I see

lament salmon
manic orchid
#

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);
    }
}
icy sparrow
#

can any one help me with my cosmetic script

austere jewel
icy sparrow
#

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.

austere jewel
#

!vs

thorn flintBOT
#
Visual Studio guide

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)

icy sparrow
#

okay thank you

stoic otter
#

is there a function or a delegate what execute when you duplicate or copy/paste a object in the scene view?

abstract folio
stoic otter
#

ObjectChangeKind.CreateGameObjectHierarch

abstract folio
stoic otter
subtle river
#

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

abstract folio
austere jewel
#

I have exploited lightprobe tetrahedralisation before I think...

sage radish
abstract folio
#

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?

sage radish
# abstract folio Man, soon as I get over my impostor syndrome, you guys post something like that ...

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.

subtle river
#

@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...

▶ Play video
sage radish
#

Or maybe it's just easier to implement the algorithm from scratch.

subtle river
mellow plinth
#

Does IL2CPP, optimizes typeof(T) == typeof(U) when one of both is a value type?

fresh salmon
#

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.

mellow plinth
#

For example, if (typeof(T) == typeof(int)) is automatically propagated

#

Making it zero-cost

fresh salmon
#

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

mellow plinth
fresh salmon
#

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.

severe loom
#

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

sage radish
# mellow plinth For example, `if (typeof(T) == typeof(int))` is automatically propagated

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.

timber flame
#

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

stuck plinth
storm onyx
#

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

timber flame
#

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

upper basalt
#

hey y'all, who's familiar with Behaviour Tree, Behaviour designer in unity, i need help

upper basalt
#

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

misty glade
#

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

thorn flintBOT
misty glade
#

no excuse? i'm 45, that's boomer territory i think

half swan
misty glade
#

gasp, insults

#

I suppose I identify more as a boomer since .. offtopic, I play "boomer jund" in MTG. Bob/Lily for life.

half swan
#

Doesn't change anything you said though haha

misty glade
#

(I hear "OK boomer" at least once a week)

brisk pasture
#

who cares about the labels, especially in a domain like programming

half swan
upper basalt
upbeat path
craggy spear
timber flame
#

Cam we Implement a custom Depth test in srp?

smoky kite
#

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

fresh salmon
smoky kite
fresh salmon
smoky kite
fresh salmon
#

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)

smoky kite
#

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 🙂

ruby 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 🙂

sly grove
#

pass in a delegate

#

call the delegate at the end of the coroutine

ruby salmon
#

thanks! yeh but im getting a null somehow

sly grove
#

wdym by "getting a null"?

ruby salmon
#

at least i know what its called now

#

in the console it shows nullReferenceException at this line StartCoroutine(doAPIAction(() =>

sly grove
#

NullReferenceExceptions are always the same

ruby salmon
#

trust me i do but i have never tried to use delegates

sly grove
#

you are dereferencing a null reference on that line

ruby salmon
#

i cant understand what is null

sly grove
#

find out

#

attach the debugger

ruby salmon
#

been a long time since i used a debugger 🙂

devout hare
#

On that line nothing can be null so either your actual code is something else or the error comes from a different line

ruby salmon
#

yeh thats what i was thinking

#

thats what i dont understand 🙂

sly grove
devout hare
#

Show the actual code and the full error message

sly grove
#

hard to say without seeing the actual code and error yea

ruby salmon
sly grove
#

show actual code

#

and actual error message

sly grove
ruby salmon
#

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)

sly grove
#

that's a big nono

ruby salmon
#

oh yeh!

#

lol.... forgot it was a mono

#

thanks

#

perfect it works, been shying away from that syntax for ages

umbral bloom
#

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();
    }
stuck plinth
umbral bloom
upbeat path
stuck plinth
#

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

umbral bloom
# upbeat path LinQ does not work that way

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();
upbeat path
#

OMG. May I suggest, as you seem to be concerned about performance and memory, you learn how c# actually works

stuck plinth
#

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

umbral bloom
stuck plinth
#

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

upbeat path
#

@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

umbral bloom
stuck plinth
#

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.

umbral bloom
#

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

stuck plinth
#

you'd probably want to test using unity's specific version of mono

umbral bloom
#

What should I use for testing (benchmarking) purposes? UTF?

stuck plinth
#

there is the performance testing extension for unity tests, don't think i've used it myself though

umbral bloom
#

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

gleaming lichen
#

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

tiny pewter
#

no.....have you checked the method is being invoked first

gleaming lichen
#

@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

lament salmon
upbeat path
#

how are you calling a private method from a different class?

tiny pewter
#

you can by passing it as Action

upbeat path
#

I meant this

private void Start()
{
  inRangeInteractionCollider.Init(ManageVisible);
}

Init is private

tiny pewter
#

oh didnt notice that

#

mb

gleaming lichen
gleaming lichen
#

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);
upbeat path
#

yep, that would do it

gleaming lichen
#

it made dupplicates, may be some reference got lost lol

upbeat path
#

you need to use a delegate so you can add to the action rather than replacing it

gleaming lichen
#

do you have an example sorry 😄

hardy jacinth
#

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()?

stuck plinth
#

maybe the type's IComparable or IEquatable implementation?

#

that's how most system libraries work

hardy jacinth
#

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.

dusty wigeon
#

But, yeah, usually.

hardy jacinth
stuck plinth
hardy jacinth
dusty wigeon
#

Are you having multiple people using the same database ?

hardy jacinth
#

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

hardy jacinth
#

maybe more info on why I even try to use it:

dusty wigeon
hardy jacinth
#

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

scenic forge
hardy jacinth
#

yeah, I'll use regular dictionaries/sets and POCOs instead of DataRable for now. I'll them until I learn more about them.

mellow plinth
#

Given a NavMeshPath, how can I know if it contains OffMeshLinks?

upbeat path
mellow plinth
#

haha

#

Is there any other way?

upbeat path
#

yes, it is

mellow plinth
#

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.

upbeat path
#

well, yes, but it's even worse

mellow plinth
upbeat path
#

check every corner in the path, find the corresponding gameobject and then check for a NavMeshLink component

mellow plinth
#

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?

upbeat path
#

expensive, yes, error prone, not so much, worth doing it, I doubt it

mellow plinth
#

Ok

upbeat path
#

question. why do you want to know this?

mellow plinth
#

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

mellow plinth
upbeat path
#

then just set the agent to not use navmeshlinks, then you will get a partial path back if links are necessary

mellow plinth
upbeat path
mellow plinth
upbeat 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

mellow plinth
#

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

lament salmon
#

Haven't tried that myself but it's worth a try

mellow plinth
#

Yeah, that is what I will do

lament salmon
#

Oh I missed your latest message, sorry

low sparrow
#

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

lyric isle
#

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.

main finch
#

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.

main finch
upbeat path
#

is PlayerInputActions not your own class generated by the new Input system?

lyric isle
main finch
#

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!

lyric isle
# main finch Are the gameobjects created by the worldmanager?

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);

main finch
#

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?

hushed fable
lyric isle
trim glade
#

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

dapper cliff
#

hey all from where i can learn advance coding

dusty wigeon
dapper cliff
#

means from where i star

dusty wigeon
thorn flintBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

main finch
#

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?

dusty wigeon
brisk pasture
#

whats lost prefab references, or the componets on them broke

ashen yoke
#

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...

tiny pewter
#

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

ashen yoke
#

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!

scenic forge
# ashen yoke Hi It must be common to have a list and then realise you often want to find elem...

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.

brisk pasture
#

benchmark it

#

90% chance you are overthinking it

ashen yoke
#

you are right I will benchmark, also 90% it actually does not matter which I use as not significant!

stuck plinth
brisk pasture
#

also does order even matter for you

#

assuming not, that its lookup by key, or you just want to loop them all

scenic forge
#

Exactly, the amount of items and the iteration order are two important piece of missing information.

brisk pasture
#

toss a few million things in a dict, and a list

#

measure how long to iterate it all

#

there is your answer

ashen yoke
#

thanks I think since <1000 there is little issue - BENCHMARK!

brisk pasture
#

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

scenic forge
#

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.

brisk pasture
#

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

main finch
# brisk pasture whats lost prefab references, or the componets on them broke

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!

main finch
stuck plinth
#

just in case, did you move the metafiles too when you moved the scripts?

main finch
#

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.

brisk pasture
#

it feels like your asmdef references are messed up

main finch
#

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?

brisk pasture
#

is there scripts in the samples folder?

main finch
#

yes'

brisk pasture
#

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

main finch
#

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

main finch
proven willow
#

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.

sly grove
#

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

proven willow
#

Oh, dang! I didn't even notice the boolean there. Thanks! 😂

proven willow
torn basalt
#

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.

compact ingot
#

In your case it would make sense to make a custom state-message-bus-type thing that’s suited to your design.

bleak citrus
#

why not just have the receiver figure out how to tween the values?

#

the invoker's job is to announce a target value

compact ingot
#

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

torn basalt
#

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); });```