#archived-code-general
1 messages ยท Page 416 of 1
always afraid of string names
especially if you include a little validation code
making sure that nothing shares a name, for example
Hense the named enum approach. It will throw a compile error if I have collisions
for a game I worked on we have lots of configuration for items with addresses and we validate them all at bake time
One thing I don't like about using an enum is that changing the content in your game requires a code change
I like string names if I'd some additional layer of identity instead of just assuming there's not another similar string in the whole project
But it does provide some useful properties (like preventing repeated names)
yeah, what you're trying to do would be trivial in some languages but isn't really supported in C# without some effort on your part, but there are a variety of ways you could solve this
what are you thinking of here?
a type that only accepts a fixed set of strings?
e.g. in php you can have enums where the backing value is a string you define
Why not just plan out your enums upfront. so you give more range in integers to add or remove more and dont just increment by 1
I think you'd have to see how I'm using the enums to define the level data.
or yeah, in typescript you could use a union string type
from what you've shared so far, I think you should have an SO that represents each level, has a string ID that you define, and includes the level data defintions that we haven't seen
It's for a mini mobile game that I wrote back in college (Unity 2019). I'm currently working on porting it into Unity 6
That's what I do!
The asset is where the "soul" of the level lives
I can change the name, description, scene, etc.
but I never throw out the asset
I still think for this scenario they'd probably be better off with some ID generation if they are trying to reconstruct this level
are we still on the enum discussion? ๐
I think so?
And you want a better solution for the TileType enum?
void OnAwake maybe?
No the enum is fine, I just wanted the serializer to serialize it into a string matching the name of the enum value rather than using the ordinal
just use the current unix time ms as a unique id! /s
Isn't that also risky, in case you want to rename the values?
So TileType.Brush would become "Brush"
ah okay, then just do the suggestion with jsonattributes and newtonsoft
can u expose a nested array in the editor??
Yes, but it's also human readable, so I'd be able to fairly easily fix/remap it with a script. Since I can read what the previous value was.
Though odds are, I won't be renaming the values.
You mean if it's nested inside of a class? Use [Serializable]
but arrays serializable by default inside of a mono if allowed public access, or by using [SerializeField]
if that's truly your only desire, add your own step before/after you run the unity serializer where you can apply your own transformations, and preprocess the values into what you want unity to write. You'll probably want a layer like that eventually anyway
newtonsoft allows you to hook in easily and do that at serialization time, but there's no reason you can't roll your own
Or, just plan out the project before hand so you don't need to change enums at all because you shouldnt
As already mentioned, there is no good reason to use the builtin one and try to bend it to do what you want, unless you do realtime serialisation all the time or what not.
the best solution to everything is 'make no mistakes'
not to joy ๐
private void Start()
{
_sceneChangingHandler.SceneChanging += OnSceneChanging;
}
private void OnSceneChanging(SceneManager _, string oldSceneName, string sceneName)
{
_tools[Current].Exit();
RaiseExitedEvent(Current);
}
protected virtual void DoUpdate()
{
}
private void Update()
{
_tools[Current].Update();
DoUpdate();
}
private void OnDestroy()
{
if (_sceneChangingHandler != null)
{
_sceneChangingHandler.SceneChanging -= OnSceneChanging;
}
var tools = _tools.Values;
foreach (var tool in tools)
{
tool.Dispose();
}
}
In my ToolController, it works perfectly
I don't need to implement Dispose for my tools but I call it anyway, maybe some tools want to do something in this phase
thanks
Let future devs handle the problems ;p
For now it is, I'm still in the stage of porting over the game from Unity 2019 to Unity 6. Once I'm done with that, I'm gonna start implementing new features, where I may need to use Scriptable objects in some capacity
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
Anyone know of a way to draw debug rays in screen space coordinates?
As in I'm debugging Screen Space - Overlay canvas, so I don't have a camera, but I want to draw debug rays in screen space essentially
the scene view does have a camera you can access so maybe world to screen screen to world on that will do it
One way about is using graphic raycasters and covering the screenspace with a Image UI component
Okay thanks, I'll try these
not too sure why Unity UI doesn't just have a overlay collider component
I mean, you can also just get mouse position as that is effectively screen space coordinates so I'm not really following with what you're asking
sorry what are you reffering to?
I need to convert screen space coordinates to a UI Toolkit panel coordinates that is rendering as a render texture of a raw image. The image does not take up the whole screen so I need to convert the coordinates for the event mouse positions to register correctly. Struggling a bit with the conversion, but I think I'll get there
So you have some kind of monitor in your scene you wanna control, do I get that right?
No I'm essentially trying to "host" a UI Toolkit control inside a UGUI raw image via render texture.
or kind of picture in picture as a remote screen
Got it. Sounds like a good math task ๐ But essentially you are just remapping your screen size - the position and size of the box to a new "normalized" position.
Yeah, the Y downwards vs Y upwards is throwing me through a loop right now, that's why I'm trying to draw debug lines
how about a simple debug rect?
How?
oh wait, you are using UI Toolkit, not the good ol canvas UI,right
Like in the log? yeah I could, but visually is a little easier to understand. I'm technically using both.
Or you mean create a dummmy rect transform?
exactly, just a placeholder showing you the position of your mouse or maybe the calculated screenremap you are getting
Does that mean, toolkit and ugui are different in that case?
Not a bad idea
What do you mean by different?
about the y up and downwards giving you headaches. was just curious whats giving you headaches there
Screen space is y up, but I think UGUI and UI Toolkit both use y down
you mean, where the 0,0 origin is?
Yeah screen is bottom left, UI stuff is top left
UI is also bottom left
ugui is the same, if overlay then world pos is screen pos
well doesn't ugui depend on the anchors?
It does in case of position. but Y increase is always up
anchored position is different yes, but .position is not this
so rectTransform.position = camera.WorldToScreenPoint() or something is valid
Well I guess you have to work with bottom and left then to get the correct position from UGUI anchored position to UI toolkit visualelement style position using position: absolute
I mean I don't think I need to care about anchors, I think I just need to remap screen position values relative to the panel coordinates.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RectTransformUtility.html
Helpful amount of utility methods here too for rect transforms
I'm having a problem with the Unity Physics package in Unity 6. When I install it I start getting the following error and I'm not sure how to resolve it.
1>Microsoft.Common.CurrentVersion.targets(2413,5): Warning MSB3277 : Found conflicts between different versions of "System.Numerics.Vectors" that could not be resolved.
There was a conflict between "System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
"System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not.
References which depend on "System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\System.Numerics.Vectors.dll].
C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\System.Numerics.Vectors.dll
Project file item includes which caused reference "C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\System.Numerics.Vectors.dll".
System.Numerics.Vectors
References which depend on or have been unified to "System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\PublicAssemblies\System.Numerics.Vectors.dll].
C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Facades\netstandard.dll
Project file item includes which caused reference "C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Facades\netstandard.dll".
netstandard
F:\Unity\TruckKun\Temp\Bin\Debug\Assembly-CSharp\Assembly-CSharp.dll
I got it working, I essentially needed to flip the y by subtracting from the screen height and then use this method to convert the coordinates to panel space, the targetRect is the rect in screen space (y flipped) of the raw image (render texture)
public static Vector2 ConvertPositionToTargetRect(Vector2 sourcePosition, Rect targetRect)
{
return sourcePosition - targetRect.position;
}
It doesn't work properly if the Canvas scalar resolution doesn't match the display resolution, so that's the next problem to solve
Do you have a copy of the System.Numerics.Vectors dll in your project? Either by manually copying it in or by dependency via NugetForUnity, or custom unity package?
Essentially search both in packages and assets folder for that dll
It only shows up after I install the Unity Physics package
Is this a blank project? Try in a blank project to see if you have the same problem
Hi,
Why this sin slows down as the times 2 doesn't exist when Stamina reaches 0?
Stamina ranges from 0 to 1
float breathSoundFunction = Mathf.Sin(Time.realtimeSinceStartup * (2f + (2f * (1f - Stamina))));
Is this something to do with floating point wizardry?
Not really sure what you are asking, but when stamina is 0, it evaluates to (2 + (2 * 1))
So Time.realtimeSinceStartup should be multiplied by 4
game runs fine in preview play mode, build/run is just crashing within a couple seconds of starting and there appears to be no logs
What are you trying to do?
but it doesn't
I doubt there is no logs, what platform is your build on
right, it's multiplied by 4 instead.
what effect are you trying to achieve? faster breathing as stamina decreases?
windows. all i found was player.log and theres nothing in there
Yes.
oh wait that isnt even for this project
there should be crash logs, check here %TMP%\CompanyName\ProductName\Crashes
so what should the parameters be?
what's the max & min frequency, and how are they interpolated (linearly? or something else?)
linearly
Are you building as development or release?
@dense pasture don't think this is the right channel, try #๐ปโunity-talk
development build is unchecked
try development build, also yeah probably not right channel
Doesn't matter what the exact frequency should be to be honest
Build completed with a result of failed again
It usually tells you why it fails
Not happening in a blank project but I don't really have anything installed
doesn't have to be an exact frequency, just a min/max for scaling would give the same kind of answer
Try closing unity deleting temp and obj folders and reopening the project. Something in that project is causing it forsure though
minimum should be Time.realtimeSinceStartup * 2, max Time.realtimeSinceStartup * 4
as the code says
so what's the issue?
When stamina reaches 0 (code by logic evauluates to 2*2) Time.realtimeSinceStartup gets multiplied by 2
That doesn't seem to want to fix it ๐ฆ
yeah this is definitely a code thing but whats weird is i get no compile errors in visual studio
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(9,3): error CS0246: The type or namespace name 'CustomPropertyDrawerAttribute' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(9,3): error CS0246: The type or namespace name 'CustomPropertyDrawer' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(12,45): error CS0246: The type or namespace name 'SerializedProperty' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(23,43): error CS0246: The type or namespace name 'SerializedProperty' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(38,59): error CS0246: The type or namespace name 'SerializedProperty' could not be found (are you missing a using directive or an assembly reference?)
[ScriptCompilation] Requested script compilation because: Recompiling scripts for editor because player build failed.
how are you verifying that that's the case?
i'm not getting any errors building that code
by doing
float breathSoundFunction = Mathf.Sin(Time.realtimeSinceStartup * 2);
You have editor code that's not in an editor folder or wrapped in editor preprocessor directives
You have scripts using UnityEditor that are included in a build. Can't do that
aha
and...what, the result is the same?
have you tried actually checking the relevant values?
I told you how
think i got it nvm
Put it in a folder named Editor, or put it somewhere with an assembly definition that doesn't have any build targets but editor
or wrap in
#if UNITY_EDITOR
// editor code
#endif
yep thats the thread i found
@winged tiger have you tried Debug.Log($"{Time.realtimeSinceStartup}, {Time.realtimeSinceStartup * 2}, {<thing inside the Sin>}")
with the folder approach does it just have to be at the top level? or it skips any editor folders?
Any folder whose name is exactly Editor
Can anyone help me with this? I get this error when building for Android. I already have Android SDK and accepted all of the licenses. It's so specific to 30.0.3 which I also downloaded as well.
no clue what im looking at here
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.0/api/Unity.Cinemachine.CinemachineBrain.ActiveBlend.html
Does anyone know if this property is updated in the same frame for when you manage camera priority?
I'll probably be testing out in a bit but seeing if anyone has any experience grabbing the blend time quickly
Is there a recommended way to remember and auto-select previously seelcted buttons in gui when navigating menus wth a gamepad? For example from main menu click on settings, and then when closing settings to return to main menu, the settings button should be selected instead of it jumping back to default of play game.
It can start getting messy when you deal with multiple panels and popups.
My current method is to have a script for each panel that has the default selected as a priority stack (because sometimes the default for a panel can change like main menu default being "Continue Game" if you already have a save, but "New Game" if you haven't played before) and then also a list of which buttons it should "track", and then whenever the panel is disabled, it remembers which was the last selected, and then when the panel regains focus it selects the last selected if there is one, or looks at the default stack. Is this a common solution? Am I overthinking the problem or missing some built in Unity functionality that handles this situation?
Should just cache the values in some list of structs if the question here is you want to remember the history of all last Focus'd buttons
or for every multi-select panel make a script that incorporates a list of buttons and have a property "LastFocusButton"
results from the first code I posted
Multiplier is the result of 2f + (2f * (1f - Stamina))
it's clearly visible that the frequency plummets at 0 stamina, when it should be the highest
oh my, it looks like that, because the phase increases as the multiplier grows!
Hey gang! I'm running into an issue with the TextMeshPro Font Asset Creator where once I generate the font I get all the letters EXCEPT N and T despite the letters being in the generated atlas, any ideas?
The text that I'm typing out vs the atlas
found it out, it was an issue with bolding I guess ๐
I need help with a script, the script keeps falsely detecting exit collisions, script:https://paste.ofcode.org/p7FkB2t25WDbtbwszwySMr
This is definitely not the best way to handle a grounded state, we usually use rays for that because all it takes is your collider to slightly leave the other to trigger an exit. Use a raycast that goes a bit down from the feet so you won't get false flags
Pretty sure I already answered this. That's going to fire whenever you stop colliding with any object tagged "Floor".
Regardless of whether you are still touching a different object also tagged floor
Can i show vid
WORDS
Try logging other.name inside the exit function
see which object you're stopping colliding with
@leaden solstice yes there in same script but exist separately from the other classes so it should be fine no
Each of them should be in own file
Those green planes where tagged floor
Try logging other.name inside the exit function
see which object you're stopping colliding with
ok
it said
So, you are exiting a collision, with an object named Floor
So the code's doing exactly what you told it to
It's calling that function when you stop colliding with something named Floor
private async UniTaskVoid Start()
is this the right approach for replacing async void unity events when using UniTask ?
what are the benefits of state machines, especially for a platformer game with many monsters
Less comparisons for the most part, and helps prevent odd cases you could run into otherwise, ex. being able to crouch and swim
However, similar to abstracting logic with classes, you may find yourself rewriting similar code for different states because you've converged the states too much
I'm reading through the doc for the new input system but the first thing that was introduced was this
this looks similar to the old input manager of getkeydown, getkey etc
i'm guessing this isn't the right way to use the input system?
I'm still quite in a blur with the newer system, but I figured since I'm just prototyping, implementing the input system seems overkill for the time being
There are methods with the input system that allows you to just poll the input too if you prefer
Usually you have to poll the mouse movement too regardless... not sure about gamepads though
otherwise you can make any button into some callback/event
Oh I'm just trying to get the input from the keyboard in a 2d space & no mouse input is needed
what does polling input mean?
if(A key is pressed)
does it mean just accepting input without setting up action map?
ah
gotcha thanks man
I only have a superficial idea on how the input system works, but it's not my current focus now. I'll learn it later
I tend to ignore it for smaller projects and that I'm too used to just doing it the old fashion way
but if you wanted your code to look nice and organized you'd use it. Also helps to quickly swap out keybinds
I did hear a lot of benefits from talking to people here about the new input system, and it's a direct improvement from the old one
but yeah I think I'll just stick to the old method for smaller scale/prototypes for the time being
thanks again ๐
Are you reading an early documentation version on purpose? Note that you should always use the dropdown in the top left and make sure you're on the version you're using
oh huh I did not notice that, i just clicked the first result in google but that wasn't my intention
thanks for the heads up
Can you break a coroutine from another function?
Why not make a boolean that checks if the coroutine should break
In the coroutine check if its false
If it isnt then break the coroutine
you can call StopCoroutine from anywhere you like
Nvm im stupid
Thanks
Be mindful that StopCoroutine is not cooperative, so the coroutine being stopped might not have any chance of doing clean up if it needs to.
What @potent island described is how cooperative cancelling works, the only issue is that Unity's coroutines don't support them natively so you have to reinvent them yourself.
If you use UniTask, you would get to do cooperative cancellation like rest of the .NET world.
or Awaitable or a regular C# task, you don't need a library for that
I haven't looked into Awaitable but I heard the cancellation is a mess. You can use regular C# tasks, but you need to reinvent all the stuffs that coroutine has, which is part of what UniTask gives you.
Awaitable provides most of the same stuff as UniTask, and you can freely mix and match with regular tasks
you can use a regular cancellation token with Awaitables
nothing wrong with UniTask but it's not true to say that you need an extra library to get cancellable tasks when Unity does nearly all of that out of the box these days
Well that (you need a library to do cooperative cancellation) wasn't what I meant but sure.
The more important point to note is just the difference between cooperative cancellation and not
Which is especially problematic with coroutines due to their inability to return values, so a lot of coroutines are written with some state containers, and stopping the coroutine like that might cause the containers to be in an invalid state.
Hey there, does anybody know how to switch the Mask of a layer to another AvatarMask?
https://paste.ofcode.org/duRUuKjhLWWJEsHzuuCUZ8 in this code I want the player hp bar to update after the animations are played and also after shake animation is over if present for the move how to do it ?
Looks like you already have coroutines to wait for animations, dont you?
those are the coroutines for playing the animations they don't wait
So inside the coroutines, that frame adding is not the time your animation is playing?
no basically that script is just for defining the animations they are played in the other script and the hp is also updated there I have provided both the scripts in the link
This is waiting for the animation frames, right?
no that plays the animation
WaitForSeconds?
this deals with showing/updating healthbar
yeah because I have a time fixed animation the animation is done through dotween
See conversation above. Consider using a CancellationToken. These are general tokens that inform when something gets cancelled so you can pass that into a coroutine and occasionally check if it's cancelled. Stopping a coroutine with StopCoroutine isn't graceful and can lead to issues if data is being handled.
You don't need to use awaitables or whatever for this to work, CancellationTokens often go hand in hand with it but you can just use them completely separate
Note that Unity has its own share of tokens available, such as [this one](#archived-code-general message), which you can also use. Additionally, you can combine tokens in case you must listen from multiple sources.
Thats what I mean, you already got the time. So either wait for that time and in the end, update your healthbar or hook the health updat einto some event you are firing off at the end of an animation
I tried using WaitForSeconds but it doesn't work for all moves
I am understanding your code, that your frames get cycled through until the last frame, then coroutine continues, right? So you could just pass in an event to your coroutine that gets fired when reached the "bottom" of the coroutine code.
When last frame is reached the coroutine should stop as the move is not selected anymore
I think I should use an event at the last of the coroutine and then call it to update the hp
yeh, thats my suggestion, if you can rely on the coroutine being your leading method in that case and nothign else happens in parallel
Oh ok let me implement it thank you very much for helping
I have a problem with material transparency. Most of the game objects should be opaque all the time. But cursor, that player uses to place those objects into the scene needs to be transparent. And from what i found, you can't just turn surface from opaque to transparent at runtime. And if I understand it correctly, setting material surface to transparent for all materials to control transparency through alpha channel will cause performance issues. As Unity will have to perform transparency tests for everything in the scene, even if alpha always stays 1.0 for most of the objects.
Is there a better solution than making duplicate for every material with transparency enabled, to use those specifically for cursor ?
Hey guys, is anyone here familiar with how Lethal Company does their procedural generation?
Hey, in Unity I have a huge 2d array. I also have a scriptableobject TileSO for all different tile types. Each TileSO has a different int id
What would be faster, to just store TileSO[,] or have int[,] that would store the ids of these tiles and then have a dictionary of <int, TileSO> and find needed tile by its id?
The second one sounds like an unnecessary second step?
but that would reduce the allocated memory a lot
storing ints instead of whole objects
you'll still need to have the object somewhere, aka the dictionary
TileSO would be a class, a reference type, so it wouldn't be much bigger to store a reference than an int (2x for 32-bit architectures, equal for 64-bit architectures, most likely.)
make a public interface that is agnostic to how the data is stored, and implement that dictionary approach if it ever becomes justified
it does sound like an unnecessary overcomplication
also possibly a premature optimization
i feel like this might be based on a flawed understanding/assumption, btw. might want to check that?
yep, that was a stupid assumption. For some reason I thought that each SO would be a new object in that array
No, you're only storing references
hey, it wasn't stupid, it just lacked background knowledge.
but yeah, the array would just hold references to existing objects; each entry in the array is not necessarily a new object.
TileSO x = ...;
TileSO[] arr = { x, x, x, x };
```this would have the footprint of - a single `TileSO`, and a 4-member array of references
How can i get the position of a Plane struct
normal * distance
Hey guys so I'm trying to create a wave based spawn manager that spawns navmesh agents along a certain navmesh surface. But I'm always getting the following error:
Failed to create agent because it is not close enough to the NavMesh
UnityEngine.Object:Instantiate<UnityEngine.GameObject> (UnityEngine.GameObject,UnityEngine.Vector3,UnityEngine.Quaternion)
Anyone have any idea how to deal with this? I'm using a simple wave based spawn manager that uses a logic similar to the one given in the Junior Programmer pathways with some alterations made by me and i've used it previously in another small project I made. The main difference to that one is that I'm not just spawning random enemies that follow the player. I want the enemies to spawn in a certain area in front of the player and I want them to patrol that area so the player can shoot at them, when theyre all destroyed a new wave spawns. Thanks for any and all help in advance.
Sounds like you're not spawning it close enough to the navmesh or the navmesh is disabled or non-existent
The navmesh I'm sure is there because the enemies "spawn" but they don't move. What I do is that I generate a random spawn position and check to see if that position is valid and return that vec3 to another method that instantiate's the prefab. What I'm maybe thinking is causing the problem is the fact that i'm doing a random.range to get the x and z values because I want them to spawn in a certain area and then i'm hardcoding the y value as 0.5 bc currently i'm using primitive cubes for the enemies that's the height at where they're not clipping into the ground
How do you check if the position is valid?
Enemies spawning doesn't mean the navmesh is there...
And wdym primitive cubes I thought we were using navmesh agents
I have a vec3 list where I'm saving the valid positions then I go through that list with foreach and check a minimum distance from those saved positions to the new one. If it's smaller than that min distance I do a recursive call to the same generate spawn position method to get a new position else I save that position in the list and return the position to the actual spawning method
I meant to say that I'm pretty sure that the navmesh is there because I baked it into the scene and set it up properly according to what I've looked up. Or am I missing something else? I made prefabs of enemies with the script for their ai, which is very simple as of now, and they also have the navmesh agent component and I made them primitive cubes that I later will replace with models
But where are those valid positions coming from?
You could just use NavMesh.SamplePosition to snap the position onto the Navmesh.
You can also use NavMesh.CalculatePath to make sure that the position is reachable. Depending on your level geometry though, this part is not necessary
The positions are generated in a method i have that generates a value for x and z with random.range according to the bounds of the area I want the enemies to spawn in and then I create a vec3 with those values called spawnPos. that SamplePosition method sound useful by the description of it. I'm gonna the documentation on it. Thanks
This is a #โ๏ธโphysics question and you should show a video of what you currently got
alright
google results often take you to random versions, yeah
(and the documentation has changed a fair bit in recent versions)
ฤฐ am trying to make a runtime transform tool and doesnt work properly it moves when i first click it even if i dont move my mouse
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.
You're computing the offset based on the physics raycast, but then you add the offset to a point that's produced by the plane raycast
Those don't line up.
did somebody know haw to attach game object to object thats prefab and have script with : public GameObject Player? becouse idk haw to attach gameobject to this code
You can't reference scene objects from assets.
More accurately: things in an asset can only reference:
- its contents
- other assets
Scenes and prefabs are both assets!
So an object in a scene can have a reference to other things in the scene, as well as to prefabs. But it can't reference things inside other scenes or things inside prefabs.
chat gpt tells me that i can use "FindObjectOfType<T>()" is it true?
well, yes, it exists https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
btw sorry but this is for unity 6000, and i use unity 2022 is it exists in 2022 version
it has existed for ages, you can change the unity version for docs at the top left.
And dont worry im not from the US either ๐ฌ๐ง
thanks u so much
Ah, that is important -- you'll see a warning if you use it in new versions of Unity
it is intended to be replaced with https://docs.unity3d.com/ScriptReference/Object.FindFirstObjectByType.html
I'm having a mildly interesting problem with a [SerializeReference] field in the Recorder package
I have a script that reserializes all of the assets in my project. I figure I might as well just keep everything up-to-date, rather than having Unity update serialized data piecemeal over time
For some reason, though, my recorder settings asset keeps changing
The managed reference IDs keep going up!
I don't see this happening with anything else in my project
is it possible for a script to rename an object whilst the game is in the editor mode? I've got these prefabs which contain a scriptable object, and it would be helpful if these prefabs always have the name in the SO whilst im editing the scene
its quite tedious having to go and rename 20 or so different objects myself (especially if I ever change the names later)
You can make a script with a static function that has the attribute [MenuItem] to add it to a context menu.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MenuItem.html
You can make that function look through a bunch of objects in the hierarchy and change their .name. If you do it outside of playmode, those name changes will stick
that might be a bit too involved for what I need, I was hoping for something just like void Awake() { gameObject.name = SO.Name; } but in whatever method would allow the editor to call it
Yeah, you'd just do a rough editor script like I said so you can run it in edit mode without doing any custom inspectors, then you could just do a FindObjectsOfType and call a function on em
That's the least spooky way to do it
Yeah, this is the way to make it less involved
I might add to that, you probably need to SetDirty the child if you want the name changes to persist
[MenuItem("MyMenu/UpdateTechTreeNodeNames")]
static void UpdateNames()
{
int count = Selection.activeTransform.childCount;
for(int i = 0; i < count; i++)
{
Transform child = Selection.activeTransform.GetChild(i);
CanvasNode cn = child.GetComponent<CanvasNode>();
child.gameObject.name = cn.Node.Name;
}
}```This works
I added an event based functionality but now not only the hp bar the action selector also appears earlier https://paste.ofcode.org/Y7uNstubJaQBgqYpaYHuhA
Make sure to set them as dirty as well as record prefab modifications
Instead of calling a global event, you could also just pass in an event to the coroutine and call that
Anyone using vcontainer and know how to add a new LifetimeScope for a scene and register it as a child of my root scope that is in the DontDestroyOnLoad scene? I'm a bit confused by the vcontainer documentation
Huh. I spent a good while chasing this issue down today
Note: OnDestroy will only be called on game objects that have previously been active.
Never knew that.
This was causing me to miss unsubscribing something that could subscribe in Awake or in a public method
Oof, that's good to know
It was causing dangling event listeners when changing control schemes whilst a menu wasn't open
Definitely filing that into the ol' mental toolbox
(since that caused all of my individual action displays to be destroyed and recreated)
I've never stepped on that specific rake but it's definitely something I would eventually hit
I can't just subscribe in Awake, because I could miss a control scheme change that happens before the input action display appears
Ghetto fix: Instead of having the object start disabled, have it start enabled and disable itself in start. That way it receives OnDestroy callbacks
It's spawning in parented to a deactivated object
This is wild
I tend to subscribe to events in OnEnable and unsubscribe in OnDisable, but for slightly different reason. OnDestroy doesn't get called immediately when calling Destroy. It gets called at the end of the frame.
When you call Destroy it disables the object immediately though
Destroying the attached Behaviour will result in the game or Scene receiving OnDestroy.
????
very weird line
I guess I'll subscribe and unsubscribe in OnEnable and OnDisable, and also manually update in OnEnable
There's no point in updating the inactive action displays anyway
Yeah in my opinion event subscriptions in Awake and OnDestroy can be unreliable and can cause weird bugs.
Almost everywhere else does OnEnable and OnDisable, yeah
ah yes
this script has another alarming piece of code
[NonSerialized] private InputAction inputAction;
It bricks if you remove the [NonSerialized] attribute
because Unity still serializes private fields (for the sake of hot-reloading, I'm pretty sure)
Like if I'm subscribed to an event and unsubscription in OnDestroy this can happen:
Destroy(myObject);
meEvent.Invoke();
myObject will still receive the event
It's strange so I avoid it completely
this wound up causing it to insert a bogus object
I'm pretty sure destruction can happen instantly, but only in certain situations, which makes it even weirder
notably, while the game is shutting down..?
maybe it's just anytime you destroy something at the end of the frame
Yeah usually only in editor code
Is that just in playmode?
There is DestroyImmediate(), it's really only reccomended for the editor though
I have no idea!
I don't think this is the case, it should only serialize if [SerializeField] is added to a private field
: )
: )
try switching the inspector to Debug mode
you'll see private fields pop up
I believe it was also interacting badly with having Domain Reload disabled
Are you using a hot reload package?
Yeah but I thought that's for serialized fields marked as [HideInInspector] as well
Debug inspector will obviously show those even if marked as hidden
We aren't just talking about it showing in the inspector, but the value being saved
And persisted
It's very sneaky
I never use play mode hot reloading, I have my settings set to stop playing and recompile
ive never had it work it just breaks everything. only sbox does it well imo
hello im trying to figure something out from the reusable stat machine video(from i heart gamedev) and that is how to make it so that child game objects are able to change the state of the parent game object for example lets say you have 2 trigger box as children. one is for taking damage and the other for a melee hit ( i know the one receiving the melee hit should call trigger but lets say the one doing the hit call it). if either of trigger box activate i want the player to go to idle state for example how would i go about doing that?
What is sbox?
And yeah exactly, everything usually blows up. In my opinion, most of the time it's just not worth the extra code complexity to make it work properly.
https://sbox.game/about
They use the modern .net clr and have amazing hot reload while playing
In OnTriggerEnter set a parameter on the animator that causes it to transition to the idle state
im not sure what mean can you clarify
Do you have a character animator setup already?
i dont use animator graph since my game is 2D i use play/crossfade function
The Animator isn't a 3D specific thing
Whatever transitions your character into the idle state, you need to call it from a script attached to your trigger collider inside OnTriggerEnter
can anyone tell me whats wrong with my script after i click left shift i dont sprint..
I see a graph not a script 
cant even tell if that float is supposed to be setting some type of variable you haven't specified
yea it doesnt do anything from what i can tell
how do you make it so when using SendMessage() with PlayerInput (new input system), that the method gets called both onpress and onrelease?
right now, it only gets called when i first press the button, and never when i release the button
what mode is the action set as? you probably need as Value
i'd bet that the input action is set to pass through
sorry, moving there
Why does this not work?:
yAngle = Vector2.Angle(mousePosition1, mousePosition2);
where mouse positions are converted to world space
What doesn't work about it
this doesn't convert positions to world space?
just gets an angle
yeah I know, mouse positions are converted before that
I assume they meant the variables are holding the already converted values
those are converted variables
do dest - source, normalise and use mathf atan2
they still havent said whats wrong
you're asking people to make a whole bunch of assumptions about what you think is wrong
I don't quite understand what that does. So why does Vector2.Angle not return that?
it may presume both are normalised directions
What are you expecting it to do? You have two world-space positions
Maybe I need to specify angle on z axis? What's wrong is I Will place mouse position 1, then click mouse position two parallel to it in x space. I would expect to get an angle of near 0
It'll be the angle they make with the world origin
but I get a ''random looking'' number
vector2 is already omitting the z position as 0
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector2.Angle.html
the description says this...
I am confused by 2d tbh...what I want is I place position 1. I place position 2.
if:
- position 2 is directly to the right of position 1, I'd expect an angle of 0
- position 2 is directly above position 1, I'd expect an angle of 90
- position 2 is diagonally above and to the right, I'd expect 45
Your expectations are wrong.
I don't care about 180 vs 360 or negative numbers, it will work out the same
ah yes, Vector2.right, that makes sense now
2d confuses me
that image helped me too i miss understood it too ๐
I usually use atan2 myself to achieve the result or dot product
it works better than what I had but it still sometimes doesn't work...hmmm
I do:
Vector2 dir = (b - a).normalised;
float angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
i think this is correct?
What did you change it to and in what way is it not working?
Doesn't always give the correct result but seems to in most cases
I did what the person above suggested
I will check this
Okay, so just adding ''SignedAngle'' instead of ''Angle'' solved it
Say, when I open up a prefab in edit mode, what's the exact OnValidate behaviour? Is it called on ALL scripts on ALL childobjects of the prefab? Only the active ones? Only the ones I click on? Only the ones which have their values changed?
I'm looking for a way to have a callback on every script in a prefab whenever said prefab gets opened. That callback could potentially include a Resources.Load thingie inside, so I'd rather not have it run too often
edit mode only stuff? you can then use [ExecuteAlways] and OnEnable()
ooooh that's a good one, yeah! I'll keep it in mind!
I do wonder out of curiosity, how that onvalidate works exactly tho
i think i had this same desire once and i forget how it works...
i know at least on any var change in inspector its called
I know that part, and I also know that it can be plenty
I once did a buunch of instantiate and destroy inside onvalidate and when sliding a variable it completely KILLED my poor cpu
on validate may be called if you added a new prefab instance but i dont think it is just by opening it in a prefab stage
perhaps I'll have to combine OnValidate and [ExecuteAlways] with OnEnable (thanks again!) and it should work for me
Im trying out state machines, and I have a problem where every time my character goes from the airborne state to the grounded state (where WASD force is applied), it's velocity is always set to zero, instead of maintaining it. What could this be?
I know it is nothing to do with deltaTime, but dont know how else to debug it
the values probably no persisting through states
The only thing affecting velocity in the movement state is rb.addforce. Could that be it? If I put that in the master script, that would defeat the whole purpose of the grounded state
so where exactly are you expecting the value to be maintained ?
you have to explain the problem a little more
I figured it would be maintained in the rigidbody
I have tried saving the velocity right before leaving the airborne state and setting it upon the grounded state being active, but have had no luck
it could if you dont have another state setting it to 0 / something else
I have narrowed it down to this line of code inside of the grounded script```mm.rb.AddForce(mm.MoveDir.normalized * Time.deltaTime * mm.speed * 60f, ForceMode.Force);
yeah if any of those value is 0 then everything is else is 0
aslo you should not be adding time.deltaTime inside AddForce
rigidbodies already move on a specific tickrate
yes but the whole point of Time.deltaTime is to achieve a similar consistency
so your values change at the same rate no matter fps
The problem is persisting, even after removing time.deltaTime. Every other value is not zero when the script is activated
that had nothing to do with fixing the probem, its just smething you should be doing from now on
if its not mentinaing velocity its either colliding or you have somewhere where rb.velocity = vector3.zero ๐คทโโ๏ธ
Had a hunch and found out that the values for WASD are set to zero when the script is activated. Have no clue how but I think I found the culprit.
hey guys, weirdly couldn't find much on the internet but do you know how to stop the OS toolbar from "freezing" your game's state?
of course in this test case, im impatient as fuck so i didn't wanna let it ride for the entire map, hence i failed the map, but it could. and a player has before; so it proves to be a little problem.
focus checks and making it run in the background doesn't seem to help nor prevent things. i attatched an example to show what's up (if im using the wrong terminology here, lmao)
Hello! Sorry if this is the wrong channel. Im struggling a bit with organizing my scripts on my gameobject. Its not really a problem that there are so many, but im starting to lose the overview a bit.
Most of these are individual moves for my character. Any way to organize this better?
I think you're definitely overusing components here
why does every move need to be a component?
What does the code on these actually look like
Every move inherit from a base class that handles all the functionality of moves (Making hitboxes etc), and the actual move components just say "Create a hitbox on this frame, play this sound effect" etc.
I can share a code snippet if that elaborates more
SOunds like you could just have that base component and then a list of some POCOs or whatever for the actual move data
or even ScriptableObjects for the moves
with a list of instructions
Sorry can you elaborate on what a POCO is? Also for clarity, the base component is not actually attached to my game object, since the components all inherit from it anyways
Also, hypothetically, lets say i 2x or even 3x my amount of components on my object. Would this cause any issues? Or will it just be a bit messy
Poco = Plain class / struct
(plain old clr/c# object)
Ah ty
Would the only benefit to switching to scriptableobject be that i have less components? If it doesnt cause major issues, i dont feel like reworking a lot of code for this ๐
if its just container of data/run specfic functions with data then yes SOs are far superior than making everything a component
if data is meant to be mutable copy it from SO to POCO
Sorry im very unexperienced when it comes to SO's. I will share a code snippet, maybe that can clarify what the best cause of action is for me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicAttack1 : AttackBase
{
// Start is called before the first frame update
void Awake()
{
attackanimation = "BasicAttack1";
attackKeyCode = KeyCode.Mouse0;
SeriesLink = 0;
soundeffect.Add(Resources.Load<AudioClip>("Audio/Sound Effects/attacksound"));
stateRequirement.Add(pawnstate.Grounded);
}
public override IEnumerator ActivateHitboxes()
{
PlayAttackSound();
overrideStartAttack = true;
MoveCamera(new Vector3(-1, 10, -1), 0.1f);
//CanBeCancelledWithAttack(true);
yield return new WaitForSeconds(0.1f);
AddHitBox(id:0,radius:0.4f, position:Vector3.forward, damage:15,KnockbackDirection:Vector3.zero);
AddHitBox(id:1,radius:0.7f, position:new Vector3(0,0,2), damage: 15);
AddHitBox(id:2, radius: 0.4f, position: new Vector3(0, 0, 2.7f), damage: 15);
yield return new WaitForSeconds(0.03f);
DeleteAllHitboxes();
yield return new WaitForSeconds(0.05f);
CancelAttack();
}
}
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I mean I don't hate this
especially since they're coroutines
Maybe to organize them better you could put them on a child GameObject or something
shouldn't those be in an array though why are they all plopped on the gameobject
Yeah theyre all like this
Thats why im here x)
these can be easily done as SOs unless you need specific MB functions
MB functions?
Ah, i really dont know if theres anything specific in Monobehaviour required
unless you need those methods, probably no reason to have them be MBs
SOs weren't always a thing and I'm pretty sure a lot of this was pretty standard before
just that nowadays SOs can make the inspector easier to navigate cause it does get pretty crowded very quickly
seems simply enough for a POCO before SO tbh
SOs basically just make POCOs into tangible assets on disk
true, pocos must always be instantiated though for some reason
Ok! Thanks all. Ill look into turning them into SOs or POCOs tommorow. If i feel like i end up in rewrite hell, i will probably attach them all to a new script that has an array container for them instead :)
I think when you do Create asset is the same as creating the instance
but yeah SOs are mix of like static pocos and unity objs its weird
SOs will allow you to say make an empty list of abilities on a component, and it can contain multiples or none SOs
Like a list of scripts?
list of instances
Is this not possible with monobehaviour?
you can but you need MB to be on a gameobject
SOs live on Disk
therefore can be placed onto any MB that have the field for it
indeed nvm
Can they? I think you need to run them on a mono
Ah thats annoying, i use coroutines for basically everything atm
I mean there is always Awaitable and async
You can stick monos on anything. It doesnt need to be the exact instance
er coroutines*
Like you can even make a singleton that you just run coroutines from other sources on
tru
Ah ok!
coroutine can be modular you can pass all sorts of stuff like Func and all that maybe adapt it to whatever
or again use true async
You may be able to define the enumerator on the SO, but start the coroutine on the mono caller
yeah cause StartCoroutine needs MB to start it on
Ah makes sense. Anyways, ill look into it tommorrow, i have ideas of where to look now. Cheers! :)
ye, but if you aren't having problems with your setup just keep going
I got a dumb quick question, I need to check if the player is strafing so I wanna check the X of the input vector but is there a way to make sure that value is always positive, even when the player is holding down A/the joystick to the left? I remember having that figured out on a previous project but I'm completely blanking on it now lol.
you want the Absolute value
Mathf.Abs
mine has to do it a thousand times and only remember it for a month or so 
thank you very much it worked
@rigid island hi are you quite good with coding
does anyone know how to use json in unity
what do you want to use from it?
like i wanna make a storygame but idk how to make a json file in unity
cause the dialogue web is gonna be massive so a json file would be the best for it
but how would making it in unity solve anything
wym
doesn't sound like you're sure how you want to use json
well idk how to like
make the json file
and then import it into unity
yes json is just a text formatted special way
You can create json in Unity too through code too
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/JsonUtility.ToJson.html
and to deserialize you use FromJson
o damn what
I need help making a scrip
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
@somber nacelle I need to create a money script so player van buy weapon off wall
What have you tried so far, and which part are you specifically struggling with? Also how is your money script intended to work?
Hello. I have a scriptable object that works well, but I want to add a regular class to the same script to store information at runtime. Does anyone have any examples of how to do this? Should I be using a second script to store the class info instead?
in my experience, keeping scriptable objects immutable and making any runtime state a separate class ends up being a lot easier to work with
my textures in unity is ~80x larger compared to the file size in disk. the image dimension is only 458x356 px . how comes it 600kb in unity? Based on the inspector, it shows Compression as "Normal Quality". and max size is 512. Do i really have to lower the max size to 64 to get decent build size of texture?
the import max size doesnt affect the real file in the project but it will be better in builds (the inspector is showing the size of the texture in gpu memory)
btw you can only "down size" with sprites but textures you can have unity resize up/down to the nearest POW2
so fix your sprite to be pow 2 externally @mossy glacier
When i fix my sprite to be 512x512, the size is still very big, from 8kb in disk to 256kb in unity build
PNGs are heavily compressed
graphics cards can't render PNGs though haha, you can set it to a compressed format but you shouldn't expect it to be as small as PNG
As I said, that's the size in gpu memory which never matches the source file.
DXT is compressed however and results in much better sizes than non pow2 textures. Thats why it went from 600kb to 256kb.
This is also why it wise to use spritesheets for stuff like this as the sheet can be pow2 and you can have many sprites in it at varying size!
hmm i see. i dont know how to use spritesheets in unity yet. i'll look it up
Hello! Suddenly ran into a very strange problem. My sound effects are no longer playing, but i havent touched anything except restarting unity ๐ . Heres the code that run the sound effects
void Awake()
{
soundeffect.Add(Resources.Load<AudioClip>("Audio/Sound Effects/Paste25"));
}
public override IEnumerator ActivateHitboxes()
{
PlayAttackSound();
yield return null
}
public void PlayAttackSound(int soundeffectnumber = 0)
{
GetComponent<AudioSource>().PlayOneShot(soundeffect[soundeffectnumber]);
}
I have a debug sound that plays correctly in case no sound effect is present
But i dont understand why every other sound effect broke
When I use ScriptableObjects, I usually have a setup like this:
[CreateAssetMenu()]
public class SomeDataSO : ScriptableObject
{
public SomeData data;
}
[System.Serializable]
public class SomeData { ... }
That way the data can be set in a scriptable object, assigned to a object reference through the inspector, and then something using it at runtime can use serialization like JSON or copy each field into a new object to make a copy of the data without affecting the scriptable object, if it needs to be saved at runtime, it can be saved to a file and reloaded later, for example:
public class SomeMono : MonoBehaviour
{
public SomeDataSO so;
SomeData clone;
void Start()
{
var json = Newtonsoft.JsonConvert.SerializeObject(so.data);
clone = Newtonsoft.JsonConvert.DeserializeObject<SomeData>(json)
}
}
If you are certain your code is executing correctly, double check that you might not have muted the Game window, and that there is a AudioListener in your scene (usually on the "Main Camera"), and that the AudioSource is enabled (and its gameObject is active), and if your code modifies it, also make sure the AudioListener.volume is not 0 or using any strange settings on mixers
There is definitely sounds playing, i have an error sound playing correctly that comes from the same folder
Nvm i found the issue, it was really stupid sorry :P
Glad to hear you figured it out
Thank you for the example!
Yes turns out, List.add() adds object to the 1 index, not the 0 index ๐
And i havent saved since i transferred stuff to a list
That seems a bit odd to me, Lists always start at index 0 but adding one to a empty list will make the .Count a value of 1
I spend like 30min finding the cause for this. In the unity inspector, they initialize all lists to a length of 1 for some reason ๐
you must have put a value in there already, even if its "none" its going to be in the list as null. Remove it or stop making it serlialized to solve.
Hmm ive really searched everywhere if i added a value somehow.
In the editor it shows up like this (I havent added anything to it yet).
Then in my code, i add sound effects like this
soundeffect.Add(Resources.Load<AudioClip>("Audio/Sound Effects/Paste25"));
soundeffect.Add(Resources.Load<AudioClip>("Audio/Sound Effects/Paste3"));
And in game it looks like this
That screenshot is showing what i explained, the "none (audio clip)" is element 0
remove it
yeah but unity added this by itself when i created the list object
It shouldn't, do you have a Reset() function or some editor code?
Nope, not as far as im aware
then click that element and remove it and you should be good
Ok thanks! Its a bit annoying since it added it to all my components that inherit from the base where i added the list ๐
did you perhaps define the list something like this?
public List<AudioClip> soundeffect = new(){null};
I think i defined it like this originally
public List<AudioClip> soundeffect = new List<AudioClip>();
Then changed it to this
public List<AudioClip> soundeffect = new();
Then tried to change it to this
public List<AudioClip> soundeffect = null;
Hmm it should have been empty then always. If you reset the component it will go back to defaults:
Ah thanks! Ive never used reset before, so that is very handy
Is there an easy way to reset several or globally all components?
Well you can select multiple and reset in bulk. (You can also define Reset() to run code on reset)
You can Ctrl + Click or Shift + Click if everything is next to eachother in a list, and if they have similar components editing the inspector will apply the same value to all selected - however some fields might have a dash, meaning the selection for that field have different values and changing it will change all of them
Ok! Thanks everyone! :)
the first 2 are the same; the last one is most likely not what you want
but since it's serialized, it'll get replaced with unity's value anyways, you just have to set a reasonable simple default
Hi, if I write one of usefull commands in any unity chat is it visible to everyone or just me?
it's visible to everyone; it's just a normal message
What's a Unity chat?
As in here?
Yes
This is discord, anything you post is visible to anyone with access to the channel.
Which, in this channel, is accessible to everyone who's joined this server.
The only messages that are not visible to everyone is the built-in slash commands if you start a message with /
What is the best practise to use those commands, I don't want to interrupt people by chating commands in some chats?
You can use private threads and DMs for private chatting
You can use private threads to test bot commands
I'm not familiar with private threads, how to create one?
not necessarily; the reply is visible by default, and it'll show who sent the command
it's only hidden if the bot chooses to set their response to ephemeral
Open a thread, make sure to tick the box saying it's invite only. Make sure to ping the bot.
Make a thread with the big button on top of the page
Thank you
or from the plus on the side of your chatbox
Oh thats a good point, I guess the initial command is invisible, but the result would not be, your right
No problemo, happy commando'ing
I guess we only annoy the moderators with these threads though
Sorry mods
(also slash commands are technically not messages, btw)
I haven't even known that we have slash comands, thanks again ๐
Discord has some interesting features and they often add new ones with updates, so always something new to to learn about lol
I have an array of Nodes with a worldPosition property.
How can I generate an array of worldPositions from the array of Nodes? I think I can use linq to do it really easily but I'm not familiar with it
yeah with linq you can do Select(node => node.worldPosition), for example
that uses a lambda, do you understand those?
ahhh I did the same thing but with Where for some reason whoops
yeah for the most part ๐ thanks
Hey friends, I think I did something wrong, something basic, but I can't tell what it is. As you can see here in the debugger it says I cannot reach this breakpoint. And following my order of operations, it does not seem like I had, but the data in m_curAnimate has mutated from its initial value of 'Idle 1' to 'Idle 2' without me setting it to change anywhere in my code.
private void DoAttack(Transform target)
{
var animator = m_context.m_mob.m_animator;
switch (m_curAnimate)
{
case m_idle01Name:
Debug.Log("Idle01");
if (Vector2.Distance(m_context.m_mob.transform.position, target.position) > ((CamoBoss)m_context.m_mob).m_dashThreshold)
{
m_curAnimate = m_dash01Name;
animator.SetBool("PrepareDash", true);
animator.SetBool("Attacking", true);
}
else
{
m_curAnimate = m_walk01Name;
animator.SetBool("Walking", true);
}
break;
case m_idle02Name:
Debug.Log("Idle02");
animator.SetBool("Walking", false);
break;
case m_dash01Name:
Debug.Log("Dash");
animator.SetBool("PrepareDash", false);
break;
case m_walk01Name:
Debug.Log("Walk");
break;
case m_attack01Name:
Debug.Log("Attack01");
break;
case m_attack02Name:
Debug.Log("Attack02");
break;
case m_attack03Name:
Debug.Log("Attack03");
break;
case m_attack04Name:
Debug.Log("Attack04");
break;
}
}
public override void HandleAttack(Transform trans)
{
// Lock movement during Awakening
if (m_context.m_mob.m_animator.GetCurrentAnimatorClipInfo(0)[0].clip.name == "P1 Slumber" ||
m_context.m_mob.m_animator.GetCurrentAnimatorClipInfo(0)[0].clip.name == "P1 Awakening")
{
m_context.m_mob.m_aiPath.canMove = false;
return;
}
// Lock Movement
if (m_context.m_mob.m_animator.GetBool("Attacking"))
{
m_context.m_mob.m_aiPath.canMove = false;
m_context.m_mob.GetRigidbody2D().linearVelocity = Vector2.zero;
return;
}
else
{
m_context.m_mob.m_aiPath.canMove = true;
}
AttackSettings(trans);
DoAttack(trans);
}
yeah Where would be for filtering; iirc linq is based on sql
that warning often just means you need to restart visual studio and/or unity (it thinks the source code and compile code differs)
@oblique basalt are you familiar with any other languages?
I'll try it out, thank you
er
Though the mutated data is still a mystery
lol
Are you sure you don't have a compile error?
im sure you know values dont change magically unless its serialized so have a look when debugging works.
No errors in the error list
The issue seems to persist after restarting both applications
In the console
Unity console
Not in the ide
Not there either
Take a screenshot of the whole console window
sometimes vs is just shit, you can try re generating the solution in unity preferences.
usually for me a restart of both us sufficient
Sometimes when you press play it decides the breakpoint will work ๐
Debugging mode is enabled right? @prime lintel
Yeah, so:
- Make sure the ide is configured correctly.
- Check the script file in the inspector and see if the code corresponds to what you see in the ide.
Hey, how can I run the game in two instances? I see all the youtube videos on multiplayer do it, i have no idea how as they don't explain it
yep
what if the code is truncated by the inspector for being too long
If it's a build, just run it twice. If it's editor, there's a plugin for that. "ParrelSync "
are you going for splitscreen or something? if it's really two instances, this isn't really a code question
Then there's not much you can do. Restart the editor/PC and hope that it works after that.
๐ญ alright then
parrelsync? using unity 6, unsure if it will work
Also, really make sure your !ide is configured correctly
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
btw any suggestions or guides on creating enemy AI in a 2d game?
Should work. Also it seems like unity provides a package that does something similar:
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/testing/testing_locally/
tsym
please don't crosspost
How can I find the screen space dimensions of a RectTransform no matter the scaling settings on the CanvasScaler?
If the RectTransform is being used in an overlay-mode canvas, world-space positions are equivalent to screen-space positions
heres an example for overlay canvas use
var localToWorldMatrix = levelArea.localToWorldMatrix;
Rect rect = levelArea.rect;
Vector2 min = rect.min;
rect.min = localToWorldMatrix.MultiplyPoint(min);
Vector2 max = rect.max;
rect.max = localToWorldMatrix.MultiplyPoint(max);
Hello! Ive been struggling with letting my program work when i build it, i just get an entirely Orange image when the program starts. I can hear the sound effects from my game, which indicates its working correctly, so i suspect its a camera issue.
Heres my build settings
And heres my camera settings
I tried searching for the issue online but no solutions :(. The game works perfectly fine in the editor
Heres what it looks like when the build finishes, and after the splash screen has popped up
this isnt really code related but have you checked the logs for the build? for dev builds it should appear as an option in the drop down in the console window. (is "Editor" by default)
Ah sorry, i couldnt find a proper channel to post this in. Ill check it out now! Thanks! :)
Found the issue, cheers! An overlay camera was causing the issue for some reason
yay
Hi I trying to make a procedural animation with a spider, but I'm confused about zigzag legs pattern, how can I make this in the code?
Very vague question, what part are you asking about?
Having the legs alternate?
Yes
It's easier to help if you show what you currently got
Including code and gameobject setup
Basically you can get every other leg by checking if its index is index % 2 == 0 or index % 2 == 1
so far I've only done the target script, is circles attached in body and the legs follow it when the distance is so big
I write the code in portuguese
Well, I don't know portuguese
I will try something, thx for your help
I will try this
is there any noticible difference between [SerializeField] private float and public float for game design?
i mean for global script variables
Serialized private fields can be set by the inspector.
Public fields can be set by anything.
i guess that was a pretty dumb question of me now that i think about it XD. Was not thinking in code when i asked
"global" is a bit of a weird term to use here, btw
that usually implies that it's something that everything in the game can see
(and access, directly, without any help)
i consider "global" to be variables that are declared outside of a method, "global" vs "local" variables in programming
but what would be a better term to define them so other people have a better understanding?
Those are fields
a kind of member
It is true that variables declared inside of a function are called local variables
when learning programming, i was taught any variables declared in a class but outside of a method were global variables, so those are callled "class fields"? or just fields
"global" tends to mean something that doesn't really have a specific owner. local variables are "owned" by the scope, fields are owned by classes, and since vars can't exist outside of types in c#, global vars don't really exist in c#.
ohhhh, ok ok thats explains things in a way i understand
public global int foo;
public class Whatever {
public int bar;
}
(there is no such keyword)
if it were say, python, you would have 3 levels, or in js, you would have 3-4 depending on the environment
# python
x = 0 # global var
class C:
y = 0 # class var
def m():
z = 0 # local var
def f():
z = 0 # local var
``````js
// javascript
globalThis.w = 0; // global var
let x = 0; // module var (or global, if modules are not used)
class C {
y = 0; // class var
m() {
z = 0; // local var
}
}
function f() {
z = 0; // local var
}
yeah, ive never dealth with declaring variables outside of a class (i was taught in java)
delt
yeah java doesn't really have globals either
public class Foo {
public int field;
public int Property => 123;
public int Method() { int localVariable = 100; return localVariable; }
}
yeah i understand the difference now, ive never seen global variables before, because i havent had a use for them yet. My thinking was always in java, even when using other languages,
thank you for the info
Most object oriented languages don't allow that at all so it makes sense you've never dealt with it
C and cpp allows declaring functions and vars outside a class/struct
most oop languages being c# and java
we all know c and cpp dont follow the rules
i mean, if c/cpp are oop, then so much else is that i feel it starts becoming meaningless, no?
c/cpp don't need objects if you don't want them
you can't do that in java or c#
C isnโt oopโฆ
That is the entire readon cpp exists
so is cpp oop
You can code in OOP in c though no ?
you can, but the language doesn't force you into oop
You can code OOP in any language that has the concept of a class at all
my thoughts being; if you use that as the metric, then so much becomes oop, what's the point of the distinction
oh no! ontology!
if eventToInvoke is null, what will happen here? My project has plenty of errors right now so I can't check for myself, but I'd like to know while still writing this class. For reference IProcedure : IEvent and they're both interfaces
null is not an IProcedure, so it will not go into the condition body
but you have to specify T, and T COULD be an IProcedure, so there should be enough information to go off of that, right?
can't do T is IProcedure sadly
No, it checks the actual contents of the variable there rather than the declaration, so null shouldn't pass that condition
is there a way to check if eventToInvoke is an IProcedure then, if it's null? nulls are perfectly acceptable in this function, as long as T is not IProcedure
If eventToInvoke is null, then it isn't an IProcedure
Yes, so it's an IEvent
No, T is an IEvent
IProcedure is also an IEvent
so you can pass an IProcedure to something that expects an IEvent
yeah I know, but I want this specific function to only allow IEvents that are not IProcedures, is there a way to limit that?
Don't pass an IProcedure to it
Or make a different interface implemented by everything that implements IEvent except IProcedure
I work in a team, and I can't guarantee that nobody will pass a IProcedure to it, I want to make it impossible or at least throw an error
kinda breaks "IProcedure is an IEvent"
I really need IProcedure to derive from IEvent everywhere other than this function
Then you'll need to pick a type that includes what you do want, but excludes the ones you don't
could make an IInvokable that extends IEvent and make other stuff except IProcedure extend that
Hm, that's a good idea
Always better to make invalid options impossible rather than checking if it's correct after you get it
I keep getting precision errors that result in a value not being calculated as zero
Which is why you shouldn't compare floats with ==. Use Mathf.Approximately instead
what if i need to check if a value is greater or less than 0?
Have been working with unity for a while and this thing has bothering me since beginning. is there a reason why GameObject has a getter to itself?
Because funky polymorphism reasons
there's also some precision error: i divide 0 with some float, but the result isnt zero
Which is why you shouldn't compare floats with ==. Use Mathf.Approximately instead
im not comparing, im dividing
Yeah, but when you go to use the result, you should be using approximately to check the value
lol wtff
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.
even approximately doesnt work
What does the full code look like, and what exactly is the problem?
{
if(hasJumped){
hasJumpedFromCeiling=colls.rotation==180;
hasJumpedFromwall=colls.rotation%180!=0;
}
colls.rotation = 0f;
rotationDirection = 1f;
Debug.Log(rb.linearVelocity);
velocity= rb.linearVelocity/ velocityMultiplier;
changeDominantRay = false;
}```
the problem occurs on velocity=rb.linearVelocity...
when colls.rotation is 180 and rb.linearVelocity.x is 0, velocity.x isn't zero
If you're trying to apply and un-apply a multiplier, you're going to need to store the before and after speeds as different variables. Multiplying it by velocityMultiplier then dividing it out later is going to eventually introduce larger and larger discrepencies until it no longer ends up being approximately correct
Is there a way I can have an Action<MyInterface> that implicitly accepts adding Actions that don't take any parameters? it'd make things much simpler for me
nevermind, got it working
is there really no way to mark a built-in unity class/struct as System.serializable?
it'd be massively convenient to be able to do so for Unity vector classes
Nope. I think the unity mathmatics structs are serializable however. (float3 can replace vector3)
alright, thanks
Pretty sure vectors are already serializeable
https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.float3.html this is but no idea if it will serialize well
it's different to Unity serializable
How can I generalize those 2 functions into one so that I don't have code duplication?
protected static bool ValidateListener(Action<IListenable> listener)
{
if (listener.Target == null)
{
return false;
}
if (listener.Target is Object o && !o)
{
return false;
}
return true;
}
protected static bool ValidateListener(Action listener)
{
if (listener.Target == null)
{
return false;
}
if (listener.Target is Object o && !o)
{
return false;
}
return true;
}
They're visible in the inspector, which would mean they're serialized to the meta assets
as I've, I mean System.serializable
it's a different type for turning C# classes/structs into JSON, XML or Binary
what are you using to serialize that doesn't support serializing a vector3
Vector3 should be serializable, I'm pretty sure
BinarySerializatoin, for saving things
saving files in a secure way
Yeah, and I've definitely managed to write out json, xml, and binary containing vectors
can some smart person help please
i mean what specifically, you can easily serialize Vector3 to binary, but what are you specifically using to try to do so
hmm? how did you do it?
use generics
how can a generic save me here? Maybe I'm too tired to code but I don't see it
I think you should be ablet to do ```cs
protected static bool ValidateListener<T>(Action<T> listener){
if (listener.Target == null){
return false;
}
if (listener.Target is Object o && !o){
return false;
}
return true;
}```
hmm? what should I use instead?
btw yes it is indeed
if only there were some sort of link that explained why it is insecure andsome alternatives to use
that works for everything except Action that doesn't have T, does it
also use Path class to create paths
but also if you want to serialize to binary, i personally recommend messagepack
yeah I did see it, I actually mean the question
xml, json, protobuf or bebop
what question? the one that is also answered by the thing that was linked?
it should. Try it
what to use instead
but thanks
you should learn to read before trying to use unity tbh
Maybe if there were some sort of list of alternatives that were preferred, perhaps on a webpage that was linked
I did think of using JSON as that's what I used in GM2, however I think I'd have to do cryptograph
ah, I see
if you want it to be efficient then json and xml are off the table
blah blah newtonsoft conversion issues blah blah
that's what I'm aiming for, I'll save huge amounts of data
I'll read further into it
nope, doesn't work
knew it wouldn't be this easy lmao
Try specifying the type arguments explicitly
I recommend protobuf but it requires defining all messages and generating code to use them
it wants me to put in T
and it has no T
Because the action has no T
that's the whole point
I'll also read into that
thanks
Oh sorry I thought you had two
unless you meant like this?
Action and Action<T> are not interchangeable
I even specified that one has no T ๐ญ that's the whole point
I thought you wanted an Action one and Action<T>
mb
assuming this is System.Action that is
does converting an action into an action T like this
(Action<T>)((_ => myPlainAction.Invoke) preserve the target for the purposes of checking if it isn't null?
it is
would Delegate work?
what is even the purpose of this?
to check if target of an action isn't null
I'm making an event system where I dont want to bother with deregistering listeners
and if I check the target and it still exists, it should be fine for my purposes
It's going to capture the myPlainAction variable
System.Action.Target is not the listener
it's the instance that a method is being called upon (if one exists)
what, what if I have code in brackets there instead? or a static function?
then there is no target
that's exactly what I want though
and if you subscribe a static method then the Target is null
which breaks your entire system
and if you add multiple listeners, it doesn't make sense at all
i'm not sure what happens there
It is true that it's the listener in a subset of all possible cases
fortunately I'm not gonna be doing that
If the delegate invokes one or more instance methods, this property returns the target of the last instance method in the invocation list.
ah, there's the definition
I have a list of actions with separate listeners so its ok
i was having a bit of trouble pulling that up
sooo, is there a way to generalize those 2 functions or no?
I guess I can just make a ValidateActionTarget function...
oh yea that does work, niceeee
otherwise you would need to have a separate implementation for every number of generic arguments
I've also thought about an event system that doesn't require explicit un-registration
public static bool Validate(this Delegate listener) :X
You could have a singleton that notes down every time an object says it's subscribing to something, and then unsubscribes everything when that object reports that it's being destroyed
basically, GC for your event listeners
yeah that would likely be better than this current implementation which will break if you decide you want static subscriptions or to subscribe multiple methods to a single delegate
You could also create a "conditional action" type
basically, an action, plus some information about when you can use that action
or you just wrap the listener in another delegate type
ooh, that could be a use for the add and remove accessors!
or a bastardized event bus that basically just takes an object (which you would pass this) and the desired Action and throws it into a list, then you could just null check the object passed
lists are scary because you could trigger a concurrent modification exception from literally anywhere
I remember seeing someone implement a modification-safe list that'd avoid that problem
ah yeah, probably wouldn't need a list just a dictionary<object, Action> and each time something is subscribed it gets thrown into the relevant Action.
of course none of this matters for anything that doesn't inherit from UnityEngine.Object considering other objects don't suddenly turn up null
why can I add a [CanBeNull] to a parameter function of type T, but I can't make its default value be null?
default as the default value doesn't work, because I can't check if eventToInvoke == default
or rather, my real question is, how can I make sure that this T IS nullable and I can check it for null?
I know I can just make a parameterless function but this frustrates me!
Never seen that one before.
just because T is constrainted to an interface doesn't mean that only reference types can be passed here
usually I'm being forced to use default or so VS tells me
wait that doesn't work EITHER??
I am explicitly using [CanBeNull] though
I think you can do Nullable<T>
what type is it supposed to be using there
that's just a compiler hint about nullable reference types and has nothing to do with the actual type being passed
anything that derives from IEvent
sure but what type is that null supposed to be
how can it know because you literally just passed null
Can you add like a class constraint to the interface to infer the nullability
only non-nullable value type can be used with Nullable
wtf
ooooooh yes sounds like something I want! How do I do that?
interface IEvent : class?
: object?
I'm just thinking out loud here
:(
It's supposed to be type T, which is being passed in
T is not a type, T is a type parameter. you didn't tell it what type you are passing
if you cast the null to IEvent it will work because it knows that you are passing a null IEvent object
but if you just pass null then it doesn't know wtf you want
I'm using reflection later to create an object of type T if eventToInvoke is null
this just sounds like a whole lot of bullshit just to avoid unsubscribing your events like a sane person
no, that's a separate thing
that's invoking the events
then you need to specify a concrete type when invoking the method otherwise you're gonna have a bad time
this is still a problem? just do your own event dispatcher
that's what I'm doiiiing right now
i know how to unsubscribe your events correctly: an on-destroyed event
now you just have to unsubscribe that one...
๐
actually, I do something like that in my code -- a "one shot" list of actions
I'm not even doing the unsubscribing part anymore tho
I solved that part
new problem:
inside the function
public static void AddListener<T>(Action<T> listener) where T : IListenable
I cannot do (Action<IListenable>) listener because it throws an error and rider suggests
listener as Action<IListenable> but that results in a null value
Like I'd assume that Action<T> where T : IListenable would be convertable to Action<IListenable> but clearly not...
You generally can't cast Foo<Child> to Foo<Parent>, no
This is where you bump into covariance and contravariance..
although isn't that just a way to allow for implicit conversion?
i've yet to actually find a situation where I need either https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/
pretty sure you would need Action<in T> for that rather than just Action<T> to support contravariance
why do you need to cast like that? are you trying to put the action into a list?
yup! that's exactly what I'm doing!
I tried Action<IListenable>)(Delegate)listener which makes no compiler errors but... well I'm glad it doesn't work
do you know how to help me achieve that?
Just throw out the generic type parameter entirely, actually
this is my dictionary:
protected static readonly Dictionary<Type, List<Action<IListenable>>> listeners = new();
and this is my function:
public static void AddListener<T>(Action<T> listener) where T : IListenable
{
if (!listeners.ContainsKey(typeof(T)))
{
listeners.Add(typeof(T), new List<Action<IListenable>>());
}
listeners[typeof(T)].Add(listener);
}
All you care about is having an IListenable
You'll lose the ability to compute typeof(T), but you can just figure that out via reflection
the reflection part is actually a framework I'm using, I'd rather not use reflection outside of it
and I really need the T because not all actions require T in the first place
some listeners ignore the T object entirely
can I change my Action<IListenable> in my array to Delegate?
would that work?
But you aren't using the generic type parameter at all here (other than to get a Type object)
Yea but I also have this:
public static void AddListener<T>(Action listener) where T : IListenable
{
if (!listeners.ContainsKey(typeof(T)))
{
listeners.Add(typeof(T), new List<Action<IListenable>>());
}
listeners[typeof(T)].Add((Action<IListenable>)((_) => InvokeIfValid(listener.Invoke)));
}
Does that even compile? You're storing the action in a List<Action<IListenable>>, but you're trying to put an Action<T> into it (where T derives from IListenable)
yyyyyyy yes I have Action<IListenable> in that cast I'm just experimenting with Delegate now so I had to recreate that code back to send it to you lmao
sorry
You can't really do this type-safely. Every kind of action demands something more specific than an IListenable
I have an idea, have the subscribers de sub and stop this madness ๐
okay, so now that this is edited -- you're once again only using T to compute typeof(T)
I'm saying for the fourth time this isn't even about that anymore!!
XD
you can throw that out entirely and retrieve a type from the action
Type type = action.Method.GetParameters()[0].ParameterType;
you missed the lack of T in that Action again
if I remove T I have no way to get the type I need
Yes you do. I just showed you how to get it.
void Test(System.Action<IConfigurable> action)
{
Type type = action.Method.GetParameters()[0].ParameterType;
}
see? you have <IConfigurable> here
and I have 2 functions
one is Action<T> and one is Action (without the T)
well, yes, you'll need separate code for a zero-argument function
so I can't use that approach in the latter case
those are fundamentally different from a one-argument function
that's why I want to pass in T, so that there is no problem
and both functions can work in the same way
and when I change my function to take Action<IListenable> then I can't pass in functions that need an argument that derives from the IListenable
or can I
okay, the above would work, if I just passed in the Action<IListenable> but I'd rather have it as it is at the bottom
is THAT at least doable?
that's an example usecase of my event bus
This is the fundamental issue. You can't pass an Action<Derived> object to something that expects Action<Parent>.
You can get a little further if you use a generic type parameter on your "add listener" method, but then you run into the exact same problem when you try to put into a list of Action<Parent>
The reverse is legal via contravariance
void Test(Action<SomeConfigurableThing> action)
{
}
void AddMe(IConfigurable arg)
{
}
void Test2()
{
Test(AddMe);
}