What Starcraft 2 AI does afaik is check whether or not it goes closer to the target or not over 1 second.
So if you grab a bunch of marines, and all double click them on the same spot they fight for that place like your skelly for 1 second, and then it force stops all of them. There is a GDC talk about Starcraft 2's pathfinding/navmesh, imho it has the best fast and responsive movement for strategy games currently, suggest you look at that talk.
#archived-code-general
1 messages · Page 22 of 1
Well another idea is to calculate formation possitions based off the player pos. We do this in one game but for enemies attacking the player
This is what I had in the beginning. The Formation would rotate and move whenever the player rotates and moves - that was incredibly annoying, so I added the margin, so Agents don't move, as long as the player is within a certain range of the formation, meaning, he can walk through the whole formation. Causing these problems.
I will have a look at their talk and maybe implement the solution as it seems to solve all problems.
But I won't fully stop them, as I also have destructible Buildings and enemies / allies could die, allowing other allies take their place, I will just slow them down a lot until they start getting closer to their target again and then reset their speed. Something like that maybe.
You would need to recalc the formation based on player pos, not just have a bunch of transforms parented to the player. If player moves check distance to each point, if its bellow min distance shift point away from player.
That's a solution I haven't thought about yet but actually possible. Hmmm, maybe I'll implement both to solve all cases.
Thanks @west lotus & @main shuttle, after being stuck on this problem, I finally have some solutions. 😄
Good luck
Btw are you making a Overlord ispired game? I loved those games.
Yes, working towards a playtest, hopefully somewhere at the end of this month - PM me if you want to test it. ^^
Im afraid I wont have time to playtest it, but I wish you all the best
Np ^^ And thanks 😄
Anyone know how to solve this problem?
This happened when I finished moving the unity editors folder from C drive to E drive
This is the first time I have a problem like this, and I don't know how to solve it, I'm a beginner 🙂
Whenever you move a project, be sure to remove library folder. Unity will rebuild everything for you, cause paths to temporary files are now messed up as you changed the path with moving the files
okay, I'll try to delete my library folder
if a gameobject is created from prefab, the component property value modified by [ContextMenu] , is not able to serialized !!!!!
What are you trying to do?
place a prefab to the scene, the prefab has a Mono script.
use [ContextMenu] to modify this component value.
but it's not saved, after switch scene
Saved to the prefab or the scenes instance of the prefab?
the instances
so you save the scene after editing values? What is your code actually?
!code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
[SerializeField]
private Vector4 value;
[ContextMenu("Build")]
change this value
what is "this value"?
(1,2, 3,4);;
When modifying assets from code you need to make sure to call either:
https://docs.unity3d.com/ScriptReference/Undo.RecordObject.html
or
https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html
otherwise Unity won't realize the object is changed and won't save the changes
so?
there are 2 scripts, one is to set the other's value
so?
^^
OK, it's working
what is the difference between EditorSceneManager.MarkSceneDirty and EditorUtility.SetDirty
read the docs
it explains
I’m making a flash baton. How do I give it a trigger kinda like a gun that the player presses and it causes damage
Okay so I learnt I can use the activate in event thing and that’s the trigger on the XR controller but in order to toggle that off I need code?
What now
I have a good idea of what I want to do, just missing a bit of knowledge on the coding side. Would appreciate if I could talk with a skilled coder. Looking at Scriptable Objects and EditorWindow.
That one doesn't exist, it's just something that vertx would want 😛
yeaaaaaaaaah
Just realised that
If you got a question about something you tried, feel free. But if you got no code, you at least should come up with a code structure or something, cause noones gonna conceptualise your idea here. especially not in general
the rules were posted just 3 messages above yours
Oh yeah that's quite funny actually
I have 500+ lines of code
Cool
TBH I'm a bit depressed and this project is helping me take my mind off things.
That's still not helpful
Post your code on a paste website, best part only the code part that is necessary for your issue, then people can look at it. You barely will find someone here making a free coding lesson 1:1
I mean it would help if he'd first actually describe his problem
But yes, having the relevant code will also help
Sanity Check:
I need a backend for my game to retrieve and store some data and do some matchmaking, but I do not need any live multiplayer functionality
Surely I can just do this with a plain ol rest api that I host on some azure server, right? Or do we do something completely different in Unity
Just started working on a card game with my brother who's new to Unity and doesn't have any coding experience.
Want to create a smooth workflow where he can create new cards, enemies etc. in the editor.
Currently effects are MonoBehaviors that you add to card prefabs. When a card is played all effects are executed. The most basic effect is a DealDamageEffect that has a "Value" field where you enter the amount.
I'd rather have them be ScriptableObject assets (this would for instance allow me to also have the cards themselves be scriptable objects instead of prefab variants) but this comes with the problem that I would have to create one asset for every value, e.g. "Deal5Damage", "Deal7Damage" etc. (I don't want damage to be entirely based on a character strength or similar).
What's the smoothest way around this problem?
Just a quick question, are you using git?
Can someone please help me? I'm getting this error and I can't open my unity project (except in safe mode)
Library\PackageCache\com.unity.test-framework@1.1.31\UnityEngine.TestRunner\NUnitExtensions\Runner\UnityTestExecutionContext.cs(110,16): error CS0246: The type or namespace name 'EnumerableTestState' could not be found (are you missing a using directive or an assembly reference?)
Hey does anybody know how I can generate a convex mesh using code in unity?
Don't cross post. #📖┃code-of-conduct
When people answer then sure, hard to get help in a constantly moving chat
It's still not allowed
Also it's not even constantly moving, you posted them with a 3 minute gap
Furthermore, it's even still visible on screen
Okay
There you go are you happy
It's a question more fit for code general than code begginer anyways
also have you googled for it or looked at the asset store
I have googled it
Mostly stuff on convex colliders
Google is always where I go first
writing a convex hull generator on your own is a non trivial issue, but its also a solved issue
so there will be many libraries and assets for creating convex meshes
I may be getting confused with concave geometry
Isn't ProBuilder a decent one? Or am I misunderstanding the context
Well I'm trying to build a quake/half-life map loader
I tried generating tris and figured out quickly that the files don't store tri data but apparently data for convex or concave geometry
no clue with out little context is given, i normally think have convex hulls being generated for non convex geo for collsions or render purposes
what does a half-life map loader even mean
Well
half-life just did map loading based on triggers nothing complex
The actual map files
.map
No I mean .map
Jackhammer and trenchbroom and other tools export .map files that I can load in half life
I'm using those files
assuming you meant compiled maps
also just loading a half-life map in unity is not going to be trivial
you will be recreating a lot of wheels
Yeah I know
It's something I'm doing for fun lol
And to maybe use in small retro projects
not even sure why you would need convex hull generators for that, but you will need to be doing a lot meshes setup in code
So I can use hl1 map editors
It seems to store convex mesh data, not polygons
yeah but you can make polygons from that definition
!code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
either way, why not use a tool like sabreCSG or something to give brush based csg tools in unity instead
I have tried but it only generates half of the needed tris
First time I've seen someone upload their .cs file lol
Because I want to make a .map loader, that's the project
Still stuck
Post it in a proper way, I'm not going to download your file
Probably not visible on phone
do `` infront and after your code
Just listen to the !code
Just follow the thing I posted...
Don't "try to do something else", just adhere to that
and explain more clearly what the issue is, "I've messed up" doesn't tell us anything
It's 3 backticks by the way
```
Well that works too I suppose
Also if you're using VS slap CTRL+K+D on that code
Also you didn't exactly define what the issue is with the sound
Why would this even play sound?
Wait it's not even playing sound? (I didn't really look at the code)
Why not just add an event to your animation where it calls the step effect function when the animation is putting the foot down?
Did you 

?
just do it based on the velocity of it
play sound every x seconds while velocity in a direction is greater then some threshold
Sure, but what Passerby said is a valid solution. Just check the velocity in Update, and check if the last step sound was x milliseconds ago.
with that you could even shorten the time as velocity goes up too
each time can cast downwards to get the physics material you are standing over and use that to modify the sound to play and make sure you are infact on the ground
so many ways to do it, just break the problem down into how do you play a sound at a set time interval and how do you detect player movement
important question, I want to make a linux server build of my game but I need to give it commands, how do I collect those commands at my build?
thank you*
I have a cube and I want to Instantiate objects within the bounds of that cube without manually hardcoding the bounds. Is there an easy way to do it?
how do i put a line renderer between 2 ui objects on the same canvas?
Solution?
We gave ideas? You want free handouts from us?
Use a UI Line Renderer
oh thank you!
Create a cube, scale it, then use
Random.Range(-cubeTransform.localScale.x,cubeTransform.localScale.x);
Same for Y and Z.
@cyan vector how do i get access to the UI Line Renderer?
float someX = Mathf.Clamp(someX, -cubeXScale * .5f, cubeXScale * .5f);
Instantiate(prefab, cubePos + new Vector3(someX, 0, 0), Quaternion.Identity);```
this constrains the x axis of the cube. it won’t take the size of the object you are instantiating though
Clone the repo ^^
https://bitbucket.org/UnityUIExtensions/unity-ui-extensions/src/release/
got it, never downloaded an extension like this before :P
Hey everone, I have some problems with an equation calculator that I want to use for creating volumetric clouds. I'm getting 8 compiling errors, all of which correspond to error CS0149. What part did I screw up on coding and how do I fix it?
nobody memorizes error codes
share your error messages, the full ones
you can start with just the first message.
I will say one thing you've done wrong here is your variable names are completely inscrutable.
and the code as you presented it is exactly hwo it was when that error opped up?
is it possible to list the amount of tris being rendered in a scene as a float, if so how can I do it?
oh wait I see the problem
You've defined this variable R:
float R = Mathf.Log(l) + ((v - lo) * (hn - l)) / (ho - lo);
But you also have this method above:
float R(float a, float b, float c, float d, float e)
you are trying to then call the method
but you can't, because you've already used that name R for the local variable
the way to fix this is not to reuse the name R for your local variable @jade heart
local variables should not start with uppercase letters by convention anyway
and this is also an opportunity to improve your variable and method names overall, because these single letter ones are very hard to work with.
UnityEditor.UnityStats.triangles
UnityEditor.UnityStats.vertices
This seems like what you are looking for, that's the same as the stats window.
will these still work when the project is built?
No, it's only in the editor.
Thank you, it works wonders now!
Do you happen to know an alternative which works when the project is built?
When should I use static blackboard class to store variables and when should I use a ScriptableObject for the same effect?
Using static blackboard class I need to repopulate on each recompile. In ScriptableObject it seems that it keeps the data, but does it stay the original or it's a copy (after the recompile)?
Well you would need to code it yourself then, and that wont be an easy task I think. I would expect some assets on the store to do this for you.
oh alright then, thanks anyways
Can you elaborate on what a "static blackboard class" is?
and when you say "store variables" what kind of data are we talking about? What's the intended use and lifecycle for this data?
Something I use to, for example, store preferences and, on change, save them to UnityEditor.EditorPrefs class.
what kind of preferences?
ShowLogs
SaveDuringPlayMode
SaveFolder
...
It's an editor tool
and again can you explain what "static blackboard class" means?
Can someone help me which this if statement. I need to grow a small square. 2D collider logic
This is usually stuff you'd store in a ScriptableObject
and use a SettingsProvider
so you'd get a section in Project Settings
what kind of help do you need with it
what does "grow a square" mean exactly?
what is this supposed to be doing or checking?
I have a point ( Vector2 location)
It's returning an array
I can show in-game problem
Right now, it's drawing lines. I need sqaures
Problem is if statement
It's a globally accessible class that has some useful value types and reference types. For example, I create the EditorPreferences' class instance that will be stored in UnityEditor.EditorPrefs class. I also have a few constants like DefaultSavePath for a Reset method to use. Classes don't need to know what Blackboard class is, they just need to get the data from it. Its usually what a blackboard class is.
Well, for reference types, does it keep the original reference or copies it on a recompile?
no
nothing is kept
except for things that are serialized to assets
or something like EditorPrefs
So using a static POCO or SO, I'll always need to repopulate?
is this writing heightMap data for a Terrain?
SOs are serialized/saved as assets in the project
yes problem is I need to project the players on the chunk
wouldn't you want to compaire ranges of values here, instead of exact values?
E.g. instead of u == location.x || u == location.x + 10 shouldn't it be u >= location.x && u < location.x + 10?
Does anyone know a bit about android studio? Is it possible to put an APK or AAB that I get from unity inside of a view in android studio an put buttons etc over that view with android studio? I wanna use AR functionality from Unity but the rest from android studio
Yes, this is it
yes
not quite as an APK/AAB but you can embed a Unity game as a view in an Android app
lemme dig up the docs
would be awesome, couldn't find anything about that. Not sure what exactly im looking for tbh
This is the overall feature: https://unity.com/features/unity-as-a-library
And here's the docs:
https://docs.unity3d.com/Manual/UnityasaLibrary-Android.html
I got this basic command class that takes a command with a handler to invoke, but for some reason my handler is not allowed. I expect the Delegate type to allow my method, but I end up with the given error. I can't find anything about Delegate types not being allowed in constructors. What am I doing wrong?
public struct PillowCommand
{
public PillowCommand(
string name,
string description,
Delegate handler,
PillowCommandArgument[] arguments,
PillowCommandParameter[] parameters)
{
this.Name = name;
this.Description = description;
this.Handler = handler;
this.Arguments = arguments;
this.Parameters = parameters;
}
public string Name { get; }
public string Description { get; }
public Delegate Handler { get; }
public PillowCommandArgument[] Arguments { get; }
public PillowCommandParameter[] Parameters { get; }
}
You can't use Delegate like that
you should define an actual delegate type
and use that
public delegate void LogHandler(string message, string? prefix);```
I don't have a specific type though. I'm not restricting what can be used
The list of parameters can vary
how do you know how to call/invoke it then?
Oh I see
you have a list of parameters
It's a command system, it's reflection to an extend
(what's the difference between Arguments and Parameters?)
Parameters are optional, maybe I should rephrase them
I could swear this would work
But apparently not because I can't get it to work on methods now
I've never tried to do things this way 🤔
I swear this worked before, I have no idea how lol
https://learn.microsoft.com/en-us/dotnet/api/system.commandline.rootcommand .NET seems to just add a million overloads (SetHandler)
Should you not just do this the old fashioned way, with an interface or something?
public interface MyDelegate{
void Run(PillowCommandArgument[] Arguments, PillowCommandParameter[] Parameters);
}```?
I suppose
Would love a solution to this though
DynamicInvoke should only be used when absolutely necessary. You have better options, you should those.
Which is?
it's not too pretty but you can cast it to it's delegate type which will allow it to get through.
void TakeAFunc(System.Delegate dele)
{
dele.DynamicInvoke( ... );
}
void AnotherFunc()
{
}
void FuncWithInt(int i)
{
}
TakeAFunc((System.Action)AnotherFunc);
TakeAFunc((System.Action<int>)FuncWithInt);
Also not pretty: Just straight up use reflection. pass the object and function name. Not that a command system cares too much, but one benefit is MethodInfo.Invoke performs better than Delegate.DyanmicInvoke.
Singletons work for a single instance. Is there a way to do something similar when multiple objects (so multiple instances) share the same script? I'd want my checkpoint objects to survive the scene reload
Singleton is not what makes it survive the scene reload
parent checkpoints to the manager and add DDOL
you can just DontDestroyOnLoad them or you can just make sure they are memebers of a scene that does not unload
Singletons prevent them duplicating on scene reload right?
I'll look into what DDOL is thanks
hi, i have a player controller script, when player touches the ball; ball position is setting to players forward position.
but i dont have a dribble system. When i run/walk, ball doesnt move and its awful.
how can i make a dribble system like this? "https://youtu.be/-47ak3wYHZs?t=510"
⚠️: if ball is far from player, player shouldnt move
HEDİYEEEE STEAM OYUNUUUUUUUUUU!!!:D
Oyunu alan arkadaş yorum kısmına oyunu aldığına dair mesaj atarsa sevinirim.
Sanctum: Collection
https://www.humblebundle.com/?key=RuVFke3dKAyZmF3m
i need really help, im trying to do this over 2 days..
ye goodluck with that
pretty complex system like that cant be done in 2 days
unless ur a coding god
really would fake it and do it all as a animation
otherwise maybe attack the ball to a target joint on the player
and add force to it once and a while
Declare a variable of class CheckPoint (my c# script) in PlayerManager (which handles the scene reload) and add a DDOL(CheckPoint.gameObject)?
I'm asking but I assume it's not that as it broke my scene reload
but yeah it will take day or 2 work to make dribbling the ball like that look good and work
no
I'll try the animation idea.
but how do I make the player to not be able to rotate before the ball touches the player's foot?
I fail to understand what "parent checkpoints to the manager" means
checkpoints all have 1 common parent object
Oh in the hierarchy
in the hierarchy make them all children of 1 checkpoint manager thingy
ddol on the manager
that way they can all be managed by it, and that can be set to not be destroyed when a scene loads
I'll try that thanks
Error CS1612 Cannot modify the return value of 'ParticleSystem.emission' because it is not a variable
Any help with this? I need to have dynamic emission amounts
don't try to do evefrything on one line
var emissionModule = myParticleSystem.emission;
emissionModule.whatever = whatever;```
tank u
Hello there, I have this simple enemy AI where they just walk around and chase the player when he gets in range, but sometimes my enemies stop on non-walkable areas... Is there someone who can help me with this problem?
this is the code I have for the Enemy AI
doubt agent can go there
you have something else causing it
@fervent burrow show inspector for Agent
it has a box collider
well, the enemies don't go inside the non-walkable area, but they stop against it
@potent sleet @quaint rock The DDOL is in my CheckPointManager script right?
If so, how do I reference each checkpoint in my CheckPointManager GameObject?
Drag them all into a array, or Get components in children
Is there any way I can use the vertices I have stored in an array to generate a tri pattern that will correctly generate a mesh?
I believe I can do the first, but out of curiosity, what does the second solution you offer mean?
Thank you
is there a variation on something like ImageConversion.LoadImage that DOES NOT upload to the GPU? I'm writing a v1 of a tool and feel like uploading a bunch of stuff to the GPU that is just going to be processed CPU side (for now) will just be a bottleneck?
hi, i have a player controller script, when player touches the ball; ball position is setting to players forward position.
but i dont have a dribble system. When i run/walk, ball doesnt move and its awful.
how can i make a dribble system like this? "https://www.youtube.com/watch?v=__tZ4MvkcEg"
Player receives pass in-stride running at full speed, carries the ball for a bit, then reverses direction.
looks super complicated
a ton of animation/inverse kinematics work
and procedural animation
yeah but i need a simple system
if you want something simple it won't look anything like that
hmm yeah
HEDİYEEEE STEAM OYUNUUUUUUUUUU!!!:D
Oyunu alan arkadaş yorum kısmına oyunu aldığına dair mesaj atarsa sevinirim.
Sanctum: Collection
https://www.humblebundle.com/?key=RuVFke3dKAyZmF3m
its simpler than it i think
public class ListManager : ScriptableObject
{
static Dictionary<string, List> propertyLists;
}``` How would I initialize this dictionary in a scriptable object? I want it to always be there. I know in monobehaviour I would place in the start method.
static Dictionary<string, List> propertyLists = new();
you sure you want it to be static btw?
Can I place that right in the property block?
property block?
please help 😢
Maybe you mean in the field initializer? In that case yes
not understanding what you're wanting. If you have attempted something and need help with it you can ask. But you seem to just be asking for someone to build the system for you from scratch.
ok i am playing a game now i will throw the system i tried after the match is over
I mean I don't know where I would put a constructor for this Dictionary in a scriptable object...
You would just add the = new(); to your current line static Dictionary<string, List> propertyLists
Hi! I'd like to use mesh.CombineMeshes method to do some batching. But I can't seem to retain any other uvs other than the regular uvs (I need lightmapping uvs as well as uv set 4 but they turn up blank) 😿
Anyone got any ideas?
the hasLightmapData option seem to indicate that they do some stuff with the uvs as well....
yeah I have that active on meshes I combine that use lightmap. And I can see in my shader that its flagged as having lightmaps but the uv data is blank 😦
you may have to find a way to do it without unitys help
do you mean not using the combinemeshes method?
yes
How would I link my asset file to my editorwindow?
Hi. If I want to change component in script by referencing the “XR Grab Intractable” component and then if I wanted to do something with the interactble event more specifically the activate feature. What would I need to reference in my script would it be interatble events or ActivateEventArgs
I mean, I have a ScriptableObject asset file that is working like a permanent database and I would like my EditorWindow to see it and use it.
In the case of a monobehaviour I believe I can just link it directly, but not sure how to go about this with EditroWindow.
if you know where it is you could just load it with this
https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
I'll give that a try.
i assume you mean the
DualSenseGamepad / controller ?
there is the SetMotorSpeeds function in the input systems code
https://docs.unity.cn/Packages/com.unity.inputsystem@1.2/api/UnityEngine.InputSystem.DualShock.DualSenseGamepadHID.html
I want to create a premade script when clicking an option, sort of like how I can create a new scene when clicking "Scene", but It'd be my own name with my own script. Thanks in advance!
Does unity have some system from drawing components created via script to the scene before running? Like if I add a box collider to a sprite programatically at awake can I get it to draw the box collider's gizmo?
it will draw the gizmo once the collider exists
if you want it to draw a particular gizmo in scene view you can use OnDrawGizmos() or OnDrawGizmosSelected() and draw whatever you wish
anyway to access the box colliders gizmo draw function from the script?
so i dont have to build something manually
the box collider doesn't exist yet so that doesn't make sense
After trying quite a few things with this, I've not managed to make it work. So far I've declared a Component[] type variable which I plugged in with each checkpoint in the inspector.
In Awake() I have a DDOL for CheckPointManager and I loop through Component[] to DDOL each children gameObject. This still isn't it 😦
you do not need to DDOL the childern
only the parent
only mentioned GetComponentsInChildren so you have a easy way to access all of your checkpoints from the manager object
var checkpoints = GetComponentsInChildren<Checkpoint>(); in the checkpoint manager script for example would get you all checkpoint components that are on child objects
Sounds like your looking for a MenuItem or CreateAssetMenu attribute, depending on what your trying to do:
https://docs.unity3d.com/ScriptReference/MenuItem.html
https://docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html
Hi all, I need to implement a star pathfinding in my project. I've never done this before. I've started looking into it and I think I mostly understand it but there's one thing I'm not getting
In my project I'm using it to determine if block A is connected to block b via a chain of other blocks
These blocks can be destroyed in the middle of a chain and I see a potential issue where when I'm walking the grid that when it hits the blank space it's just not going to clear the open list
So how does one go about determining that there is no path when some of the nodes are completely cut off
that's exactly the point. If you do the graph traversal and never reach the destination, there is no path
you should also clarify if you're just implementing A* yourself or using the "A* pathfinding project" asset.
But how do I determine that I have traversed all of the nodes that I'm capable of if I'm just going off of an open list?
I'm implementing it myself
you keep going until your fringe/queue is empty
once it's empty you've traversed everything
Right, but if I just pull in all of the blocks and add it to a list then that would contain all of the blocks that I can traverse and all of the ones that are separated
why would you do that
How else would I do it?
that's not how the algorithm works
you put your starting node in the queue
that's it
to start with
then you are only ever adding the neighbors of the current node to the queue
anything that is not reachable from the starting node will naturally never get added.
Oh!!
Got it now that makes sense
Thanks so much! I would have been circling that all day
how should i go about making a Z axis curve in a 2.5D game? basically i want the player to turn around a curve and have the camera continuously follow them on their path, where the light blue is the cameras position, the blue is the cameras direction its facing, and the black is the players path from a top down perspective
use splines
ill look it up
as for the camera, use Cinemachine
wait so can you explain to me how splines work? from what i can tell they are just a 3D representation of Bezier curves, right?
have you gotten your IDE configured yet?
more or less, sure. They're like a path you can create and then your code can sample the path to get a position and orientation at any point along the curve
you had errors which were not showing before
meaning it was not configured
have you actually started using the Vector3 you assign in OnTriggerStay
so you haven't changed the code at all yet?
then show the current code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
sorry to bug you but, is there any article you know of that documents splines for use in monobehavior scripts? im seeing alot of doccumentation for how to use splines in the viewport to make things like curved meshes, but im not seeing alot on how to access their data at runtime.
actually, post the current code in #💻┃code-beginner because you shouldn't have crossposted in the first place since you were already receiving help in that other channel
just because you didn't receive a spoon-fed answer doesn't mean you weren't receiving help
Using the SplineAnimate comnponent makes it somewhat easy
hold on
you know it was me that you were interacting with in that channel right? i was the one pointing out your issue
#💻┃code-beginner message
so then what part of that interaction was not receiving any answer or help on the topic you had a question for?
I need the objects more than anything. When a checkpoint is hit I destroy its collider so that the play can't "rewind" the level by hitting already-obtained checkpoints. That's why I want all of my checkpoint gameObjects to survive a player death. It saves me a massive headache. It still causes one tho
and we clearly moved past that and i was providing information about your issue. if you wanna just cry about not getting spoon fed help then i'm just going to block you. good luck getting help when you refuse to even cooperate with those actively trying to help you 🤷♂️
also nice job editing your message after the fact when you said "i don't know what that means" instead of "it is already configured" 😉
tmp.Q<Button>("HeroButtonRenderer").clicked += () => HeroButtonClicked(hero);
}
static event HeroButtonClicked(HeroInfo hero)
{
}
I know this is very wrong...how would I setup this to be an event?
is HeroButtonClicked supposed to be an event that other objects are subscribing to? or is it just supposed to be a method?
was hoping it could be both?
that doesn't make sense
🤔
you can subscribe a method to your event and invoke that event, but the event itself cannot be defined like a method
hmm ok thanks
I got to go watch a video again
was wanting everytime that function to be called
and event triggered and everyone that subscribed to the event did a different function
i think you should for sure go find a tutorial about events because you appear to have some major misconceptions about what they are and/or how they are defined
events are epico
is there a way to attach an event to like a VisualElement (UI Toolkit) the same way I do like Button.clicked?
i haven't used UIToolkit so i have no idea. i imagine that it probably has button-related events though 🤷♂️
basically when 1 button is clicked I want the background of others to turn back to off
figured easiest way was using an event
okay and again, i have not used UIToolkit so consult the docs. i'm sure they are pinned in #🧰┃ui-toolkit
Hi there, I made an cube and i want it to stay in place and rotate around player (so that It looks at him) could anyone help me get into the right direction?
"stay in place" and "rotate around the player" seem like they are at odds with one another
what behavior do you want? You want it to orbit the player?
Well idk how to say it so that it makes sense
so you just want it to look at the player
is this 2D or 3D?
"is this 2D or 3D"
"yes"
Thats what i meant, rotate in place
it's basically just:
void LateUpdate() {
transform.right = player.position - transform.position;
}```
I was responding to "so you want it to look at the player" but he typed too fast
Wait thats it?
i know, it was just funny lol
that's it
Thank you : D
it might be transform.up instead of right, it kinda depends how your sprite is drawn
Well, i can always play around it
If you were going to have a large area on a 2d grid game that grows trees and then when they get big enough an NPC comes over and chops it down to get wood, would you have the trees and their sprites be Tiles on a Tilemap where you manipulate the tree by modifying Tiles on the Tilemap based on state? Or would you just use a GameObject for each individual tree? Let's say the area may contain 100-200 trees. As I write this out, I'm leaning towards one option, but curious for input anyway.
it depends on how the interactions work. Ideally you would not have to use a GameObject
if you can handle all the stuff by inspecting the grid data and doing grid-based pathfinding and grid-based logic, then it can all be in tilemaps
renderTexture.style.backgroundImage = new StyleBackground(hero.renderTexture);
(throws erros)
Are you able to set RenderTexture in code in UI Toolkit? I'm able to find setting all other types of background except this
Thanks, it's a roller coaster in my mind. I was originally thinking that I can do it with Tilemaps, but then I thought that calling an instanced object to keep track of the chopping state and handle dropping the wood and despawning the tree would be nice to have incapsulated in a Tree object, so I was thinking GameObject. But now I'm thinking a Scriptable Object per tree that works with a Tilemap. Partly because I'm going to want to do the same thing for other types like rocks, and those would benefit from RuleTiles for rendering larger structures (and the performance benefit of Tilemap for rendering many instances of these things)
I don't think ScriptableObject would be that helpful
but just having basic POCO objects in your own data model in a grid structure would probably work quite well
With the TIlemap as the presentation layer, so to speak
haha thanks, I was just realizing ScriptableObject isn't what I want. I misunderstood their purpose, I thought they were a sort of POCO. I read the docs for ScriptableObject and they're very cool (I'm using them for their intended purpose elsewhere without even realizing it). I'm also working with PhotonFusion so I need some NetworkObject with a NetworkBehavior to act as the controller with an internal structure of items for the trees and their state.
tyty ill try that out
have you ever made UI sytem with state pattern?
i wanna know whats the logic behind handling ui with state pattern
How do I link a scriptableobject to a prefab, in a way that when the prefab changes the scriptable object will respond?
@quaint rock I just ended up making a singleton in my CheckPointManager. It works as intended tho I have a NullReferenceException I have to solve. Thanks a ton tho man, the hierarchy was the key. Thanks Null (too many of you) too!
Why can't I get JObject.FromObject to return when passing an Int32 as a parameter?
Hello guys, so I have planets in a solar system that I can instantiate and they get added to a list but I want them to be destroyed on impact with another planet and remove themselves from the lest. How can I use events to do that or some other method without directly referencing the list?
why wont this work
too lazy to type all this out again but here: #💻┃code-beginner message
I'll rephrase this cuz it's not very clear
Basically I have multiple planets that each need to declare an event whenever they die but I don't think I should loop through every single one of them just to listen out
So I was thinking maybe there is a different solution
i probably would make the script that hold the list a singelton
then you can call a function on that scrip from the dying planet to let the system know its dying
ooh alrighty
wait how do I make a singleton again
do I have to make the class static for that?
you dont
you just have to make sure that a variable that is static is filld with the reference to the object that reperesents the class
alrighty thank you
{
bodies.Remove(celBody);
}
However this is the function
And I can't really make this static
Is there any way to define an interface to only apply to MonoBehaviours? So that you can use properties like .transform on the Interface.
you might want to look up how singletons work in unity
i do...
I can define properties like public Transform transform {get} and it works, but is there a way I can just say "This interface extends from MonoBehaviour so the only things that implement it are also MonoBehaviours"
The problem is the bodies list is always changing
as long as you have just object handeling it thats fine
no
again look how singletons work with Monobehaviours in unity
i'm reading an article alright 👍
Hey can anyone help me why i cant build and run my game? i get burst compiler errors. If you know how to export the log of the console maybe its easier for you to check. I tried to google it and they suggest I need a special module for the Universal Windows Platform in my visual studio. I have tried to install said modules repeatedly and also checked and renamed the file so that the editor can find it. but the errors remain unsolved
Ok I'm sorry but I'm sort of confused because here you said "to let the system know its dying" the problem is I need to pass that this specific planet is dead and to remove it from the list
But I just don't know how I can do that...
Are you building for UWP?
yea
IDK, share your specific errors etc.
you could use this to start the code that notyfys the list script on destruction
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html
is there an easy way to share them? or do i just snippet the console log out of unity
{
if(collision.collider.CompareTag("CelestialBody"))
{
//BlowUp();
}
}
void BlowUp()
{
NBodySimulator.RemoveBody(this);
Destroy(gameObject);
}
I already have this so it's fine
this was after i tried to rename a folder that was named "arm64" into "arm" because he kept complaining he couldnt find the link.exe
Don't go changing folder names. Other things probably depend on those
I'll just directly reference it
well tbh i just copied it and renamed it so i have two of the same but with different names
Is there any way to achieve a reverse-sphere-cast in Unity? Meaning that the sphere (or any of the geometric casts) needs to completely overlap an collider (not just "nudge" it for example) for it to count as a "hit"?
So now you have two identical copies of the same stuff trying to load at once
@naive swallow i mean i was just trying to fix my problem, because he kept saying he cant find it. so i tested that option out. i guess its a bit iffy yea
simplest way I can think of is to check if a few key points on the object are all within the sphere
anyone who can help me? 😦 I have the URP
Don't copy the folder
i deleted it.
its not helping what you are saying because im back where i was. 0
do i just go ahead and install them all ? i spent last two hours trying to install all of the latest versions
Hey there! Is there a way to check if a sprite is currently behind a sprite mask (so when it's being hidden) via code?
Maybe a dumb answer but... use Collider2Ds and normal collision detection stuff
to anyone interested. I had to uncheck and check this, to make it work:
thank you anyway!
I am editing a dictionary inside a scriptable object from a EditorWindow. When I leave edit mode and enter play mode my dictionary is reset. Why is the scriptable Object not maintaining the changes to its data...
Yep, for burst and il2cpp stuff you need the C++ compiler.
i know and it was there to begin with
but apparently it wasnt enough. had to uncheck it and then check it again
then for some reason he found some other missing components
How are you serialising your dictionary ? Dictionary is not serialisable by default isnt it ?
Maybe VS installer bug.🤷♂️
Dictionary is not supported by regular unity serialization
yea probably. i am about to cry honestly. Errors such as that which defies all logic and problem seeking is so frustrating
But you got it solves in the end, right?
yea but now i got the next slap in the face:
a work around i sometimes do, is store things in a list of structs where the struct contains my key and value. then later on reconstruct a proper dictionary from that list
Thanks. I should have thought of that...
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
this provides a good place to do the conversion
Personally, I do the conversion with Linq (.ToDictionary()) in the Awake
awake is not always a option for all types the callback can be nice since it will get recalled if someone edits the list in the inspector
i have this class and i want the second constructor to call the code in the first constructor when its done, is that possible?
You can do it in OnValidate, if it is something you wish to control. That being said, the ISerializationCallbackReceiver is a more complicated way to do it.
doesnt work
public Foo(int id) : this(id, "")
how do i apply that to my code?
public Country(string name, Color color) : this() {
thanks
ok so im trying to figure out witch collider has stopped colliding. I used oncollidionexit but I cant figure out who stopped colliding???
Debug.Log should help out
thx but I'm past that
Hello this is my code. I keep getting the error "object reference not set to an instance of an object" Ive been trying to figure this out for so long. Can someone please help?
Theres a problem on line 39
But I don't know what it is
your IDE needs to be configured
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio: https://on.unity.com/vshub (Installed via Unity Hub)
• Visual Studio: https://on.unity.com/vsmanually (Installed manually)
• VS Code* https://on.unity.com/vscode
• JetBrains Rider: https://on.unity.com/3XgkeqG
• Other/None: https://on.unity.com/3CYp2c9
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
How do I do that?
well did you install visual studio via the unity hub when you installed the unity editor or manually?
Manually
then take a guess at which you should click
once you've got that configured you need to figure out why one (or more) of the objects hit by the overlapcircle do not have a Monsters component
Wait, where do I find this modify option?
in the visual studio installer like the instructions said
But I already have it installed
great! then open the visual studio installer and select the modify option
The monsters component is a script and all the other objects have the script
you wouldn't be getting a NullReferenceException on the line you highlighted if all of the objects on that layer had it 😉
arcorrding to your error that is not true
the overlap or what ever you used, captured something that does not have the Monsters component
you should use TryGetComponent, but you'll also want to figure out why something is being detected by that query that shouldn't be
you can either make sure with your layermask it only hits things with the component, or you can simple check for null and return early or use TryGetComponent
is there a way to convert a string input to a type ?
so say the field has "int" then i can convert this to a type so i can make say an array int[]
i need this for an editor tool where it can generate an array of a custom type the user decides
got a example of the string
got stuff like int.Parse that can take a string and make it a single int
its a field in the inspector of type string so the user could put MyCustomClass
or any other type
then i would want MyCustomClass[]
this is very much sounding like a xy problem
ok ill explain the scenario
i have a map editor tool and users can create their own custom tile class
the editor then needs to be able generate array data of their custom class
so right now my idea to solve this is to use a string input of the name of their class
and the editor tool will use that to create the array of the type
they arent GOs or prefabs so i can't reference it
so approaching this with strings is asking for trouble
so how do i approach it
why cant the user custom tiles just be extending a existing type and override methods of it
would I use
if (attackPoint == null)
return;
or just be types implementing a interface
because it might need to set data in the derived type
which isnt part of the interface
if its a user type, how do you expect to access data on it, of types and names you do not know about
because once you convert the string to the actual type it'll have access to its methods
making the user extend a existing type you control lets you still be able to store it in a knowen type, and still be able to know about and call methods on it while letting the user override parts of it
hmm i guess but then i either have to force the data to be an array of monobehaviour derived classes , or non monobehaviour dervied classes or structs and the user has no choice in the matter
i can see a situation where i dont want monobehaviour but also scenarios where i do for other setups
if you really want to push forward you can just use reflection to do it. but i highly would discourage it
since it makes using it on the other end so much harder, since you would know nothing about the type the user is providing
could you help me out again?
would I use this to only hit the objects with Monsters components
if (attackPoint == null)
return;
well ideally your layermask should be set up to only detect objects with that component, otherwise use TryGetComponent to determine if an object has that component on it
How would I use TryGetComponent, I've only used getcomponent so far
I still need help, would this be the code I would use?
if (TryGetComponent(out Collider2D Monsters))
{
TakeDamage(attackDamage) = true;
}
if (TryGetComponent(out Monsters monsters)
TakeDamage(attackDamage) = true; also makes no sense
then the component it got would be in the monsters variable so you can
monsters.TakeDamage(attackDamage)
It still doesn't work, I get the same error and I'm using the code same code
Same error message
Show the full error message including stack trace as well as the relevant code
And the code?
if (TryGetComponent(out Monsters monsters))
{
monsters.TakeDamage(attackDamage);
}
Well none of that could give a NRE, but you're also calling TryGetComponent on this object instead of the object from the array
Make sure to call it on the correct object then save the code and try it again
If it still errors post the full class using a bit site from #854851968446365696
So where would I add the name of object in this code?
call TryGetComponent on the object from your foreach which i believe was called enemy
show the full class using a bin site
There is also an underline under the enemy part
well then your code didn't compile and you shouldn't even be able to enter play mode
if it's a red underline, that is
in fact, if that is the case and you've actually saved your code then you should have a whole new error in the console
I can't enter play mode now
When I used enemy
well since i'm not psychic why don't you share the code like i've asked and also the error message
if (TryGetComponent(out enemy Monsters))
{
Monsters.TakeDamage(attackDamage);
}

why did you swap out the component type for enemy?
you should be calling TryGetComponent on enemy using the . operator
How do I change that, sorry I'm really confused now
do you know how to call a method on an object?
if you are not sure, take a look at this code where you were calling GetComponent on enemy
#archived-code-general message
so should my code be like this?
if (enemy.TryGetComponent(out Monsters monsters))
{
monsters.TakeDamage(attackDamage);
}
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I'm still getting the same error even with this code
Oh ok
share the full class
Ok
When im buildin the game i get this error
“Create visual studio code”
But i have legit no clue what to do about it 🤭
Then i create it with that visual studio code and tadaa even more confusion 😂
make sure you're looking at the first error in the console. you're also not really providing enough information to know wtf you are talking about
I will share tomorrow, time to head to bed for now 
show the current error message as well
make sure you actually save the code. you don't even have an Update method in this class
the stack is not from the code you posted
I have saved the code and I changed the fixed update to update, nothing happens
Same error
then you're looking at the completely wrong file
double click the error in the console and it will take you to the correct code
the error you gave us is saying there is a NRE on a line with no code, and references a method that does not exist
by the way, i did a bit of googling and it turns out you need to read your error messages better. your error is because you are trying to build directly into the project folder. you need to build to an empty folder
public class Billboard : MonoBehaviour
{
[SerializeField] Camera cam;
void Update()
{
if(cam == null)
cam = GameObject.Find("PlayerCamera").GetComponent<Camera>();
if(cam == null)
return;
transform.LookAt(cam.transform);
transform.Rotate(Vector3.up * 180);
}
}
im following a tutorial for a multiplayer game and this script that finds a player's camera and looks at it returns the NullReferenceException error on the GameObject.Find line
how can i fix this?
that means there was no object found with the name "PlayerCamera"
also you know you can use Camera.main to get the camera tagged with the MainCamera tag without needing to use any of the Find methods, right?
"This function only returns active GameObjects. If no GameObject with name can be found, null is returned"
to add onto this: whenever you spawn a networked player, you should destroy or disable any components/objects that are not needed by the local player so that you don't have to worry about accidentally referencing the wrong player's object
does anyone know of a function that would disconect a player from a relay? for example a function like RelayService.Instance.LeaveAllocation.
how could i send i close request? there really isnt any clear definition
i think i found it thanks for the help
I've been trying to wrangle the UI system for a bit and I thought I had it figured out. I have a segmented meter and I'm creating the segment nodes in Awake() like this:
nodes = new Image[max];
for (int i = 0; i < max; i++)
{
GameObject node = new GameObject($"BarNode.{i}", typeof(Image));
node.transform.SetParent(transform);
Vector3 offsetPosition = Vector3.zero;
offsetPosition.x += anchorSprite.rect.x + ((i + 1) * nodeSpacing) + (i * nodeSpriteWidth);
node.GetComponent<RectTransform>().anchoredPosition = offsetPosition;
nodes[i] = node.GetComponent<Image>();
nodes[i].sprite = onSprite;
}
The problem is that the node ends up with an arbitrary Z position, some arbitrary scale, -10 rotation on the X (wtf?).
try setting the parent when you create the node and not after
That works if I make a prefab to instantiate. I was kind of hoping to avoid that, but so it goes.
i found that if you create a ui element and parent after it causes a bunch of positional errors. weird bug
why whenever i open visual studio, i have to go into preferences and set it as the IDE i want to use as a default ?
how do i keep it as default
?
So, Im making a multiplayer game and trying to get an interaction script to sync door opening and closing however when the Client interacts it works and does the correct opening and closing animations but when a client opens the door the Host sees the opposite animation.
When the client opens/closes the door, the host will see the opposite animation. If the door is open for the host and the client interacts the door will jerk closed then play the open animation and reverse if the host sees it closed
Select it inside unity
i did but everytime i try opening it when i reopen unity, it switches back
I was using a dictionary in a Scriptable Object, only to find that dictionaries are not serializable. How would I achieve the same key value setup using lists?
there are free resources online to serialize a dictionary to view and use from the inspector, but you can have two lists: one for the keys, and the other for the values. when you add an item to the 'key' list, add the value to the 'value' list . . .
hello, i would like to create a leaderboard for a small game i have; how should i go about doing this?
tons of tutorials to start from on google and youtube . . .
If my key was a name, and my value was an address, how would I use the key in this case to retrieve the address?
since it's a list, you need to get the index of the key (from the 'key' list), then use the returned index to access the value (from the 'value' list) . . .
Great, I'll have a look. Thanks.
using the serializable dictionary seems like the easier route though . . .
My initial idea was to place the Key and Value into a struct. Would this work?
I would prefer to work within standard libraries
you can have a list of structs with a key/value, but then you have to use Find with a predicate to search and retrieve the struct based on its key field . . .
it's just one or two scripts that are easy to use, that's up to you though . . .
how would I run that search on the key field?
int index = listAddresses.FindIndex(x => x.key == prefab.name);
no reason to use FindIndex if you have a struct (with key/value), just return the element . . .
int index = listAddresses.FindIndex(x => x.key == prefab.name);
AssetDatabase.DeleteAsset(listAddresses[index].address);
propertyLists.Remove(propertyLists[index]);
listAddresses.Remove(listAddresses[index]);
I'm using the prefab name as the key
problem is, you need to manually search for duplicate keys. if you have any, it'll return the first one found . . .
would someone have 2 prefabs with identical names in a project?
what are you trying to do
I'll leave it broken for now.
I was trying to store a dictionary in a scriptableobject...
i dunno, it's your project. you need to check for all cases . . .
Hey! I'm trying to display debuff sprites in my project but im running into an issue. I need the debuff sprites to move based on the number of them, so if there's one debuff it should be at local 0,0 but if there's 2 they need to both move to the cumulative position is centered as well, and 3 be centered etc etc.. How would I do that?
I think I'll check when someone adds to the list - and only allow a new entry if it does not match an existing.
place them in a horizontal layout group with the a center alignment . . .
oh my god why was i adding them as Gameobjects with spriterenders. i might be mentally deficient
thanks
Are lists serializable in ScriptableObjects?
I've switched to lists and they still not being stored.
So you cant serialize structs. Good to know
the entities do not get rendered .why?
Can you not cross post
cross post? i don't know
Just don’t post the same thing in many channels
Is there a downside to using a public variable with a private setter, beyond not being able to use the [Range(0,1)] etc things?
[field: SerializeField]
public float someValue {get; private set;}
[SerializeField]
private float someOtherValue;
It seems to work, but I don't know if it comes with downsides I don't know of, or is against a recommended standard, or something of that sort.
@bitter hound what’s the purpose of float being public? Inheritance?
Other scripts can read the value but not change it
Have public getter and private settet
That's what it does, yes
Please configure your editor to properly support Unity before asking questions here. #854851968446365696 -> 💡 IDE Configuration
!ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio: https://on.unity.com/vshub (Installed via Unity Hub)
• Visual Studio: https://on.unity.com/vsmanually (Installed manually)
• VS Code* https://on.unity.com/vscode
• JetBrains Rider: https://on.unity.com/3XgkeqG
• Other/None: https://on.unity.com/3CYp2c9
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I assume it's mostly identical to
[SerializeField]
float _someValue;
public someValue {
get { return _somevalue; }
}
@bitter hound I assume this pattern is totally fine, though I would doublecheck if changing it is actually outside scope of other classes
I've checked and it seems to work so far, but I've been an artist that sometimes codes before, and now I'm looking to transition into being a programmer, so I want to make fewer guesses based on "it seems to work" now. 😄
I have personally only used private setter and public getter similar to this way
Range should also work if you specify field: before it. Right now the behaviour of your field and property are basically the same, other than that the property can be read by others outside the class.
If you have no need to read it outside the class, you might aswell make it a private field
Alright, I hadn't noticed that `field:`` makes the other... uh, property modifiers work
Your property is just a wrapper for a backing field right now, same as any other field, so there is not much use to it if you don't actually make use of the features of the property
and a private field would be private float someValue {get; set;} right?
In that case I don't know the difference between a field and a property
{ get; set; } indicates the getter and setter of a property
You can modify the way you get / set its backing field
Previously I've just called all of these 'variables', it seems like I have some reading to do
So in your case here, only the setter is private, and the getter is public
Yeah, I get that part
A property is not a variable
A variable can be many things
I suppose this is a nice read too: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/differences-between-properties-and-variables
I found this:
Avoiding Overuse of Property Getters and Setters
Most people don't realize that property getters and setters are similar to methods when it comes to overhead; it's mainly syntax that differentiates them. A non-virtual property getter or setter that contains no instructions other than the field access will be inlined by the compiler, but in many other cases, this isn't possible. You should carefully consider your use of properties; from inside a class, access fields directly (if possible), and never blindly call properties repeatedly without storing the value in a variable. All that said, this doesn't mean that you should use public fields!
https://stackoverflow.com/questions/2166433/why-ever-use-fields-instead-of-properties
It seems to imply that in some cases properties can be a bit slower?
hello, i am trying to call a: yield return StartCoroutine(exampleCoroutine()); (inside a coroutine)
but the problem is that the coroutine has a for loop and is not looping correctly
i am not sure what the problem is, but i suspect it may have something to do with the code being paused per frame
Little to no change performance wise, really. If you only use a class privately, use a private field. Otherwise consider using a property in some way.
It is actually a violation to use public fields
Properties are basically a conventional format for get and set functions. In C# it is generally considered good practice to use them instead of public fields. Real differences start when you use them to verify if input and output are correct. And nothing stops getter from being more complex than just return value.
this is the code
I like to reference Stylecop on coding styles: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md
IMO properties should only be used to specify how to set a value, be it private, init, or by constructor. Any complex behaviour to set the property should be done in a seperate method altogether, no matter how small
looks like you're starting multiple coroutines
yeah, im trying to code a little cutscene
so where are you starting them
in a coroutine which calls a coroutine after the next
public IEnumerator cutscene(){
yield return new WaitForSeconds(3f);
yield return StartCoroutine(FadeTo(1, 3.5f, sprite1));
StartCoroutine(runText("presents", presentsText, .2f));
yield return StartCoroutine(FadeTo(1, 5, sprite2));
yield return new WaitForSeconds(5f);
}
@thin aurora yeah I don’t personally use them for anything beyond checking if it’s suitable value, but for example microsoft’s own documentation has some examples I would consider ”complex behavior” https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
and where do you call cutscene?
on a trigger enter
Don't use StartCoroutine if you want to wait for the other coroutines to finish. Just yield return FadeTo()
you can add a debug log for when the cutscene is called - you will likely find it's being called twice
ok
is there any way to solve it being called twice?, i've also changed the code to what @mellow sigil told me
i've tested it and the same thing happens
verify that is happening first, don't just assume
right
if that is the case though, an easy way is to add a bool, e.g isPlaying, that is set to true when it starts, and false when it ends - then only start the coroutine if isPlaying is false
guys, if we plan to make some online multiplayer
do we still need the playerprefs ?
for each client
ok, u were right, gonna do as u say
Question makes no sense, why would you need playerprefs for anything?
although if it's being called twice when it should only be called once it's better to fix the root cause instead of patching it
what do you mean by fixing the root? also, i did what deynai suggested
should i disable the collider component?
yeah, though since it's calling twice in OnTriggerEnter that's a can of worms to consider, and the fix is likely similar
also it works now btw
I mean if it's being called more than you expect then there's a problem that you're just covering up
hmm, so is this to do with the collider trigger component or something else? the only elements in this situation that i can think of are just the trigger collider and the player going into it
debug logs are your friend
ok
maybe its because i have multiple colliders on my player
but i think your fix should be ok
Yeah I would not even do that in properties. I expect a method for these things. A property just makes a mess, especially when you introduce any complexity in the form of asynchronous code or setting multiple properties in one transaction
I'm not sure if I ever want to introduce any sort of guard clause to them. I can understand if you add those, but right now I would rather put those in a method too.
Seems like that was indeed the issue, fixed it by making a entire new folder
anyone familiar with firebase know why im getting this error?
Best guess is that the database URL is not set in the Firebase config
might be this issue
https://stackoverflow.com/a/66164019
So i got this weird issue where, the first 2 times the enemy boss spawns in normally, but the third time it disappears and never returns, however i dont see anything that changes lol...
!code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
ComputeBuffer.SetData requires a non nullable data type. I was using a struct. Struct can not be serialized in a scriptable object. What is the correct way to proceed?
what do you mean struct can not be serialized in scriptable object?
are you using the [Serializable] attribute on the struct and making sure the field itself is serializable? for example with [SerializeField]
is a 4x4matrix serializable?
yes actually
public struct MeshProperties
{
public Matrix4x4 mat;
public Vector4 color;
}
yes mark your MeshProperties struct with the [Serializable] attribute
will [SerializeField] work?
that is for the field, let me show
[Serializable]
public struct MeshProperties
{
public Matrix4x4 mat;
public Vector4 color;
}
public sealed class MyScriptableObject : ScriptableObject
{
[SerializeField] private MeshProperties m_meshProperties;
}
if you make the field in the scriptableobject public, you don't need SerializeField
why is Serializable not available for me...
I could literally kiss you right now
Thank you. Thank you. Thank you.
I was rewriting as a class - but then that introduced its own problems. I read somewhere that structs weren't supported.
is it possible to ignore a script for a specific platform? like #if (UNITY_EDITOR) but for Windows builds only
thank you!
What is the proper way to rotate an object with a character controller component?
Anybody know how to fix this prefab being all jumbled when i try to edit it?
it aligns perfectly when i instantiate it, but not when im editing it
might be because it doesn't know how to align until it becomes a child of a grid layout?
i aligned it to the grid layout then made it into a prefab
I think the automated canvas is the problem
And it defaults to the resolution of the game view
@deep willow ^
how do i solve it? lol
Change the resolution of your game view
Or usually, I just edit in the scene honestly, and then apply it back to prefab
Anyone know where UnityEngine.Transform is at the c# source ref?
There is a search bar
I think thats it
Thanks :)
Guys how do I change a variable of a prefab as soon as it's instantiated because there is this flickering when I instantiate this planet
{
Vector2 spawnPos = cam.ScreenToWorldPoint(Input.mousePosition);
GameObject planet = Instantiate(planetPrefab, spawnPos, Quaternion.identity);
planet.GetComponent<CelestialBody>().radius = 0.1f;
CelestialBody celBod = planet.GetComponent<CelestialBody>();
AddBody?.Invoke(celBod);
}
It starts out as radius = 1 but then flicks back to 0.1f
ok i fixed it
thx guys
No problem, glad to help
Hi, I'm working on a script that changes vertex colors on a skinned mesh instance. It works, but for some reason when I copy from SkinnedMeshRenderer.sharedMesh to an instanced mesh it replaces the source sharedMesh in project assets as well. This is documented in the API reference, though it doesn't say why it is so or how to work around it. Is there a way of working only on an instance of a skinned mesh and not the source asset? Short of constructing a new mesh piece by piece in code.
hi there, why doesn't this add force to my 2d object? (i checked with console.WriteLine and it finds gameobject with tag and also the object has rigidbody)
Is the rigidbody kinematic? If so, it doesn't simulate physics then.
its not, i just set the gravity scale to 0
but i have the same on player and i can add force to it just fine
That doesn't matter. You are sure that the AddForce gets called?
If so, show a screenshot of your RigidBody2D component.
i dont think thats its added because the ball doesnt move, thats what im trying to figure out. Why doesn't it add
thats my setup for ball
Do you have multiple ball objects perhaps?
nope, just one with tag ball
Then add a debug.log in your update, and in your if.
will do
Transform.forward will send it to z axis
There's your culprit
Happens lol, but do optimize your code tho
yeah it works now
Doing findobject in update is very performance extensive
will do, its a mess for testing
Cool
yteah i know its better to do it in update
I believe you meant to say Awake?
whats the diffrence?
Just serialize it...
Very big
i think both do something once on start
Update does it continuously every single frame
Finding at all is bad practice.
i meant diffrence between start and update
So if your computer has 120 fps, it will find an object 120 times from your heirarchy
Still very big
Start is called only once
and awake?
Also once but before start
Between start and awake, yeah, but start won't be called if the script is disabled while awake will (if the gameobject is enabled)
There's an entire execution order
ohh, i didnt know that
the more you know i guess
Hey, there.
How to reduce slip in wheel colliders?
I have been modifying Sideways Frictions values and Forward Friction values, but can't figure it out.
My wheels are constantly turning left or right uncontrollably.
Seems more like a #⚛️┃physics question to me.
Does not sound like a coding problem. Try #💻┃unity-talk
Hello everyone, is anyone firm with Editor and PrefabUtility? I am trying to find out, when an object is modified in the scene, somehow this is giving me a zero count list, even if I add something to the prefab. I also tried to update delegate, but that only happens when the prefab is actually saved.
Returns 0 List => PrefabUtility.GetObjectOverrides(childTransform.gameObject).Count);
Returns 12 Length Array no matter the changes => PrefabUtility.GetPropertyModifications(childTransform));
Good afternoon, I have a question about a movement I'm doing, currently I have a vehicle that moves by physics and I would like to make this could not hit the walls and slide down these, does anyone know any way to do it, if with raycasts or some mathematical formula similar to PID?
Hello everyone is anyone firm with
You could probably achieve this with a Physics Material, with friction it should "stick" more frequently, with no friction it should "slide" down surfaces instead
attempting to do sorting on a list but now sure how to go about it
List<VisualElement> SortedList = itemsList.OrderBy(o => o.???).ToList();
I have a itemsList of VisualElements...but I want to sort by a background color inside of the visual elements
aka by
tmp = itemsList[itemAtIndex]
tmp.Q<Button>("ItemButton").style.backgroundColor;```
that background color
hmm
might just be easier to have everything in a dictionary
colorList.Sort((col1,col2)=>col1.AllColorValuesAdded().CompareTo(col2.AllColorValuesAdded()));
Something like that?
probably? not entirely sure and Im terrible at sorts...at this point its probably easiest if I change make another class to store a few things in to make it easier to sort
You can just test it 😄
Hello, how can I separate game input from UI input ? For example, when I click on a button, my script from a totally different game object also recognizes the click
would require quite a few tweaks to work with ui toolkit since I don't have a reference to the item I want to sort at the time I try to sort lol
😄 So you gotta grab the reference before doing so
much too complex for my smol brain 😄
List<StoreItemsVE> SortedList = itemsList.OrderByDescending(o => o.itemRarity).ToList();
how could I add in like a secondary sort? (this "should" work for sorting by rarity)
ex) I want them to sort by ItemType, then secondary sort by ItemRarity
Orderby().ThenBy()
fantastic thanks!
Tip: googling a specific question about something most likely gives you the answer, since many people before you probably wondered this
Source: My answer was a 5 second google search
fair enough thanks, I was struggling getting search results for sorts that was helpful earlier so assumed wrong
alright here is an actual one I can't figure out from google
First link worked for me 🙃
Not to bash of course, googling is a very good skill to have
inside of a sort, I have an enum I want to sort by...how can I chose the "order" of high to low items?
alright here is an actual one I can't figure out from google
public enum ItemType
{
Undefined,
Currency,
Loot,
Material,
Supply,
Recipe,
Weapon,
Armor,
Helmet,
Shield,
Jewelry,
Backpack,
Coupon
}
if I wanted a different way to sort this enum how could I do that?
aka I want recipe, then weapon, then supply as the sort order for example
you can assign an int to enums so Undefined = 0
You manually specify it? I'm not sure what you mean
It sounds very specific
enums are just ints
like chose the order in which it sorts by
An enum is just a list of numbers so if you use Enum.GetValues you get a list of them
makes sense...assume I can't change the enum itself
(enum is from an asset and could really mess up asset code if I change values)
As soon as you change the enum and did not specify a position in the enum, it will mess up all your inspector values
what you could do is create a wrapper that associates a secondary sorting priority value for each, then sort by that value - though that will be something extra you'll need to maintain
just a static dict that maps enum to another value, say
Or just use the NAME plus an INT to be able to sort the enum by name but still got its correct int to call on
sweet thanks guys 🙂
last question...hopefully
why can't I set my itemsList to the new SortedList?
cause you assign a type to a List
it is outside of the scope
itemList is a list of whatever type and SortedList is a type of the namespace Collections
And that 😄 outside of scope too, I would not call it uppercase sortedList tho, cause it seems to be already a thing in collections
ah gotcha...renamed SortedList to sortedList
and now its fixed 😭
didn't know SortedList was a keyword(also just stole the code from stackOverflow)
yeah, bad habit, abandon this! 😄 copy paste without thought will get you 0 knowledge
I mean, I understood the code, just didnt realize the variable name they chose was bad lol
anyway, thanks everyone!
sorts was my most hated things from my coding classes like 4y ago lol
i just shoot it towards the ball
If anyone has time to help could you please DM me so I can send you the details of my problem since my issue seems to be a bit complex to post here. Put simply though I'm having trouble updating a object to match a target position exactly each frame using unity's physics, without causing jitter and also any objects that have a hinge joint component freak out and jitter a lot when interacted with even though I'm using methods such as Rigidbody.MovePosition and MoveRotation
Feel free to open up a thread and explain to everyone here, so we can look into this.
(and pick one channel, you xposted to physics)
Ok thanks, will do. How can I open up a thread and is it expectable to show multiple sections of code as I don't want to flood the thread?
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
NaAquelo's physics thread
Thanks
does anyone have experience with building large open world games? wondering how do i manage terrain chunks for performance
i am considering activating terrains around the player on a 3 x 3 grid:
with each terrain tile being 512 x 512, will this be too large for optimization purposes?
(i am also using culling)
you can only find this out by testing/profiling it on your target hardware
every game is different
right, are there other approaches I can explore?
terrain streaming
approach to terrain streaming
right, that's one approach
tiles are activated as the player moves around
would love to hear how someone who built an open world game handled this
that approach is what terrain streaming is
okay, thank you
Watch GDC on firewatch
I’m working on Lag Compensation and I ran into a problem. On the server I instantiate a “RewindHitbox” game object and then immediately shoot a Raycast. But the problem is apparently at least one FixedUpdate needs to run for a raycast to hit a newly moved object.
They do "portals" when to activate terrain relevant to player @fiery oracle
i actually am watching that talk now! i've seen that talk years ago too
https://youtu.be/WMN710Ttg2A this one
In this 2016 talk, Campo Santo's Jane Ng breaks down the art production challenges encountered when making Firewatch, and explains the methodology behind the team's scene management, asset modeling and world streaming. The talk also goes into some details regarding the specific tools required to achieve the art style in Firewatch, and offers adv...
thank you
Hello, trying to make a camera for my character. Work well in first person , but in third person the camera does not orbitate or stays in the back of my player. Not sure how to do it.
public void Look(Vector2 lookDirection)
{
// Convert mouse input to rotation
float mouseX = lookDirection.x * Time.deltaTime * sensX;
float mouseY = lookDirection.y * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -45, 45f);
// Rotate camera
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
// Rotate Player
playerOrientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
This question isn't code related at all. Try #💻┃unity-talk
okay, thank you