#archived-code-general
1 messages · Page 329 of 1
but a branch on a uniform doesn't diverge: every single thread is going to take the same path
do you mean you're getting no autocomplete or error highlighting at all?
I don’t think generated code can regard it? You can still change the value on runtime
I mean that, when the shader program is executing, every thread will take the same path
because the branch is based entirely on a uniform
Follow the guide you brought up in #💻┃code-beginner
autoComplete. Look at the ss I have attached. I was expecting it to suggest me the "useGravity" attribute of the rigidbody i have mentioned above in the code
alr
show the declaration of rb
here it is but i believe im fixing it now. i had to install something in unity called vs something
Hm, guess that right, but I guess I would prefer using static branching for consistency
the problem is that this causes Shader Variant Hell very quickly
True, it's multiplying every time you add something like that sure
where are you coding without vs.
They are likely talking about the package. That is also likely not the issue
oh ok.
But I think the case you mentioned is quite specific (and relies on some internal detail), so I doubt it could be a general tips and practices
i mean, skipping a calculation if I'm not using a feature is pretty standard
Usually involves using other resources tho. I do like to see benchmark on that
I'm trying to create a gravity switcher mechanic and I'm failing to use quaternions/rotations to reorient and remap player input to handle movement.
Would someone hop in 5min call so I can show current state and ask questions?
Very unlikely someone will get on a call. You should show what you've tried and maybe someone can help here
Show your code and we can probably help.
Oh, also don't cross-post
visual studio code
I jus downloaded visual studio
the download keeps failing though
😭
this isn't a code question
also !install
- Make sure you have enough space including on
C:drive. - Check that it's not being blocked by antivirus/security programs.
- Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).
If you still have issues, perform a clean install in another location:
- Install the Hub and Unity in a non-system drive or a clean new folder in the root of
C:drive. - Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
sorry
So I see that you can just define dynamic_branch keyword in this case which consist with other keywords and change easily when you need to make it static branch
Only downside is probably that you can't set it with MPB?
I can't do that in the shader graph, unfortunately
I guess that a uniform is basically equivalent to a dynamic_branch at that point
Yeah that's just lacking the feature
But it is equivalent
Or use custom function and code it.. lol
public static Dictionary<Id, Sprite> LoadTexturesFolder()
{
Dictionary<Id, Sprite> sprites = new Dictionary<Id, Sprite>();
string folderPath = Path.Combine(Application.persistentDataPath, Data.TexturePath);
if (Directory.Exists(folderPath) == false) { return sprites; }
string[] filePaths = Directory.GetFiles(folderPath, "*.png", SearchOption.AllDirectories);
foreach (string filePath in filePaths)
{
Texture2D texture = LoadPNG(filePath);
if (texture != null)
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
sprites[new Id("scourgefall", fileName)] = sprite;
}
}
return sprites;
}
private static Texture2D LoadPNG(string filePath)
{
Texture2D texture = null;
byte[] fileData;
if (File.Exists(filePath))
{
fileData = File.ReadAllBytes(filePath);
texture = new Texture2D(2, 2);
texture.filterMode = FilterMode.Point;
texture.LoadImage(fileData);
texture.Apply();
}
else
{
Debug.LogError("File not found: " + filePath);
}
return texture;
}
So I have the above to load in some .png files at runtime. In the editor I can go into the Sprite Editor and edit: Custom Physics Shape and Secondary Textures. Is there a way to assign/ apply these somehow directly in the code at runtime too?
I want to:
- apply a secondary texture to a loaded sprite with a specific name like "_Emission" etc.
- Ideally also set a custom physics shape somehow per code
Any way to do this?
Physics shape:
https://docs.unity3d.com/ScriptReference/Sprite.OverridePhysicsShape.html
For applying a secondary texture, that wouldn't have to do with the texture itself but with the Material you use in your SpriteRenderer or however you're rendering the thing.
Oh, thanks alot!
I think I realize what you mean; The material has 2 Textures exposed as properties in the shadergraph: For example. "_MainTex" and "_Emission". Then I can just apply these 2 properties with the 2 textures I want. The textures themselves arent related at all and I set them seperately in the material.
I had the wrong Idea of how it worked i think, Is the above correct?
It just confused be cause in the editor I would just set the "_Emission" as a secondary of the "_MainTex" and not assign it to the material too
I guess the engine does that step for me when its the secondary texture with the proper 'id'?
What is the obvious reason I can't reference my VectorCache class from a MonoBehaviour class? 😂
I have no Errors to resolve
your VectorCache is in an unreferenced dll
you can reference Assembly-CSharp from Assembly-CSharp-Editor but not the other way round
why is VectorCache in the editor assembly?
I have no idea why it's there 😂
did you perhaps put it in a folder called Editor?
it's in an Editor folder ?
Ah. I am extending a downloadable tool and didn't realise when I dropped it in. It certainly is. Thanks a bunch
yeah, if you don't add your own assembly definitions, Unity puts anything in an Editor folder into a separate Editor assembly
Is there a way to keep it in the Editor folder, but have it in the standard assembly?
why does it need to be in the Editor folder?
simple answer, no
obviously not
What?
well if it was supposed to be editor only and you are referencing it in Assembly-CSharp then it is not Editor only or you have a serious design problem
The underlying tool has design problems unfortunately
then, as long as VectorCache does not contain any editor only code or references, best to move it out of the Editor folder so it becomes available to both
Adding an assembly definition can make you have that under Editor folder
But now then your Editor folder is not for Editor
You'll just have to make sure that you don't have any references to it when building the game
You can have the entire script inside an #if UNITY_EDITOR block
It's not worries I just moved it. The class that requires it stores editor data for Editor and Gameplay functionality and rewriting that would be a massive undertaking
Finally, working splines. Just tried it on 2022.3.31f1
did you try in 6 preview as well? it should be the same code
the fix was pushed in 6000.0.4 and 2022.3.31 so it should work in either
For grid based games what is the common practice to store and manage data associated with the grid.
Say the level map is a 2D 100x100 grid. You would want to store the grid position of the player, enemies, items/interactables, obstacle and walkable grid positions, etc. And also be able to change the positions of these elements and access their associated data easily, i.e. enemies moving each turn or a randomly generated level so the walkable and obstacle positions need to be changed.
In my view it depends on whether the data is expected to be dense or sparse
If the data is dense, it usually makes sense to use a 2D array, e.g. GridSlot[,]
If the data is sparse, I would use something like Dictionary<Vector2Int, GridSlot>
How would you describe dense and sparse?
What I mean by dense and sparse is, will the grid be mostly empty? If it's mostly empty, the data is sparse.
If most or all of the spots will always have some data associated with them, it is dense
The nice thing about the Dictionary is we don't need to store any data for empty slots. This makes it more memory efficient than the array when dealing with a sparse grid
But the Dictionary comes with slightly higher costs for adding and retrieving elements, so if the grid is dense, we may as well just use the 2D array since we will need to hold all that data anyway.
Do you know why i have 2 circles ? It's really weird
Hmm, well I wasn't talking about a specific game I was making, more to start planning the data structure of one.
Lets say of the level grid there would be at least 30-40% of the grid positions that would be obstacles and structures, the rest would be sparse with maybe a few enemies that move around the map and some items to interact with.
I've done a game with grid movement, but just used a collision system for movement as I didn't really need any data storage. But I'd like to instead not use collisions and just use the underlying grid data to place characters and move them.
Well, you gotta at least show how you create them
That sounds pretty sparse to me, but it's in the range where it would probably be similar either way.
Anyway you can accomplish that with either data structure I mentioned above.
Your code isn't handling the case when the dog is direcetly in the opposite direction
Oh yeah sorry ahah
Please, use one of the sites listed below !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
private void UpdateIndicatorPosition(Transform enemyTransform)
{
Vector3 screenPos = mainCamera.WorldToScreenPoint(enemyTransform.position);
indicatorImage.transform.position = screenPos;
}```
You should check here if `screenPos.z < 0` and if it is, hide the image
Simply ?
So either way you would either store a data element in a 2D array or a dictionary. In this case what would you store, a struct?
Would the data be stored in the struct just be the position and a reference to the gameobject associated with that grid position? Or would you store the gameobject data needed (enemy data, etc) directly in the struct.
Its work, thanks !
You don't have 2 circles, it's just that the circle is drawn even when the enemy is not visible to the player.
The z position returned by the WorldToScreenPoint method is the world units from the camera, so if the enemy is not visible to the player, which rotates the camera, then its z position is smaller than the one of the camera.
Oh i see thanks for explanation !
The enemy should just be detected when the camera sees it. This means its z position is greater and in camera's range
What is wrong with unity's rotations? I have a cube and I have a decal that's is rotation depending on the rotation of the cube no matter which face is facing up so when I put it down, the decal is align with the cube. but when the y axis is facing down, it acts weird.
this is what I want
And this is what it does when the Y axis is facing down
I use a very simple script for it
the other why I tried was this
_angle = vector3.angle(vector3.up, transform.right);
_rotation = transform.localeulerangles;
upf = mathf.abs(vector3.dot(vector3.up, transform.up));
rightf = mathf.abs(vector3.dot(vector3.up, transform.right));
forwardf = mathf.abs(vector3.dot(vector3.up, transform.forward));
up = upf > rightf && upf > forwardf;
right = rightf > forwardf && rightf > upf;
forward = forwardf > upf && forwardf > rightf;
if (up)
{
_angle = transform.localeulerangles.y;
vector3 _rot = transform.localeulerangles;
_rot.x = 0;
_rot.z = 0;
decaltransform.eulerangles = _rot;
}
else if (right)
{
quaternion targetrotation = transform.rotation;
targetrotation.y = transform.rotation.y;
targetrotation.x = 0;
targetrotation.z = 0;
decaltransform.rotation = targetrotation;
}
else if (forward)
{
quaternion targetrotation = transform.rotation;
targetrotation.y = transform.rotation.y;
targetrotation.x = 0;
targetrotation.z = 0;
decaltransform.rotation = targetrotation;
}
and this time the problem was only this Z
still trying to modify quaternion properties. DONT
the reason I have so many if and they are same is I was trying something else
When you do Quaternion->Euler A->Quaternion->Euler B. A and B will almost certainly not be the same
That part depends heavily on your game and what a grid slot can "contain"
YOu might also have a "terrain layer" which is probably pretty dense and an "items layer" which maybe has enemies, chests, items, etc which would be sparse.
I see it. it doesn't fix my issue
show what you tried
it still doesn't make sense that it only acts weird in one axis
because you're mangling a quaternion's four components
the behavior is not intuitive
Vector3 _rot = transform.localEulerAngles;
_rot.x = 0;
_rot.z = 0;
decalTransform.eulerAngles = _rot;
this is what I first tried
this one acts weird on Z axis up or down
so what should I do?
Would it be impractical to store all of these different game elements in one grid? Say have a struct that points to a gameobject reference.
It owuld be quite practical
I would recommend rather than GameObject though, to have a component like GridElement which goes on all of the different things
This gonna be complex as your box can be rotated to any direction so you cannot rely on any single axis
I assume you want your decal to follow the axis that is most upward
Other option would be just locking Y axis
I'm making a tower defense and I have a tower I would like to do something whenever each round ends (give the player bonus money). I have a level manager game object that handles spawning enemies/updating rounds and such, and I could just have the tower look for a change in the round variable each frame but that sounds like an awful design choice. I don't want the level manager to have to have an array of all of this type of tower or anything like that, so is there a way I can set up a callback across objects? Essentially have my tower look at the level manager and whenever it updates the current round, it runs it's function.
Have the level manager fire an event when the level ends
have the tower listen to the event
To mimic a single axis and maintain whatever values are on the other axis try:
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, otherTransform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)
Or to nullify the outlying axis', replace them with 0
Thank you!
OverlapCollider not finding colliders
Hey ! Someone know if it's difficult or not to create a launcher for my game ? I want create it for upload new version of my game to my friend without download it again ^^
yes thats what I want
first I tried to check which axis is on top and get the rotatins depending on that
but that didn't work as expected
it was the last thing I tried after eulerAngles when it didn't work
There are tutorials out there on how to create one. Regardless they'll have to download it though, which is something your application might try to do automatically. If you plan on publishing this for the public, stuff like Steam already handles this since it basically is a launcher
Its not free for steam so that why i try to find a way to have it free , its for manage update and info to everyone
It's hard to answer on its difficultly, this mainly depends on you. I just suggest researching how others make it online and decide for yourself if you're capable. There is a reason that steam exists, but also consider that MANY people do not like when games have their own launchers
Okey thanks you for the answer 
Whenever I try to rotate my gameObject, it spawns a clone of it. Here's the code: https://pastecode.io/s/09qwryx7 https://pastecode.io/s/z4i3hhyd
don't think it would be possible to clone an object without Instantiate
also don't crosspost
I instantiated
where?
so you have 3 different scripts, you might want to explain what exactly these scripts do
typically can tell what goes on, but here I'm genuinely confused what is even going on. Very messy
is this some tetris type of game?
So, you're spawning a new one when dropSet is -3. That's in PuyoScript so let's see where that's changed--
Yeah, no I'm out I'm not trying to make sense of this
this is an absolutely unmaintainable mess and will be basically impossible for anyone else to make sense of it
Not to mention the fact that you are repeating everything over and over again
was about to say, lots of redundant code
to the point that you are literally setting all of these booleans to false twice in a row inside of your horrifically repeated code blocks
I say this with absolutely no hints of irony, and as a 100% serious suggestion: All three of these scripts should be deleted and remade from scratch
Do not reference any old code, make them out of whole cloth. This is a slapdash mess of bandaids and no longer resembles programming in its current state
this is a code channel. do you perhaps mean to ask in #🖼️┃2d-tools ?
oops
Yo ! Do you know any famous/good written 3D games created in Unity that have the code open source ?
Lmao I'm asking here because I searched google and I didn't find anything meaningfull
really cause I find plenty
I'm asking for recommendations here not for a list... Therefor humans are better at this than google...
the human thing to do is doing your own research like all of us do
OMG ! For example I didn't know about this, you could just answer with this but putting a google reaction seams better...
Thanks
Unless you're trying to just rip code, I doubt you'll really find what you want in open source code.
um yeah if you're lazy thats on you
"guys where can i find open source projects"
doesn't know about searching on github
fr
Lmao that's crazy to think like that
yeah, i mean who wouldn't do literally the bare minimum to research open source software
Just want to see how people write code, and some precise part about handling animation end
My statement still stands. You really wont find what you're looking for. A lot of large games will mostly be unreadable because code will be scattered across. Editor tools might not be included, or stuff like animation events may be used.
Unless you dedicate a decent amount of time to actually learning the codebase
Ok
transform.localRotation = Quaternion.identity;
transform.localRotation *= Quaternion.FromToRotation(-attachTransform.forward, transform.forward);```
the code above has different results depending on if attachTransform is a child or grandchild of transform. Why?
attachTransform's world rotation does not change, only whether it is a direct child or a grandchild.
unless I'm wrong, transform.forward returns a world-space vector no?
Can you show the hierarchy?
Yes transform.forward is world space
grab point (attach transform) in grandchild v.s. direct child
transform is Kraber Magazine?
yes
And what are the two different results you see?
child v.s. grandchild (held at same angle)
one's basically backwards for some reason
hold on
i uh
may be incredibly stupid
yeahhhh
sorry @leaden ice
{
transform.parent = selectingObject.transform;
transform.localRotation = Quaternion.identity;
transform.localRotation *= Quaternion.FromToRotation(-attachTransform.forward, transform.forward);
//transform.localRotation *= Quaternion.Inverse(attachTransform.localRotation);
transform.position = selectingObject.transform.position + (transform.position - attachTransform.position);
if (useRigidbody)
{
attachedRigidbody.isKinematic = true;
}
}
else if (activating)
{
transform.parent = activatingObject.transform;
transform.localRotation = Quaternion.identity;
transform.localRotation *= Quaternion.Inverse(attachTransform.localRotation);
transform.position = activatingObject.transform.position + (transform.position - attachTransform.position);
if (useRigidbody)
{
attachedRigidbody.isKinematic = true;
}
}
else
{
Drop();
}```
what i wrote was in the if (selecting) portion
but the interaction is in the if (activating) portion so it just never actually changed anything
on a second note though, what is the best way to get the local rotation between 2 objects if one is not a direct child?
Quaternion.FromToRotation(-attachTransform.forward, transform.forward) did not work as i thought it would and is not consistent either
transform.localRotation *= Quaternion.Inverse(Quaternion.Inverse(transform.rotation) * attachTransform.rotation);
turns out this is the actual answer. Ive tried so many things involving quaternion.inverse and never thought about using it twice like that
why would anybody keep it open source if they have made something really good. you need to try to achieve it.
I have vsync disabled in quallity settings. Also trying to override in code just in case
Application.targetFrameRate = -1;
QualitySettings.vSyncCount = 0;
But I'm still seeing it drop down to a lower frame rate and wait for vsync in the profiler. Is there some other place I need to disable vsync?
In a build or in the editor?
my game has a save system and on some of my beta tester's builds the new game button doesn't work and the load game button freezes the player's character in the wrong place
i'm not sure why this is happening
sounds like you need to get to adding more logs and seeing whats happening for real. What you've described is what the beta tester probably said, as the dev you need to dig deeper. For a button not working, id first check to see if its covered by anything. Maybe they are on a different resolution, where things just shifted enough so that the button is covered by some invisible thing they are clicking instead.
For the other part you mentioned, this isnt enough information to suggest anything. Check for errors possibly, check to see if input is being registered. What is "freezing in the wrong place"?
its the code
this couldnt be more vague. Surely theres something more you've reached in your conclusions like if the data gets logged and is correct
you are giving very little information to go off of
SaveManager script
keep in mind this only happens on some peoples computers
everyone else's worked fine
my friend's specifications
Processor Information:
CPU Vendor: AuthenticAMD
CPU Brand: AMD Ryzen 9 7945HX with Radeon Graphics
Operating System Version:
Windows 11 (64 bit)
Video Card:
Driver: AMD Radeon(TM) 610M
DirectX Driver Name: nvldumd.dll
Driver Version: 31.0.24033.1003
DirectX Driver Version: 32.0.15.5585
Driver Date: 5 8 2024
OpenGL Version: 4.6
Desktop Color Depth: 32 bits per pixel
Monitor Refresh Rate: 240 Hz
DirectX Card: NVIDIA GeForce RTX 4090 Laptop GPU
VendorID: 0x10de
DeviceID: 0x2757
Revision: 0xa1
Number of Monitors: 1
Number of Logical Video Cards: 1
No SLI or Crossfire Detected
Primary Display Resolution: 2560 x 1440
Desktop Resolution: 2560 x 1440
Primary Display Size: 15.00" x 8.43" (17.17" diag), 38.1cm x 21.4cm (43.6cm diag)
Primary Bus: PCI Express 8x
Primary VRAM: 512 MB
Supported MSAA Modes: 2x 4x 8x
RAM: 31962 Mb
first thing !code
2nd is you shouldnt be using binaryformatter https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-8.0
But really i dont know what you're showing me this code for. My first message to you just said plainly what you need to do. Add more logs, and see whats actually happening. See whats running, see if any of those log errors get printed.
Anyone here wont just look at their pc specs and say "the lack of 3 monitors causes the issue".
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
should i use player prefs instead then
its entirely possible the code youve shown isnt even related to the problem. What debugging steps have you taken to even assume this code is the issue?
first i know by a video that the player CAN interact with the new game and load game button
new game doesnt work though when clicking
id assume you probably want binary writer.
🤷♂️ so does this mean you've done 0 debugging and just watched a video of someone click buttons?
I have done some debugging
The buttons are interacted with but no errors
ig ill switch to player prefabs
you need to start debugging a lot more about what specifically isnt working. Narrow it down to an exact line of code that isnt running, or is running with the wrong value. Im not sure how to make this more clear, that the fact a button isnt working isnt gonna help you find the issue
youve basically only said "button isnt working" then showed completely random code, that i cant even be sure is related to the button.
this function is literally linked to the button
when you press this button this function starts
Ok so you are claiming that the function starts, but also 10 minutes ago "new game doesnt work though when clicking". Do you see why i am telling you to debug more? You are assuming what is happening in code. What specifically doesnt work? What line of code? Figure this out then itll be more clear at least what the issue is
im trying to debug but the problem isnt replicated on mine or most of my other testers computers
Which is why you get their logs, not your own where everything works fine.
https://docs.unity3d.com/Manual/LogFiles.html
best case is you would be able to get access to their setup, and setup a development build where you can breakpoint exactly whats happening. Though if this isnt possible, you'll pretty much have to rely on log files and videos
Guys I am so so so sorry for off topic, but I could not find a better channel to ask this, so i will just ask it here, where can i find a channel to casually tlak or report a user? Staff font reply to DMs
@swift falcon Your last chance to read #📖┃code-of-conduct and stop spamming
... I already read, i did not spam, just how and when did i spam? I am reporting you or something. I asked you MULTIPLE time to explain me how i spammed and where can i find a proper channel. but you never did
#💻┃unity-talk message, YOu still did not answer my question
If you don't intend you use the server for Unity questions and spam off-topic instead you might as well leave now.
Your next post better be a valid server interaction.
I did and for the last time, I am not spamming, Spamming means repitedly dropping messages in a fast pace
mlssp166 was banned.
Hi guys, I'm having trouble with InputAction.GetBindingDisplayString
The sample uses legacy text for their key displays
But on mine, with it being TextMeshPro text, it somehow bugs and fails to display correctly
Is debugging printing out correctly?
Then you just need to make sure UI element large enough to fit
I don't quit get what you mean...
TMP has missing char issues
Like trying to display A/u25A1
Test by putting text manually. UI has options that wrap text to next line that can obscure, etc.
Ah, if it's a missing character you need to add it into font asset
Uhm no, that's not the case.
On Legacy text, it displays as A
On TextMeshPro text, it displays as A \u25A1
And on debug, it displays as A as well
Even if I added the character to the font, it's a character that wasn't supposed to be shown in the first place
hello, i am working with inventory and i have problem can someone help me? if you equip an item and then move the item in your inventory or drop it, it is still equiped
In my game there's an event on the inventory script that broadcasts slot changes
interesting
Unimportant for your usecase but I divide my inventory up into InventorySlotGroups
oh
Each slot group has an event telling slot changes, including change index
Not familiar with the problem. There are some search hits on similar problem on forums, search u25A1. You also might want to repost entire full question in #📲┃ui-ux . Someone might know there.
This one -> public Action<Itemstack, int> OnSlotModify;
Itemstack = The new itemstack
int = the slot index
There're legit many ways to do this tho, mine's just an example
Thank you
how could I detect if an object is "behind" another in 2d
like if I was to make a perpendicular line to an objects transform.up and check whether another object lay in front of or behind it
check layers
ah
if you are using an orthographic camera you can always use position.z for this
well im aware of how I can check for in front or behind in general for 3d space
im looking for in front or behind relative to a vector
Hey !
So i have an problem when i build my game :
In unity, when i run, i spawn and everything is good
When i build, and start the game, i'm blocked in menu and i need to click on server and on client
Why and how to fix it ?
PS: I use Fishnet and PlayFlow
Make a development build and look at the console for errors. Nobody can begin to 'why and how' fix this question with less information that you have.
This is the view in unity when someone launch the game but dont click on server and client :
Oh okay thanks , i will try it
do not cross post
then remove it from here
because people like you require it when they don't follow the rules
This is a community server, the active community members know and help enforce the rules.
Don't be upset because you were told to also follow said rules. Crossposting is not allowed.
And no, visual scripting shouldn't have severe performance. It's just code in the end.
hmm, not sure, I would love to see the code generated by visual scripting
Yeah, I don't actually know what happens behind the scenes
I'd assume it's not that big a difference. Or hope anyway, assuming you have a clean board
I've made node based systems and they are damn difficult to be made efficient
I will give the guys at Bolt the benefit of the doubt
unity visual scripting is all reflection-based, there's no codegen yet unless that changed in unity 6
there are third-party ones like unode that do codegen
if that is the case then there will be very significant performance implications
I'm pretty sure I've seen errors caused by code generated by visual scripting...
there is generated code as part of the package, but just node boiler plate for the editor iirc
ah, like how code is generated for other graphs (to define the nodes themselves, that is)

yeah, the graphs themselves are just unity assets
I remember seeing a Generated folder while helping someone with a weird shader graph problem
you might find it's not a problem for your game, like for my use case it's fine because we're not using it for anything high performance, just various simple game logic
if you do hit performance problems, i believe unode comes with a tool to convert unity visual script graphs to its own format, so you could maybe keep that as a backup option
I guess I'd say it's composition-based.
You don't create more specific kinds of GameObject
you attach components to game objects
Entities/GameObjects with components (EC) is probably the way to communicate it.
Does anybody have experiences with builidng packages? I having a small roadblock and I dont know how to fix it. I know that my code works but when I want to create a package with it Im missing dependencies and stuff
I wanna make a package out of my custom Visual Scripting Nodes but Its like I cant use the using of Unity.Visualscripting inside the script
It works outside of the package just fine
The name collision is very annoying!
If you have an Assembly Definition you need to add any package references you are using to it.
how?
in the inspector for the assembly definition
yeah okay I think I did that for Mathematics
Yup, same process
but there is no deffinition for Visual Scripting
Yes there is
where?
https://docs.unity3d.com/Packages/com.unity.visualscripting@1.9/manual/index.html#installation
com.unity.visualscripting
Is the Visual Scripting package installed in your project?
Yeah
As a package? Or as an asset in the asset folder?
yes package
it works with the same script which is not inside the package
also I imported like the mathematics in the assembly definition so yeah
you mean this part right?
if for some reason the picker isn't showing it, you can probably drag and drop the asmdef from the visual scripting package into an empty slot in the list, or edit the asmdef as json and just type it in
Yeah that^
yeah but freaking why
maybe just reinstall it then
is it installed as a dependency from some other package?
You can remove it, but it comes installed by default.
yeah yoiu can it's a normal package in the package manager
This is what I see
wow I freaking hate the package manager
How can I get the distance between an object in the scene view and the scene view camera ? 👀
anyone know
You should be able to get it from there yeah?
Creating a new Project its there
why 
anyway thanks for helping
I go the route with the new project
Hello guys I need help, I have this patrolling script in which enemy will go from point to point and when it comes to last point it will just stop. I want my enemy to go back to the first point and start looping and I also want my enemy to face where the point is because now he will just walk backwards to the point that is at the back of him for example. This is script: https://hastebin.com/share/abuwegolov.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Looks like it should loop back to the start based on your current code
Use Debug.Log to make sure current = (current + 1) % points.Length; is running
you're reassigning the value in the debug log with that, just do Debug.Log(current)
okay
I did that and now it gives value 1 and starts looping
idk how did he start looping now first 3 tries he didnt loop
I haven't touched Unity in a while, but wanted to ask if Animator controller is only official path to animating sprites. It looks like the legacy Animation component doesn't actually change the sprite in SpriteRenderer any longer. Surely there is a better workflow for sprite animation that I'm just not seeing.
The goal for me is use a FSM to change out AnimationClips in script without the overhead, and potential runtime errors, of setting up states and transitions in the editor.
These AnimationClips are also getting AnimationEvents generated at runtime, so any method of assigning them would need to respect those events.
A paid alternative is Animancer
You can make a custom animator system using the playables framework
It's a pretty neat package: you do all of your animation through code.
And that's basically what it is (:
Animamcer is a readymade solution that is built on top of playables, so are mechanim and timeline
Thanks for the recommendation for Animancer. Playables seems super verbose for something as simple as changing the index of a sprite sheet over time.
you could also just make lists of sprites :p
Yeah, it's hard to understand how something as simple as an out of the box 2d animation system doesn't exist.
The Animation component of old was really straightforward.
There is no general problem that is ‘simple’
the out of the box 2D animation system is the Animator
Well, it is a generic animation system 😄
and anything beyond animator but not quite mechanim is best done DIY in 5 lines of code
Isn't that still there?
it still is and its not even deprecated
It doesn't seem to change the sprite in SpriteRenderer any longer?
I'm in 2022.3.20f1
Also running Debian editor, but I haven't seen any runtime issues because of Linux. There are some editor bugs.
Can you provide more insight on the logic behind those 5 lines?
I honestly thought Animator and Mechanim were the same system.
Based on the documentation, it seems they are anyways.
Develop once, publish everywhere! Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations - publish to the web, Windows, OS X, Wii, Xbox 360, and iPhone with many more platforms to come.
All of this code seems to be specific to blending and additive effects. It's not showing the logic behind adding animation clips at runtime.
why don't you just make animation clips from your sprite sheets, put them in an animation component and activate/play the animation you want in a script?
Legacy Animation components do not update the sprite in SpriteRenderer
an animation clip change is nothing more than an instant blend
I'm not sure how to say it any differently than the legacy Animation no longer works with sprites.
You can make the clip, mark it as legacy, and attempt to play it with a sprite renderer attached and it will do nothing.
This looks like what I need
https://docs.unity3d.com/Manual/Playables-Examples.html
Thanks for the recommendation. I'm going to take a pass at the Playables and see if it hits all of my use cases. It's great that it doesn't take a dependency on basically an empty asset object.
Hey, is there any way to simplify it using a single StartSomething method without it being async?
private void StartSomething(IEnumerator coroutine) => StartSomething2(coroutine);
private async void StartSomething2(IEnumerator coroutine)
{
await MyTask(coroutine).ConfigureAwait(false);
test = false;
}
private async Task MyTask(IEnumerator value) { ... }
what are you trying to achieve? why can't it be async?
Use ContinueWith.
It still doesn't throw an error
I'm moving through an IEnumerator
what about StartCoroutine ?
It doesn't run in Editor properly
I know about that, it doesn't work
cries
ContinueWith has TaskContinuationOptions where you can specify for error handling.
there should never really be a need to use ContinueWith tbh, async does more or less the same thing with much better defaults
But honestly this code looks kind of weird so I'm not sure what the point is.
I have already tried using it, but its WaitForSeconds is only called in Update, which, for the Editor, is just called when any changes are made
Is this for an editor tool?
ah, I see
there's no real consistent update cycle at all, is there
The iterator functions passed to Editor Coroutines do not support yielding any of the instruction classes present inside the Unity Scripting API (e.g., WaitForSeconds, WaitForEndOfFrame), except for the CustomYieldInstruction derived classes with the MoveNext method implemented
sad
I presume that a custom yield instruction would only get MoveNext called whenever the editor decides to update
So, I've tried this, but it doesn't seem to throw an error when it's happening inside of MyTask
MyTask(coroutine).
ContinueWith(t => Console.WriteLine(t.Exception),
TaskContinuationOptions.OnlyOnFaulted);
The [initial approach](#archived-code-general message) using await with ConfigureAwait does catch it
It's never called?
The error is not thrown
But you can see the error being written to console right?
No, I don't see the error in the Unity console
It's just that the method stops from its execution
does Console.WriteLine do anything in unity? surely you want Debug.Log
When using the initial approach, it does stop, and the error is thrown
Damn
My bad
It does print the exception to the console, still, no exception is being thrown when done this way
MyTask(coroutine).ContinueWith(t =>
{
print(t.Exception);
throw new(t.Exception.Message, t.Exception);
},
TaskContinuationOptions.OnlyOnFaulted);
You can just throw it yourself or do whatever handling with the exception directly, no?
I mean, ultimately async/await just compiles to a state machine, so at worst you can just look at the compiler output and copy it.
(The whole use case still feels very weird to me though)
I have a class with a bunch of different Vector3s, and I want to consolidate it into a single class. However, when I do that, I don't now how to add it into a dictionary.
public class Foo
{
public class Bar
{
public int TestInt { get; set; }
public string TestString { get; set; }
public TestPositionData MyPosition { get; set; } = new TestPositionData();
}
public static Dictionary<int, Bar> Bars = new Dictionary<int, Bar>()
{
{ 1, new Bar{ TestInt = 1, TestString = "A", MyPosition.???} },
{ 2, new Bar{ TestInt = 2, TestString = "B", MyPosition.???} }
};
}
public class TestPositionData
{
public Vector3 PositionA { get; set; }
public Vector3 PositionB { get; set; }
public Vector3 PositionC { get; set; }
}
TestInt and TestString have the correct snytax when adding it to the dictionary. How do I set MyPosition.PositionA, MyPosition.PositionB, and MyPosition.PositionC directly into the dictionary?
you would need to construct a new TestPositionData there
somethingl ike MyPosition = new TestPositionData() { PositionA = Vector3.one }
Now I'm just trying to get the syntax on your suggestion correct.
Not enough closing braces
public static Dictionary<int, Bar> Bars = new Dictionary<int, Bar>()
{
{ 1, new Bar{ TestInt = 1, TestString = "A", MyPosition = new TestPositionData() { PositionA = new Vector3(0, 0, 0) } } },
{ 2, new Bar{ TestInt = 2, TestString = "B"} }
};
I think I got it.
Thank you Fen. 😃
Yeah, it's already cluttered enough as it is so I'll get rid of that.
Any reason why line 71 would return the Element 5 on the first iteration of the for loop?
you are modifying the prefab itself
that seems weird
You're throwing out the new instance
it it going bye-bye
I bet you draw six cards
you're seeing the card that you wrote into cardPrefab in the last iteration of the loop from the last time you ran it
(okay, if we're 1-indexing, then you're drawing 5 cards)
Do not modify the prefab.
Instantiate returns a copy of the prefab
You should store the return value from Instantiate and modify that
modify the copy
I'm loading the prefab with new info
Yes, you are!
And it's producing nonsense results
You need to modify the new instance
ahhhhh
i shall return in a timely matter
I'll probably rename newCard at some point but this worked. thank you 😛
Heya. I would like to make prototype of games like They Are Billions. Any advice on the approach I can take for having potentially thousands of units on screen with collision and such? I recently started checking out DOTS but are there other approaches?
I need to try that out myself
One thing to consider is to manually draw the enemies instead of using a crapload of individual MeshRenderers/SpriteRenderers
oh wait,
I am not very experienced here, though.
ECS is the best but you can get away with a lot by using only bits and pieces of DOTS like the job system and things like compute shaders and DrawMeshInstancedIndirect.
Also I love that game glad to see it mentioned
yeah -- you can absolutely do hybrid setups
I experimented with a "3 bajillion enemies" game with DOTS
the player was 100% normal GameObjects
What do you mean by throwing it myself? That's exactly what I'm doing though? Throwing an error within ContinueWith just doesn't seem to do anything
It's just that I'm moving through an IEnumerator with asyncs
private async Task MyTask(IEnumerator value)
{
while (value.MoveNext())
{
if (value.Current is IEnumerator enumerator)
await MyTask(enumerator);
await Task.Delay(20);
}
}
Having some coding issues atm with this code. The Error I am getting is sthis
Trying to make some grass atm
write the loop so it makes sense
Are you sure it's C# syntax?
what is : supposed to do ?
Yea I am trying to do gpu instancing for grass
I guess : is used in a foreach loop for some languages as in in C#
have you used a List before ?
not really in the dark with this mostly
Your list contains items, which are List<Matrix4x4>. You can check that out by using var
So you can just call 2 loops
So just do foreach (var batch in Batches)
Performance for what?
foreach (List<Matrix4x4> batch in Batches)
{
foreach (Matrix4x4 matrix in batch)
{
}
}
Batches.ForEach(b => b.ForEach(m =>
{
}));
I am trying to load a ton of grass in a scene
What does that suppoused to do with syntax error
I think they're mixing it up with languages that put the type after the name in declarations
Like let x: int32 = 45
go?
idk, I made that syntax up, but it surely exists somewhere
oh wait go doesn't use :
var b, c int = 1, 2
Unity Cloud server functions API uses Go 
typescript/rust/python iirc
Rust but with i32
Hey ! i would like to, create an updater but how can i do that if i want remplace every file even the executor ? (like an self update) In this way, with 1 download, we can have always the latest version
Make the user direct where the install folder is and replace all the files with the new ones ?
You'd have to handle things like files while in use
No, only click on "update" and every files will be update
maybe I was thinking of creating a temporary file to run code
thought you were making an updater app separately than unity
btw if you use addressables you can just replace specific files instead, no need to update the whole build
yeah of course! but if i want update the "game launcher" with updater , i have to as kto everyone to download again the game launcher ?
no you stream the update to the game launcher
ideally with an API call to your versioning
making a launcher, especially a bad one might deter players so be careful with that
So i can create an Game Launcher who can update itself by an API and update the game ?
Interesting ! I wanted create a game launcher but i trought is was better to have it in my game
if you do it in-game go with the addressables maybe
Thanks for the link ! 
do note in some cases it might be better to just update the whole build
for now, its a very light game so its more for later ^^
Hi guys, how is input rebinding intended to be used? The rebinding sample changes the binding referenced by an InputActionReference, I don't understand how this works
The input I created elsewhere isn't the one referenced thus leading to the rebinding to apply to an unused instance
Is there a specific instance that the InputActionReference points to that I can find? Was I meant to use that one?
input system covers both
can someone who has coded an rpg tell me the logic behind creating a pokemon style battle system in unity 2d
you want someone to give a whole thesis on how the logic of an rpg works
These kinda stuff has too many ways...
yes
thats something you can easily google, cause as mentioned above there are dozens of ways to accomplish something
you have an easier time getting help on a specific part of code you're stuck on
understood
I am rewriting my "IK Manager" class. It's going to support multiple different IK components, and different kinds of components are identified differently
For example, a generic chain IK is just going to be identified by the last bone in the chain
there's also a full-body biped IK component that controls all of the limbs, and so I identify which limb I'm moving with an enum
so right now I've got this, basically
public void SetTarget(FullBodyBipedEffector effectorID, Transform target)
{
if (bipedIKControlMap.TryGetValue(effectorID, out var controller))
controller.SetTarget(target);
}
public void SetTarget(Transform tipBone, Transform target)
{
if (chainControlMap.TryGetValue(tipBone, out var controller))
controller.SetTarget(target);
}
This is fine.
However, I'm finding it annoying to allow other components to flexibly use both kinds of IK
I have a component for pulling a lever. For a humanoid, it wants to use a full body biped IK's right hand. For a non-humanoid, it will need to use a different kind of IK to control a robot arm or whatever
I need to be able to configure both kinds of IK interaction on this "pull lever" component
I had the thought to just do this:
[System.Serializable]
public abstract class IKSelector : IPolymorphic
{
}
[System.Serializable]
public class FullBodyBipedEffectorIKSelector : IKSelector
{
public FullBodyBipedEffector effector;
}
[System.Serializable]
public class TransformIKSelector : IKSelector
{
public Transform tipBone;
}
and then...
public void SetTarget(IKSelector selector, Transform target)
{
if (selector is FullBodyBipedEffectorIKSelector fullBodySelector)
if (bipedIKControlMap.TryGetValue(fullBodySelector.effector, out var controller))
controller.SetTarget(target);
if (selector is TransformIKSelector transformSelector)
if (chainControlMap.TryGetValue(transformSelector.tipBone, out var controller))
controller.SetTarget(target);
}
and I...guess this works? it just feels kind of weird
this is a lot like making an algebraic datatype in a language like Haskell though
(IPolymorphic gives me a dropdown selector when used with [SerializeReference])
@gray mural
Update ^^: I have setup the server and the client.
Now we can play with other player on the map like a real MMO ^^ I need to work on spawn mob and all mechanics about it ^^
Good luck!
I still don't know what to do with my code: Whenever I try to rotate my gameObject, it spawns a clone of it. Here's the code: https://pastecode.io/s/09qwryx7 https://pastecode.io/s/z4i3hhyd https://pastecode.io/s/nwottz8w
we told you what to do. #💻┃code-beginner message
#archived-code-general message
Nuke the code, start over with something that makes sense
don't write redundant WET code
You ended up not understanding your own code, thats how you know is especially bad if you've written it yourself
You are now seeing the reason its HEAVILY suggested to do basic programming first, and even basic problems, before unity.
This code is complete spaghetti, you are trying to rotate an object and its spawning something? Its pointed out everytime you post code.
I tell so many people this, you'll waste HOURS debugging complete garbage code, compared to just learning how to properly code in those few hours and having something decent
Although really, we also know you havent debugged anything in there, even though it's been suggested before.
The sunk cost grows and grows
I have completely restarted projects far further along than this multiple times. Or reverted to an earlier state MANY times.
That is part of progress.
Can't be afraid of restarting
anyone ever had the issue with nav mesh agent where setting the destination immediately teleports the agent there? even on a blank test script (with the speed at 2) it just warps immediately
someone was talking about this in #🤖┃ai-navigation recently
maybe you have similar problems
I'm not aware of anything that'd cause this, though
ill move there
Update: The problem is that Spawn = True, but I don't know what's causing this.
Guys this may be a stupid one but I have both
using UnityEngine;
using UnityEngine.SceneManagement;
however I am getting SceneTools does not exist in the current context
Was it removed in 6.0?
What is SceneTools, I don’t think that was ever a thing
Do you mean SceneManager?
Nothing relevant for SceneTools on Google, maybe you had a package or custom assembly installed?
Definitely not part of unity
Hello, I have a problem which I'm trying to solve which I thought I could use Physics.Raycast for, and I don't get why my approach is not working :
I'm generating a bunch of tiles with edges surrounding them, but for some cases it generates incorrect tiles, so I delete them under a certain condition. However I have
the edges surrounding the deleted tiles present in the scene, and I want to delete edges that are not surrounding anything. The solution I thought about is to use Physics.Raycast on both side of each edge to perform a check if it's enclosing a tile (I attach a collider to all tiles). For some reason, as you can see on the picture above, it works in most cases but there are a few edges that are not deleted and I don't understand why, it's seems that the raycast detects something even though nothing is there
Is that near the origin? I wonder if the physics world is out-of-date when you do the raycast
notably
var tile = Instantiate(myPrefab, Vector3.zero, Quaternion.identity);
tile.transform.position = Vector3.right * 100f;
Physics.Raycast(Vector3.up, Vector3.down, 100); // this hits the tile!
Calling Physics.SyncTransforms(); gets everything up to date
I set up automatic physics sync transforms in the settings but I'll check with this again
wdym near the origin?
didn't work rip
I know what it means haha but why are you saying it?
omgggg
Because if you instantiated your hexes and then moved them, they'd all be left at [0,0,0] in the eyes of the physics system
wait I'll check the settings
(or wherever the hexes appeared at)
I create the meshes on the locations I get from a voronoi diagram library
the weird part is that some edges do get deleted like they are supposed to so I think it's got smth to do with the physics system
are you drawing a red ray when it misses?
if so, the raycast is working fine
oh, they're all red
i'm bad with red and green
Try making it draw a different color if the raycast hits
that will reveal if it's a bug with your logic afterwards
yeah maybe raycasting is not suitable in my case where everything is done in the start frame
Consider logging what you're actually hitting
Does anyone here know if Shadergraph Fullscreen shaers work on mobile?
Quest to be speific
yo thx for your help I managed to "solve" it by delaying the function calling the raycasts
Here we go again. Also this conversation belongs in #💻┃unity-talk.
Instead of baiting with a vague open ended question, maybe explain what you're worried about?
(And if it's the "pricing changes you're going to go bankrupt with", you can read this: https://unity.com/products/pricing-updates )
only in build, editor is uncapped no vsync
Hey, i have a Problem with my Character Controller. When i'm Jumping while Moving im Jumping slightly lower than if i'm standing still. Does anybody know why this happens?
{
if (movement.y > 0)
{
Vector3 dir = playercamera.transform.forward;
dir.y = 0;
force = force + dir;
//m_Rigidbody.AddForce(dir.normalized * speed);
}
if (movement.x < 0)
{
Vector3 dir = playercamera.transform.right;
dir.y = 0;
dir *= -1f;
force = force + dir;
//m_Rigidbody.AddForce(dir.normalized * -1f * speed);
}
if (movement.y < 0)
{
Vector3 dir = playercamera.forward;
dir.y = 0;
dir *= -1f;
force = force + dir;
//m_Rigidbody.AddForce(dir.normalized * -1f * speed);
}
if (movement.x > 0)
{
Vector3 dir = playercamera.transform.right;
dir.y = 0;
force = force + dir;
//m_Rigidbody.AddForce(dir.normalized * speed);
}
if (doesjump > 0f && Jump)
{
Vector3 velocity = m_Rigidbody.velocity;
velocity.y = 0;
m_Rigidbody.velocity = velocity;
m_Rigidbody.AddForce(transform.up * height*50f);
Jump = false;
}
m_Rigidbody.AddForce(force.normalized * speed);
force = new Vector3(0f, 0f, 0f);
am i allowed to copy paste a full reddit post describing my problem or should i just link the thread. trying to get help asap lol
Describe your problem concisely, and link the post
i think i explained it concisely in the post and i tried to explain what i think is wrong and how i tried to fix it
feel like i’m missing something fundamental
i have a rope linking a player and a collider, the rope should stretch if the player moves away from the max distance but the rope isn’t stretching or growing despite the fact that my debug statements somehow say it’s moving further away (even though it’s physically in the same place)
hey guys would anyone know how to https://pastebin.com/UfmWhxrA
make some minor change such that it loads the assets into the current scene and not a new scene?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
It's some boiler plate code I found that I need a small change too
right now it creates a seperate scene and loads that, but this doesn't work for my use case of multiplayer scene management, so I need someway to just basically import the asset/scene into my current/main scene
is there just a general help channel? Im trying to fix my slider UI
my health bar slider is starting at the edge but when it reaches value of 1 (full) it sits in the right spot?
I have a question for those that are familiar with unity's physics system, particularly with the drag value of RigidBody2D. In my InAirState script, I am capping the horizontal velocity of my character whenever it reaches it's max speed. However, drag is reducing the value that I have set at the end of FixedUpdate, to a value below the max. A solution to this issue would be to set the drag to zero, but this makes my jumps higher than intended. Is there a way to solve this issue without reducing drag? Here is my script and some related ones https://gdl.space/niyeqoyohi.cs, https://gdl.space/kigoxizevi.cs, https://gdl.space/udolejurep.cpp
wdym right spot
which one is health the red green or blue
the red is the health bar, The green and blue bar are sitting in the correct spot (because I havent added slider to them yet). I want the red bar to start and end where the other bars are
yea its just being pushed back instead of starting where it should. As the value increases the health bar moves into its correct place where the others are
did u make a direct copy of the other ones and then move it up and change color
ive got the fill color set to stretch
I made the health bar first and copied the other 2 from that, but those dont have sliders on them yet
When its on max value its in the correct spot but idk why its out of position when it starts
how do you create these types of UI elements again? If I'm remembering correctly there is a class that allows you to create very simple UI like this in code, but Im forgetting what its called and cant find it online.
There is UGui, and UIToolkit. You can do both in code really, but UIToolkit uses language like html and css (uxml and uss).
That being said, I would not call that a simple ui. Lots of logic involved in that, rather than just showing values
this is the older gui
https://docs.unity3d.com/ScriptReference/GUI.Button.html
Ideally you should use the Canvas / UI Toolkit
these are only okay for testing
ahh okay, didnt realize it was depricated. The only reason Im trying to use it is since Im making a mod for another game and just needed a very simple ui button
Does anyone know an equation to handle drag in the same way that unity does?
I googled it and tried out RB.velocity **= 1/(1 + Time.fixedDeltaTime * * dragValue ), but this formula didn't work
didnt work in what way? also where did you find this formula, it doesnt really look right and is different from what i see online
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
start with pathways
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You'd probably want to provide more information like the code for instance.
look at the #854851968446365696 on what you should include in questions. We'd need to see more of the setup like code, how you pick up items or drop them. I assume you duplicate the item
!code the readme also says the same for large code blocks. Though really, you should narrow it down to a related sections. posting it all in a link is fine, if you at least say where to look and whats relevant. not many people are gonna read through that much code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nvm i fixed it
Hey, what could be the reason of my Header attributes not showing in the editor?
The Inspector isn't set to Debug mode
A custom inspector perhaps?
Not sure, the class is derived from FishNet's NetworkBehaviour, so that might be the issue
I need a enemy follow player script
using UnityEngine;
public class EnemyController : MonoBehaviour
{
private void Update()
{
if (Physics.SphereCast(transform.position, float.MaxValue,
transform.forward, out RaycastHit hitInfo))
transform.position = hitInfo.transform.position;
}
}
Hello everyone! My VS 2022 has stopped autocompleting when I press tab. It instead cycles through selectable things. Intellisense does work, it suggests code.
Hey guys,
I'm implementing fishing system. I have characters animations for fishing and rod animations separately.
Does it make sense to use separate animators on each with same states and transitions and just set triggers or bools for transiting between them ? Will they be in synced ? (Animations length are same in both the rod and the character for the each kind of animation)
https://paste.ofcode.org/34RZXLaS2mZyBG7tjsP5LtK i have this script and in GetPickaxeSprite it tells me item is null. I assigned the iconList in the Inspector
post the actual error, screenshot the console
i logged the name before in the foreach loop
it tells me the second element then this
The error does not match your code but assiming line 103 is line 102 it means item is null so you have a null item in your array
but idk why
its from before i had a extra line to log it
that is why we debug. Add a null check
Might also want to print the name of the object that the code runs on
hello guys. I have a problem. I have a unity project and i dont konw how to setup a click event, because the design has changed from unity itself. I have 2 images and i want to have it like the old design (marked with red). Someone can help me with it?
why that
Because you might have this script running on some other object that has a null reference in the array
true
doing now
foreach (var item in iconList)
{
if (item == null) Debug.Log("An item is null" + gameObject.name);
}
no other object
is there a problem with an in inspector assigned list?
Then the item is null
try logging the index of the item
Not necessarily. It could be null temporarily for example.
Ideally you want to step through with a debugger
i just noticed they got reset when starting, didnt happen before
Do you have the inspector in debug mode perhaps?
your code does have this in Start.
iconList = new PickaxeIcon[iconList.Length];
that's why
worked, i made a thinking mistake
ye
that was it
how can i check this?
sword.transform.parent = transform.GetChild();
if the child is also a parent then would it work if I put the total index number of the child inside the transform?
what are you trying to do, because that is invalid code
trying to make an object as child of another object
I know that, but which child should become the parent?
sword is an inherited gameobject
Trying to become the child of the object this script is attached in
then why GetChild ? just use transform
child in the transform
i think you are misunderstanding
sword.transform.parent = transform; // set sword as child of transform
sword.transform.parent = transform.GetChild(0); // set sword as child of child zero of transform. (Grandchild of transform)
I mean make the child inside the child as parent
what?
Let's say the script is on forearm.R
I want the sword as child of the index1.R
presuming you just forgot to mention the 001 bit of the names
sword.transform.parent = transform.GetChild(0).GetChild(0);
I see thx
you do realize this will go bang if those children don't exist or are organized differently
it would be significantly better to store a reference to the transform you're attaching the sword to
rather than rooting around in the hierarchy like you're mining for coal
which script is more performant? ```
using UnityEngine;
public class Script1 : MonoBehaviour
{
private Manager manager => GetComponent<Manager>();
private void Update()
{
if(manager.b != null)
{
mananager.b.Func();
}
}
}
using UnityEngine;
public class Script2 : MonoBehaviour
{
private Manager manager => GetComponent<Manager>();
private B b;
private void Awake()
{
b = manager.Resolve<B>();
}
private void Update()
{
if(b != null)
{
b.Func();
}
}
}
using UnityEngine;
public class Manager: MonoBehaviour
{
public B b;
}```
The second one, since the first one calls GetComponent every frame. But the difference is probably not very noticible.
Hello, just to make sure. These 2 variants do have 1 frame difference in in time, right?
WaitForSeconds(2f);
WaitForSeconds(1f);
WaitForSeconds(1f);
So Unity doesn't call the 2nd IEnumerator in the same frame when the 1st's MoveNext returns false, it waits a frame instead?
They will have a difference yes
more than one frame
In the 2nd variant, you get the Component only once, in Awake. In the 1st variant, the Component is gotten every time you access the getter of the property, in your case, every Update, which acts the same way as the method. So the 1st variant is much worse
WaitForSeconds waits until the next frame after N seconds have passed
Why would the difference be more than 1 frame though?
So you'll get like:
2.01 seconds (assuming frame error of .01 second)
vs
1.01 + 1.01 seconds
well one thing also is that frames are not consistent durations
I see, I wasn't assuming the errors
so if the frame error for the first wait is longer than a later frame, it could be 2 or more frames
The 2nd variant should get 1.01 + 0.01 + 1.01 this way though
It just depends on the luck of where the frames land basically
Are you sure about that?
Yes
because script 2 gets B just once right?
I see, so it doesn't move to the next IEnumerator in the same frame. Thank you
in script 1 it gets that B through manager but every frame
Yeah, I'm sorry, I have confused 1st and 2nd script. You can reread my message and replace every 1 by 2, and 2 by 1
note that these aren't necessarily functionally equivalent. If manager.b ever changes after Awake, the second script will not pick up that change.
B is always the same
Yes
so conclusion is that script 2 is better? => storing local variable and then get it once is better
But regardles of B staying the same or not, b stays the same
If we're talking about the performance, yes, it is
okay, thanks!
Just make sure that b is changed when the different value for manager.Resolve<B> can be gotten
And it would be better to simply remove the property
As I don't see whether you need it
I'd disagree about the "much worse". It is worse, but the impact this one difference would have is probably barely noticeable if at all.
Not saying that you should use the first variant. You should definitely cache your references whenever possible. But it's important to understand that it's not gonna explode your game.
I would move away from using OnCollisionEnter and OnCollisionExit for ground checking. What if your head hits the ceiling..
Oh, and its gone
If you hit your head, the player will forgive the character for mistakenly thinking it is on the ground, since the character likely has a concussion.
i put the collisonenter and collisionexit in another gameobject called groundcheck and its a small box collider on the players feet
that should solve it
😂
Ah gotcha. So the code you showed is two scripts?
https://pastebin.com/f8DLrzKM this is the groundcheck script
https://pastebin.com/g4PgLBKJ this is the player script
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yeah, just consider applying the changes I've told you about
Yeah, that works then, and avoids the issue I mentioned
i did
I cannot see it on the scripts you've sent though
oh i didnt update them yet
will do in a sec
Unless you jump high enough to clip through the ceiling and getting stuck in it, since it will be considered grounded
i updated it now
Just wanted to report back and say Playables are definitely the way to go for simple sprite animations, if you want to handle them in code. I was able to implement it yesterday and it seems to work well. There is a gotcha associated with setting time on AnimationClipPlayable objects, but that was the only real issue encountered.
I would have a reference to your feet in the PlayerMovement script, and add the GroundCheck script to it in Awake.
private void Awake()
{
GroundCheck groundCheck = feet.AddComponent<GroundCheck>();
groundCheck.playerMovement = this;
}
Then assign its playerMovement reference and access isGrounded and groundLayer from it.
private void OnCollisionEnter2D(Collision2D collision) => SetGrounded(collision, true);
private void OnCollisionExit2D(Collision2D collision) => SetGrounded(collision, false);
private void SetGrounded(Collision2D collision, bool value)
{
if (collision.layer == playerMovement.groundLayer)
playerMovement.isGrounded = value;
}
Of course but every bit counts
what difference will this make?
erm. I'm pretty sure MoveTowards exists
Of course, it's going to "exlode" your game if done with every variable possible
Not when you have bigger problems in the project.
If your intention is to optimize the game, you should start from profiling it. Not changing random code.
Also this is for readability
Because more and more code there is the more confusing it gets
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
alr bet
Hey everyone! Trying to be able to get a variable FROM a class by name rather than hardcoding shit and it be a pain (so, like if i called GetVariableByName(keyName, className), the class i'm trying to find is what 'className' is, and the variable i'm tryna find is what 'keyName' is.)
Alright so here's the whole script: https://hastebin.com/share/ubexozaqob.csharp
But any time i call GetVariableByName() it comes back as null - i would search as to why but to be honest I have no idea what I'm doing or why i wrote what i wrote. I'd love to know how or why what i did is not doing what its meant to did
if you need more info do let me know
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What debugging steps did you take so far?
I'm not going to say that if you're gonna use that widely in your project as a replacement to normal accessing methods, it's gonna be terrible. I assume you know it and have a specific use case.
- checked that the lists we're accessing are not null
- checked that all properties inside said lists 100% exist
- Checking what keyName and className we're passing, they're correct
Is this the only thing bothering you in the method I've provided?
So does it enter any of the if statements here?
if (property != null)
{
object value = property.GetValue(root, null);
if (value != null)
{
return value.ToString();
}
}
return null;
It's just for one feature - skinning (so altering the color/sprite/whatever of gameobjects). All gameobjects have an ApplyColor.cs if they need to be changed. They have a keyName and className to fetch which i give to them manually through the inspector.
enters the first property check
This prevents from from the requirement to add the GroundCheck script manually
ah ic ic, thanks for the headsup
None of the classes posted here actually have properties in them, they're all fields. So GetProperty() won't be finding anything. For reference, a property declares accessors:
public int SampleProperty { get; set; }
What you have don't have accessors, so they're all fields
OHHHHH
okayy, i'll do that then -- thankss SPR
It's not a one specific class. It's a gameobject with some components(I think a UI image) and some default settings.
So how would I reference it?
And GameObject doesn't even work
Depends on what exactly in it you want to reference.
you can reference its RectTransform.
Not sure what you mean by size of it, but GameObject should work as a reference
When I can figure out how to get it I can try and get its RectTransform
Yes
What type does it have?
GameObject
Share the code
Attempting to select the panel
public GameObject simulationVisualCanvas;
It's in a ScriptableObject
You can't reference scene objects from outside the scene.
Ultimately the problem I'm trying to solve is I want a box for the simulation (ie the green area) which can be dynamicly sized and accessed from the code - How is this typically done?
Referenced somewhere in the scene.
Your code should be in the scene as well
Can't say anything else without knowing the context
My simulation code is in the scene, as a script, I'm just wondering what kind of box/container is used to manage components that can be resized
is it UI or non-ui ?
Hey guys, any idea why in the game view (using the camera), the line renderer doesn t render some parts of it, while in the scene, it s perfectly fine?
Is what ui?
Well "components that can be resized" is a very vague definition. What component exactly? Are they ui Image components?
not a code question #💻┃unity-talk
Bear with me, I'm trying to comprehend this myself
Here I have a panel (green) representing the simulation field - I want to be able to get the size of this panel, and to be able to resize this panel as well
The panel contains 2d game object organisms
Maybe start simpler and go through unity !learn beginner pathways. It's gonna be very hard to help you if you don't understand the basic terminology
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Also, you might not need help at all if you do proper learning. Killing 2 stones with one bird
The problem is I'm doing this for a dissertation and to be honest its not about how it looks per se, I'm focusing on the neural network side for the entire project, but trying to get it all visually is taking bloody ages because of this steep learning curve
The dissertation is like 90% theory and neural network but ultimately I'm spending all my time trying to build a graphic for it
It's not really steep. You just need to spend a day or two on learning the basics of working with the engine(assuming programming is not an issue).
You can't jump into a professional software and hope to get something working of it by randomly pushing buttons. That's not how it works.
Does Unity still wait for 1 frame after moving through all IEnumerators in a Coroutine when no MoveNext is available?
WaitForSecond(1f);
WaitForSeconds(1f);
// 1 frame
// stop
which, tbh, if you are doing anything with Neural Nets, you should already know
why not test it
Okay, I'll do some learning into unity
if you yield return new WaitForSeconds(1f);, Unity will wait for 1 second before calling MoveNext again.
At that point MoveNext will return false
I'm not really clear what you're asking about here, though
How would I test it?
I suppose, but my use for unity is pretty simply - Literally a couple entities moving about a screen, not much more
It calls MoveNext every frame, not every second
show me the code you're actually running
this code does not make any sense to me
It checks whether WaitForSeconds has finished executing by calling its bool MoveNext every frame
maybe try counting the frames between?
Neural Nets are serious tech. So I would assume a very good knowledge of 'not so serious tech' to back that up with
but yeah unclear what you're even going for here or what problem you're experiencing
If your intention is for it to continue exactly after 1 sec then that's unlikely to happen.
Well, of course
Unity is not precise
Not sure what you're getting at here
That's why WaitForSeconds doesn't work in Editor, which just calls Update when any change was done
No MoveNext is called in this case when you're doing nothing in Editor
i still don't understand what your problem is or what you're asking about
There are editor coroutines package btw. For editor coroutines
what I'm getting at is not knowing common terms like Ui and UX and not realizing you need to learn software before trying to use it
You don't really need to get into the guts of the coroutines. All you need to know is that it would resume on the first frame when the condition is satisfied
Unity waits for a frame after getting false from an IEnumerator's MoveNext, then moves on to the next one. I wanted to make sure whether it still waits for a frame when no next IEnumerator available
If MoveNext was called every frame, it would resume the coroutine and run it to the next available yield each frame. It waits until the second has passed before calling MoveNext again
And I have mentioned why its WaitForSeconds doesn't work properly in the previous message
https://docs.unity3d.com/Manual/ExecutionOrder.html
might help you as well, shows all the yields
is it coding, sons
Are you talking about this kind of situation?
public IEnumerator CoroutineMethod() {
Debug.Log(Time.frameCount);
yield return AnotherMethod();
Debug.Log(Time.frameCount);
yield return AnotherMethod();
Debug.Log(Time.frameCount);
}
public IEnumerator AnotherMethod() {
yield return null;
yield return null;
}
Is this for me specifically?
yield The coroutine will continue after all Update functions have been called on the next frame.
yield WaitForSeconds Continue after a specified time delay, after all Update functions have been called for the frame
etc.
no, not at all, just a general observation
so apparently all yeilds wait for the Update to finish
Ok, ok, I get you, yes a classic thing is people seeing something cool and wanting to be able to create it from scratch themselves without having sufficient prior knowledge
There is a class CustomYieldInstruction with an abstract bool keepWaiting, which, according to its documentation
is queried each frame after MonoBehaviour.Update and before MonoBehaviour.LateUpdate
This class also has a methodMoveNext, which references the boolean
public bool MoveNext() => keepWaiting;
you can see where the yield run
mesh renderer sorting layer not working?
White square sprite and green square mesh are on thesame sorting layer but different order, but still they intersect. Why?
Z fighting
Yes, probably
Because IEnumerators are really compiled into a big state machine class that really advances the state to the next yield when you call MoveNext on it
please do elaborate
The example with MoveNext is not a custom yield instruction.
actually , is the big white squae a mesh and the tilemap sprites?
also this isn't code related
Sorting layers only work with orthographic cameras and geometry oriented orthogonally towards the camera afaik.
white square is a sprite, its not a tilemap, although similar, it is my own custom tilemap made of meshes
yeah not sure layer order would affect the scene view
Ah, you were looking inside CustomYieldInstruction. I see now.
So you're saying it doesn't start a timer in its constructor and simply check for the timer being completed in its bool MoveNext?
try shifting whatever you want slightly forward on Z
camera is currently ortho.
ohh its meshes?
then Order In Layer will not affect it
Mesh Renderer doesn't care about that only sprite renderer
YieldInstruction is decompiled, so, I suppose it still does the same?
It runs MoveNext() to see if there's any code left to run in the enumerator. Then it accesses current to see what was yielded by the enumerator
I see
When you yield an IEnumerator from a coroutine method, Unity will start polling its MoveNext() method until it returns false. Once it does, it goes back to the original enumerator.
just noticed, in game view its a bit different, but still cant affect the ordering
Yes that is what @cosmic rain mentioned, it would only work on Game Cam
You can make the scene cam orthographic too
So is there nothing I can do to order the meshes?
I want to have multiple meshes ontop one another
are they sprite renderer or mesh render ? im confused
the white square is sprite renderer, the green mesh is mesh renderer
You should just position one in front of the other.
i believe thereis a render order on the shader though
so best bet is just to modify the transform?
will culling still take place?
culling is frustrum-based (i.e. based on what's on the screen)
well, there is also occlusion-culling
so it would
but that is baked in advance for static geometry
I see, so it stops right after the IEnumerator is finished and doesn't wait for 1 more frame. This clears the things up for me, thank you
Right. I wondered if using something like this would cause a delay, but I haven't managed to cause one yet:
public IEnumerator CoroutineMethod()
{
Debug.Log(Time.frameCount);
yield return StartCoroutine(AnotherMethod());
Debug.Log(Time.frameCount);
yield return StartCoroutine(AnotherMethod());
Debug.Log(Time.frameCount);
}
public IEnumerator AnotherMethod()
{
yield return null;
yield return null;
}
Ah, it makes sense because Unity is not doing this:
- check if CoroutineMethod can resume
- advance AnotherMethod
It's just advancing AnotherMethod, and the moment it's done, it advances CoroutineMethod
Do Unity's Coroutines use async?
when sorting via z positioning (in my case Y), it there a good number to layer above? or should I find the smallest number possible?
No, they don't use async at all
There is Awaitable (2023.2+), which lets you handle async methods more like coroutine methods
I'm still a bit unclear on the technical details of async.
Is it's 2023.2+, then Unity's Coroutines surely don't use it
yeah they dont need to be that far apart IMO
depends what you're going for, the smallest number could potentially be all you need anyway
roger, thanks!
Just note that some platforms might behave differently and need a bigger distance.
Otherwise there might be z fighting.
The closer your near and far clip planes are, the closer you can place objects without getting z-fighting
(of course, that means you have less space to place your objects!)
you can't cheat the system (:
My brain can't syntax right now but I feel like this is where I'd put a check for a coyote timer right??
Feels like it should be obvious but I've been using Godot for the better part of a year and kinda forgot.
If the player becomes ungrounded and makes a jump, you can check the coyote timer to see if you can give the player a free jump
I know you didn't ask, but two points of advice:
- Curly braces should generally be on the same line for readability
{
// Code
}
- Enumerations should be used for integers that represent stages, such as
jumpPhase = 0. Instead, it could readif (jumpPhase == JumpPhase.PreJump)orif (jumpPhase == Jumpphase.MidAir
Enumerations* aka enums
Oops yeah, correcting
Theres no readability aspect to this, it's just convention. C# convention has it on the next line, and this is by default in VS. Other languages do it on the same line, it's the default in VSCode.
It's absolutely readability, but it's also convention.
Nope, 0 readability aspect to it. It's simply more or less readable because you are used to it. I find same line completely unreadable these days, because I do next line. In uni I used languages which did it on the same line, at the time I thought it was readable
In University I used
public void Example() {
// Code here
}
And I was used to it, but it is simply less readable than matching braces.
Readability as in consistency 😄
Matching blocks of code requires scanning side to side instead of simply following the vertical space down. Largely preference, but readability is a non-zero factor.
Unless you do a case study where you ask random people which is more understandable, theres no debate about it. It's simply just what you're used to, because it's where you subconsciously expect it to be
Anyways I appreciate the input.
Almost all C# libs uses Allman style so you might as well too
If you are writing in Rust or Java that's different story
I was used to K&R first, and forced to adapt to Allman style, allman is more readable. Seems nonsensical to argue that K&R is more readable
public class ExampleClass {
public void ExampleMethod() {
if (condition1) {
for (int i = 0; i < 10; i++) {
while (condition2) {
if (condition3) {
DoSomething();
} else {
DoSomethingElse();
}
}
}
} else {
AnotherMethod();
}
}
That is unreadable, no matter what indentation style you use 😄
Is a poll required?
It's complex and not readable by baseline, but using Allman is very clearly a better choice for something like that.
No, and I'm not claiming either is more readable. That is your claim. I am saying it's your preference, and generally you shouldnt enforce code style here. Conventions differ, as long as it is consistent for a project that is good.
C# and Unity's official documentation prefer a certain style. The style wasn't chosen by dice roll.
why not push all of the braces to the right side of your screen so you can pretend you're writing Python
public void OhNo() {
if (true) {
Debug.Log("Wow!");
Debug.Log("This is great!"); }}
Yeah guys, it's just preference
I use jumpPhase as jumpCount exclusively because that’s what the person who gave me the example used lol. Definitely a bit confusing though.
Yeah Python played smart and eliminated the possible arguments like this
Python introduced whitespace-dependent code which is terse but introduces its own issues.
and, in its place, it introduced about a trillion arguments about what is "pythonic"

Python introduced? It's been around for more than 40 years in a few languages you have never heard of