#archived-code-general
1 messages · Page 247 of 1
I'm writing a light level gen script for a prototype. In the first part of the while loop I basically set up some variables I need. In the second half I use a random instance to get up down left or right, but up down left or right may be taken, so I basically just say if right is already generated but I know that some combination of up, down, left or right is open for the current cell, goto the line where a random direction is gotten instead of restarting the loop and regenerating all the variables I need (which were already generated and would generate to the same value if restarted).
also the goto can introduce potential bugs and errors as it allows for non linear program flow which can make it difficult to reason about the state of the program at different points its just not great to use "All the time" but i mean once or twice i dont see why not
idk, goto seems stigmatized. It's still pretty linear unless you have gotos stringed together.
Well sure the goto is linear but it makes other code not linear
I've literally only used it for breaking out of multiple loops at once tbh
i mean, only if you use it like that. I've only really seen cases to use it when you absolutely need to break out of multiple loops with it, or when you want to repeat only part of a method but it would be unreasonable to move that part into its own method or local method.
it just makes the code less structered really and when you start getting lots of scripts it can build up really fast and it can just cause a lot of issues down the road but its not a terrible thing to use, just has to be controlled
well I get what you're trying to say I think, but what issues?
I mean anything can cause issues down the road.
well it creates spaghetti code which makes readability pretty hard which is where the control part has to come in, and the go to statement can cause many unintended bugs and debugging go to statements can present more of a challenge especially without proper commentation and jumping to different parts of code like that might cause values to not be correct depending in the circumstance, and the go to statement may not be supported on other platforms.
But to be fair everything comes with its list of issues
Im only fimiliar with windows and mac so i couldn't tell you what platforms but there are things like that, that wont work on mobile devices
Idk if possible i would find a better alternative to your problem if possible if all else fails screw it
#archived-networking
also the only answer worth anything is "do your own research and determine which networking solution best fits the needs of your project"
also DOTS is not networking
Is GameObject.CompareTag("x") == "x" still better to use than gameObject.tag == "x" in 2024?
the CompareTag method is always going to be better than string equality. also it's just gameObject.CompareTag("x") not gameObject.CompareTag("x") == "x"
Yep!
Thanks
@somber nacelle What about in this instance.
Do you see any room for improvement?
Surely this is better, having a bit of GC once than all the overhead of compare tag multiple times
- local variables should not be prefixed with underscores
- why's the highlighting so bad? Is VS Code actually configured?
- you can get transforms directly from components, you don't need to go through the gameObject
bridgeParentshould just be a Transform if that's what you care about, unless you use it for GameObject-specific things, just use the type you care about
the main benefit of using CompareTag is that it provides relevant errors when you have misspelled a tag instead of just failing silently. the slight performance benefit is really just a bonus
But yes, that is probably on par with CompareTag, but it avoids any warnings CompareTag gives when you're missing a tag
@quartz folio
- I know, however in this instance I prefer the underscore.
- My configuration is fine -- omnisharp is not running so I could take a quick screenshot.
- Can you elaborate?
- I've experimented with both
TransformandGameObjectand GO is just easier for this method.
- col.collider.gameObject.transform;
+ col.collider.transform;
Ah I was wrong on 4, you declare it right there. I thought it was a serialized reference for a moment there
Oh, that's a neat little hack
- your config doesn't look fine
I need it to be like that :p
If they're aware omnisharp is not running, it's fine
Please refer to my second point -- omnisharp is not running I just opened VSCode for a quick screenshot!
Point 4 is how it is because sometimes the class is within a parent that has a rigidbody, and referencing the transform like that ensures there is no missing reference 🙂
I see, hmm c# DevKit should still recognize the solution 🤷♂️
then you don't have intellisense + unity 🤷♂️
I sure do 🙂
@quartz folio @rigid island @somber nacelle Thank you for your assistance and queries!
you do ? bcuz devkit is part of the Unity extension
You don't need it!
Unless you're on an old Unity version or something, pretty sure you do
.NET Install Tool and the C# extension are all you need
say what now
how do i instantiate an object under a parent so it follows them when its spawned
pass the desired parent as the last parameter for Instantiate
@naive heron
GameObject parent = new GameObject("Bridge");
child.transform.SetParent(parent.transform);
@quartz folio I don't know what to tell you, it works perfectly fine and I have minimal bloat packages.
If you have the Unity extension installed—which you should, then it'll have added it as a dependency
curious to see how it is "working perfectly"
I'm starting her up now, I'll prove this
the ol' no access to a debugger, and no refactorings or analysers
That's not a debugger, that's just autocomplete
also missing some other stuff
I know, you were initially asking about the intellisense
if CompareTag("XXXXX") is faster than "XXXXX", then you run =="XXXXX" for n times means it is n times slower than running CompareTag("XXXXX") for n times............
CompareTag is faster only because the managed string needs to be allocated with tag, which they only do once
just depend on how comparetag implemented, i think they use unordered_map internally
not char by char matching
oh wait it still needed to get the hash code for two string then do one comparsion
how do i get the desired parent because nothing im trying is working
wdym how do you get it? do you not know what object you want the parent to be?
@naive heron I already told you
do you have a reference to the parent?
public GameObject cykaBlyatParent;
i tried to implement that and couldnt figure it out
yes as fpsCam
you don't need what they suggested. there is an overload for Instantiate that accepts a parent transform
just pass the object's transform for that parameter
@somber nacelle I think that might be a bit complicated for their skill cap
how 😭
what you suggested is going to confuse them even more considering they probably have a prefab that they are trying to instantiate and don't just want a blank object
have you looked at the docs for the Instantiate method?
okay so show what you tried
private void Update()
{
playerpos = playerModel.transform.position;
}
Instantiate(reloadPlayer, playerpos);
its in a function but ye thats basically it
well for one, you have to pass a transform as the parent. two, if you want to pass a position, you also must pass a rotation, then the parent transform will be the last parameter
If you're struggling to parent a transform..
No offense! Just want to help of course 🙂
You need to reference the Instantiate
GameObject GO = Instantiate(reloadPlayer, playerpos);
playerpos.SetParent(GO);
this is wrong
thank you
this is what i did to fix it|
Instantiate(reloadPlayer, playerModel.transform.position, Quaternion.identity);
well that just sets its position, it does not set its parent
you need to pass the playerMode.transform as the last parameter as i've said before
you explicitly stated you wanted it to follow the desired parent object. this will not do that
you probably want this
public static Object Instantiate(Object original, Transform parent);
```or this
```cs
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
i wanted to make the instantiated object follow a different game object and i assumed that parenting was the only way
so... parent it
sorry but thx
if you move you lose position unless parented
its working already tho
well unless you have some other code somewhere that makes it follow it, then parenting it is the only way
How?
doubt
because the way boxfriend suggested does it in one line ?
also ur parenting it twice
this would be a compile error. It also makes no sense. playerpos is a Vector3
and this^
Fair enough
there is no overloaded version of instantiate takes only the object and one vector3...
does anyone have a workaround for windows' X509 api? I have code to get a list of all certificates in a store: ```
X509Store s = new X509Store(StoreLocation.LocalMachine);
s.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 c in s.Certificates)
{
UnityEngine.Debug.Log("cert: "+c);
}
but it doesnt work
essentially it supposed to go to the local machine certificate directory on Windows and prints all the certificates
Elaborate on this? What happens?
I dont see anything printed
that
s the issue
thats the issue
I checked certmgr and im sure I have certificates on my system
The code isnt picking them up.
Hi, I wonder if should I destroy any created sprite? Or the GC will take care of it automatically?
Like
Sprite sprite = Sprite.Create(texture2D, new Rect(0,0,200,200), Vector2.zero):
How do you know the code is even running? Print the length of the collection
You must Destroy any UnityEngine.Object you create, aside from GameObjects in a scene which will be destroyed with the scene unloading
alrighty
thanks
How to freeze Spring Joint movement from side to side only to leave up and down ?
I need help I'm having wayyy too much trouble placing blocks in a minecraft clone
My placeblocks method looks like
private void PlaceBlocks()
{
if (Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out var hitInfo, reach, blocksMask))
{
Vector3 vector = new Vector3((int)hitInfo.point.x, (int)hitInfo.point.y, (int)hitInfo.point.z);
vector -= playerTransform.forward * 0.001f;
worldManager.GetChunkByBlock(vector).SetBlockAt(vector, BlockData.GlassBlock, transparent: true);
}
}
i put line 6 to sorta move outside the block
private Vector2 RoundToChunkPos(Vector2 pos)
{
return new Vector2(Mathf.FloorToInt(pos.x / 16f) * 16, Mathf.FloorToInt(pos.y / 16f) * 16);
}
public Chunk GetChunkByBlock(Vector3 blockPosition)
{
return chunks[RoundToChunkPos(new Vector2(blockPosition.x, blockPosition.z))];
}
- Raycast
- Calculate the grid coordinate of the block you hit
- Calculate the new grid coordinate by adding one to the existing block grid coordinate in the direction of the Raycast hit normal
- Place block at that calculated grid coordinate
i wanted to see if you guys saw anything wrong
You're doing really fuzzy stuff with the player look direction etc. that's going to be janky
use Vector3Int to make sure no fp errors creep in
public void SetBlockAt(Vector3 pos, int blockType, bool transparent)
{
int blockIndexX = (int) (Mathf.FloorToInt(pos.x) - transform.position.x);
int blockIndexY = (int) Mathf.FloorToInt(pos.y);
int blockIndexZ = (int) (Mathf.FloorToInt(pos.z) - transform.position.z);
Block block = blocks[blockIndexX, blockIndexY, blockIndexZ];
block.type = blockType;
block.transparent = transparent;
BuildChunkMesh();
}
If you're not working in the realm of discrete grid coordinates you need to throw all your code away and start doing so
Should just straight up be using Vector3Int
oh yeah, i meant everything is in integers anyway but yeah
now it's trying to die 😭
idek what's happening
the y coordinate is right
everything else is wrong
my game
is trying
My recommendation remains this: #archived-code-general message
to die
i guess i'm too dumb rn to know how to do step 2-
what am i doing 😭
The stuff you're doing isn't even taking the Raycast hit normal into account, no idea how it can work without that
That's like the most fundamental function you should have in a Minecraft game
Vector3Int vector = new Vector3Int((int)hitInfo.point.x, (int)hitInfo.point.y, (int)hitInfo.point.z);
is this proper for now
i mean
You need to lay a solid ground work of helper functions before you start adding features
do you know how i should do this-
extension methods out the wazoo
i'm trying to figure out where the issue is
i'm guessing it's in the calculation
i mean
Well the Raycast hit will be at the edge of the block
Draw some things in the scene using Debug.DrawRay/DrawLine
does this look okay (Chunk class)
Usually you'd offset that by half a unit inward before converting to get the coordinate
move it inside the block?
so like negative the surface normal
because i'm placing a block :D
Vector3 vector = new Vector3((int)hitInfo.point.x, (int)hitInfo.point.y, (int)hitInfo.point.z);
should i
do that to this
For God's sake use Vector3Int
i thought i was moving it half a unit out
so i thought float yay
I'm saying offset before you convert to int
When you convert to int, then use Vector3Int
E.g. Vector3Int newGridCoord = hitInfo.point + (hitInfo.normal / 2);
Cannot implicitly convert type 'UnityEngine.Vector3' to 'UnityEngine.Vector3Int'
I think there's an explicit conversion
Vector3Int.RoundToInt
E.g. ```cs
Vector3 offsetPos = hitInfo.point + (hitInfo.normal / 2);
Vector3Int newGridPos = (Vector3Int)offsetPos;
private void PlaceBlocks()
{
if (Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out var hitInfo, reach, blocksMask))
{
Vector3Int blockPos = Vector3Int.RoundToInt(hitInfo.point + (hitInfo.normal / 2));
worldManager.GetChunkByBlock(blockPos).SetBlockAt(blockPos, BlockData.GlassBlock, transparent: true);
}
}
is that good
now I don't even know what's going on, it works sometimes but then it doesn't?
usually it works but then sometimes it'll decide to place blocks in the air
oh what is happening
is it sorta possible to draw a box around the block it would be targeting
like in minecraft
You can draw anything using a number of lines
More math lesgo
(They are editor-only lines) and I have a package that can draw more advanced shapes https://github.com/vertxxyz/Vertx.Debugging
I wonder what I could print to check if it's working
You could use the debugger and just go over everything
there's rarely a reason to print when you can just look at variables and execution directly
this is so dumb I'm printing values and I can't see a noticable difference between the times it placed it correct and wrong
wait
...it works now?
@quartz folio @leaden ice is this code good or stupid (it works)
private void PlaceBlocks()
{
if (Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out var hitInfo, reach, blocksMask))
{
Vector3 vector = hitInfo.point + (hitInfo.normal / 2);
Vector3Int blockPos = new Vector3Int(Mathf.FloorToInt(vector.x), Mathf.FloorToInt(vector.y), Mathf.FloorToInt(vector.z));
Debug.Log("Point: " + hitInfo.point);
Debug.Log("Half Normal: " + hitInfo.normal/2);
Debug.Log("Sum: " + (hitInfo.point + hitInfo.normal/2));
Debug.Log("Block Position: " + blockPos);
Debug.Log("---------------------------");
worldManager.GetChunkByBlock(blockPos).SetBlockAt(blockPos, BlockData.GlassBlock, transparent: true);
}
}
Not sure where the best place to ask this is - it's a Unity Native splines question. I would like to efficiently look up a point on the spline at a set distance away. GetPointAtLinearDistance returns the linear distance so is not what I need. I can walk the spline manually until I reach the distance I want, but this is super inefficient for lots of points... Am I missing a method somewhere? I need a parameterized version of the spline basically.
is the spline deforming after creation?
It can be yeah
so cacheing cumulative distances wont work?
Yeah that's my fallback - I can cache once and then use that cache for all the points. I'm just wondering whether that's being done internally somewhere
You can access ConvertIndexUnit from a SplinePath to convert between distances and normalized values
oooh ok, I'll check that out, thanks!
Ah wait no, the value I have is a distance, the value I want returned is t. ConvertIndexUnit will do the opposite?
Ahh yes sorry missed the second method in the docs
I haven't used it that much, I just have a memory of using some jank conversion function in the past 😄
I looked at SpriteAnimate and noticed that's what it uses
Guys, first line of code is obsolete now, and i am not sure how to edit 2nd one properly so it works, can u help?
Yeah that's awesome, works fine. Thanks!
Guys how can I be master at using events and delegates? They are core of game dev, i believe.
practice
You need to defeat the previous master in a fair combat.
I want a way to make all type of NPCs to look at the player when approached and salute them (salute code is in second pic). How do I do this?
Is there a way to make the NPBCrain abstract class already have the function in the second pic in it?
abstract class can have non abstract methods
So i should learn DOTS and ECS, or have the changed the paradigm?
Would something like this work? I still have to fix in the errors, I was using a navmeshagent for the random wanderer NPC who stops when player gets close.
How can I achieve same condition about distance from this NPC to the player in the if statement?
@fervent furnaceCan I add a start function to the abstract class?
I need to add the animator and transform
your abstract class is ScriptableObject......
you can add what even you like
ohhhh, sorry for the stupid questions, I have not worked with abstracts much😅
wait, your npc brain is scriptable object then you cant access the methods from monobehaviour
or inherit from it
oh
So what do I do? 🥲
I remember Fen sent me this code, does this help in any way?
make your monobehaviour base class of other specific npc script eg
public class Letter:Monobahaviour
public class A:Letter
yes, put the common methods in the "top" most class
I will try that, 1 sec
Hello, i have this error when I build my project, I'm in URP on Unity 2022.3.5f1. The game work normally in editor, sometimes when I build there is no error but the app show just a black screen. This is the error :
Recursive serialization is not allowed for threaded serialization - files cannot be written during serialization callbacks
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()
Unable to write objects to temporary file: Temp/assetCreatePath
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()
UnityException: Creating asset at path Assets/HDRPDefaultResources/HDRenderPipelineGlobalSettings.asset failed.
UnityEngine.Rendering.HighDefinition.HDRenderPipelineGlobalSettings.Create (System.String path, UnityEngine.Rendering.HighDefinition.HDRenderPipelineGlobalSettings dataSource) (at ./Library/PackageCache/com.unity.render-pipelines.high-definition@14.0.8/Runtime/RenderPipeline/HDRenderPipelineGlobalSettings.cs:140)
UnityEngine.Rendering.HighDefinition.HDRenderPipelineGlobalSettings.Ensure (System.Boolean canCreateNewAsset) (at ./Library/PackageCache/com.unity.render-pipelines.high-definition@14.0.8/Runtime/RenderPipeline/HDRenderPipelineGlobalSettings.cs:102)
...
Error building Player: 372 errors
Something like this? If so, where do I put ScriptableObject tag?
npc inherits from npcbrain and npcbrain inherits from monobehaviour
i dk what you mean by ScriptableObject tag, ScriptableObject is a class
think in this way: inheritance usually means "is" (or are)
you are citizen and citizens are human
so
citizen:human
you:citizen
GameObject gun = Instantiate(g);
DontDestroyOnLoad(gun);
gun.GetComponent<NetworkObject>().Spawn(false);
ConstraintSource src = new ConstraintSource();
src.sourceTransform = weaponHolder;
gun.GetComponent<ParentConstraint>().AddSource(src);
I am trying to spawn the gun prefab with this code that works fine but the issue comes with the ParentConstraint cause for some it does not follow the transform of WeaponHolder but whenever I change the index of it to 1 in runtime it does work -_-
i realize that npc is not npcbrain, you can use composition instead (let npc stores one npcbrain)
Make sure the ParentConstraint is active, enabled and has weight at 1.
is this correct ?
Make sure lock is enabled in Constraint Settings
it is
src.weight = 1;
lemme try
oh that was it works now!
thanks
I am still a bit confused sorry. I need to make scriptableobject so I can create NPC SO for the different type of NPCs, also So I can add name, NPC type, etc
@fervent furnace I was watching this guide and was trying to follow it. https://youtu.be/0VV24g1SxGU?si=H0qMGDNselBu7E6b
Learn how to setup Enemy Brains or AI Behavior using Scriptable Objects allowing you to easily drag and drop new ai behavior through the Unity inspector.
Scriptable Objects are a powerful tool in structuring your code cleanly, and here is no exception. With this approach you can setup a complex enemy a.i. behavior tree while all of the behavior...
yes your npcbrain (or other class that stores data) is scriptable object
while the enemy in world store the reference to its scriptable object
So is my current NPCbrain a scriptable object?
no, it inherit from npc and npc is monobehaviour
Now I am confused 🥲
So I dont have any SO?
I am trying to achieve something like this. Where I can make an SO of the desired NPC type (wanderer, teleporter, weaponsmith) and then the person adding these to the scene just need to give them a name, and maybe some other perimiter like teleport location, etc
@fervent furnaceI hope it makes sense what I want to achieve
I just dont know how to achieve it
I currently have a Crowd Simulator using RVO2 for Collision Avoidance and A* for Pathfinding. I'm in school and for my course I need to evaluate something so I need another simple collision avoidance algo to compare with the one I have. I want something as simple as possible because I just want to be done with this course and im stressed. What is something I can use for collision avoidance and use A* for pathfinding as well on it (not a must but probably easiest)?
Originally I was thinking Boids but Boids and pathfinding is basically mutually exclusive
Don't really have the time to deep dive and learn to how to implement something difficult and complex..
I was using ScriptableObjects to hold and update stats of certain characters. Everything works okay.
But when I load those stats from a json file it works in the Editor, but not in the Build. Am I doing this wrong?
Even though debug messages show the correct values, in other areas of the game, the values are not correct in the Build.
How do I do this?
use composition
Any form of avoidance is mutually exclusive with pathfinding. You need to blend between the two.
you can have enemy (monobehaviour) and data (scriptable object), enemy can store the data
Hard to say anything without seeing your implementation.
public abstract class Enemy:MonoXX{
public data theData;
}
public class Enemy0:Enemy;
public class Enemy1:Enemy;
public abstract class data:ScriptableObject;
public class data0:data;
public class data1:data;
```then enemy0 and enemy1 can reference data0 or data1 (or not having data as abstract class if no more variations)
True, just feels quite inherently hard with boids since the whole point of boids are to just flock and follow average alignment etc. I guess you can override it with goals and obstacles changing the alignment
And if two groups meet i want them to avoid eachother but not merge
pass through basically
Im gonna try and just use the RVO I have but without A* and then just use rudimentary collision avoidance with like a raycast and then just rotate to the side if it hits an obstacle or something
I hope you can bear with me, If we take it step by step. Is the following correct in the pic?
https://en.wikipedia.org/wiki/Multi-agent_pathfinding
oh np-hard.....
The problem of Multi-Agent Pathfinding (MAPF) is an instance of multi-agent planning and consists in the computation of collision-free paths for a group of agents from their location to an assigned target. It is an optimization problem, since the aim is to find those paths that optimize a given objective function, usually defined as the number o...
do you know what is inheritance first? i think you dont understand it at all....
I understand the concept of it, but I am getting very confused while trying to apply it together with scriptable objects. I have used inheritence multiple times in previous java projects
For example I want to have this abstract NPCBrain class, where NPCWandererBrain and NPCTeleporterBrain inherites the Think and Salute methods from it. Inside the Think method each of those will use it differently
think scriptable object not scriptable object, it is just some base class
then you can reference it without care what it exactly is
public class NPCBrain:magicalclass{
public abstract returntype think(parameters);
}
public class ActualNPC:monobehaviour{
public data theData;
}
If you are using raycasts for collision detection, do you create a new one every update? I assume so, just wanna check so Im not "Ray ray = new Ray(transform.position, transform.forward);" every single update unnecessarily.
public class NPCWandererBrain:NPCBrain;
public class NPCTeleporterBrain:NPCBrain;
```assume they both implement think(), then in ActualNPC:
```cs
var result=theData.think(parameters);
@fervent furnace I kinda understand what you are getting at, for me the class names are a bit confusing. Is it possible for you to use my class names in instead of those? I think it will greatly help me understand
If you want to get the current position/direction of the object, you will need to do this every frame yes
note that Ray is a struct. Structs are stack allocated and will not create garbage for the GC
scriptable object has nothing to do with how you organize the inheritance tree of different object btw
What is magicalclass here?
ohhhh
scriptable object
it just add an additional root to your tree for unity to use your objects
Is this better?
Another Splines question ( @quartz folio ?) - I can get callbacks from EditorSplineUtility.afterSplineWasModified when the spline container is on the same gameobject as the script with the custom editor... However what I want is callbacks from a spline that is referenced by the script, and I can't see a way to pass the target spline to EditorSplineUtility.afterSplineWasModified?
yes, something likes that
btw i think it is better to let the NPC having variation not the data, but idk what your game design is
I just want it to be simple. So I have this soldier NPC that I want him to have a couple of different types, like Wanderer (who move randomly, like this guy in the pic) then a teleporter guy (you interact with him and he will teleport you to a location)
Hello! I would like to have an add users option on my menu(Something like a friendlist)
I have no idea, how can I call a button to spawn with the selected user profile, so that when they click the name of the added user, they will see the details of the profile.
I'm using firebase as a backend
can we change the alpha of an Imgae through code at runtime?
of course
how Im trying to access it but the option ain't coming
wdym by "the option ain't coming"?
Color temp = yourImageComponent.color;
temp.a = desiredAlphaValue;
yourImageComponent.color = temp;
like that
why did you write .Color when it's called color?
Also the correct technique is here: #archived-code-general message
coz color wasn't working as well
In what way was it "not working"?
You need to actually read your error messages, don't ignore them.
They tell you what's wrong with your code.
aight thanks for the help mates
do not crosspost #💻┃code-beginner message
Im trying to evalute two different crowd simulators for school. One I'm using is much more complex and the other is simple. The complex one seems to move slower and slow down as it gets further along (seems to still be smooth but the agents move slower) I'm assuming this is due to it being more complicated so lower fps. I'm thinking of just counting FPS instead and using that as the metric for how long it takes agents to get from A to B with the two different algorithms. Since one will in real time be much slower but will actually probably be better in terms of how efficiently the agents move, does this seem reasonable?
For the informed im using A Star with RVO2 in one, and just A Star in the other. Obviously the one using RVO2 is the slower one in realtime.
But yeah, assuming FPS is good metric that connects them
FPS would be a measure of how quickly your computer can run the algorithm
It doesn't say anything about how good the pathfinding is
which I imagine is what you're actually trying to measure?
It's unclear what you're comparing
computational performance, or the quality of the paths generated
A* is a general purpose pathfinding algorithm which will always find the shortest possible path (guaranteed unless your heuristic function doesn't conform to the requirements)
RVO2 is more of a navigation algorithm with collision avoidance iirc
Stopwatch class is a good tool to measure how long a given evaluation takes, and is a better measure for just one specific thing.
But praetor is right that it’s not clear what you are looking for.
Stopwatch just requires you to be able to clearly define a line of code when you start and another line when done.
When i start the game prefabs are invisible on the ingame camera but i can see them in scene. Can somone help me ?
sounds like they're not actually in view of the game camera
perhaps they're behind it for example
assuming you are on 2D, check their z position
thanks
Yeah I'm having a hard time finding a way to measure in time how good a crowd sim is since the computer plays a part. I have two, and I want to measure in time efficiency how long it takes for one to get to its goal, so lets say two groups of 5 passing eachother to get the other side.
A crowd sim using only A star will deadlock a lot and take longer since it won't avoid other agents/characters. But the one using RVO on top of A star will be faster. But my computer however will take longer to simulate the RVO one, since its more complex. So in Real time it will appear slower, even though it isn't. Basically the agents move much slower in the RVO one because its slower to calculate each timestep.
So again you need to decide if you're comparing computational efficiency or navigation quality or something else
Navigation quality
What you can do is just use an in game timer e.g. in FixedUpdate
float timer;
void FixedUpdate() {
timer += Time.deltaTIme;
}```
you need a metric for navigation quality then, friendo
use this in game time to measure how fast the things navigate
if you don't care about actual real time running speed this is ideal
Yeah but the further along the sim it goes, the slower the agents move because more calculations need to be made. Thats just because of my computer
not the algorithms theoretical movement
this will account for that
that's why we are using an ingame timer
not a real world timer
i would use Stopwatch for that tbh
Oh it will? But not if its in Update right?
stopwatch uses system time
update should actually work as well
but generally simulation style things should be using FixedUpdate or an equivalent anyway
otherwise they may be inconsistent
Time.time will use ingame time, and inlcude time spent on other tasks, like overhead and rendering, and managing scripts etc.
i think you would need
System.Diagnostics.Stopwatch sw = new();
sw.Start();
CallMyExpensiveMethod();
Debug.Log(sw.Elapsed….formatting);
to isolate just the CPU cost of the one expensive method that doesn’t take a whole frame’s computational time.
Hm I'm a little confused between the two approaches. Im not trying to evaluate how fast a certain method is, I'm trying to evaluate in a consistent way, how long it takes for my simulation to finish its goal, from A to B, even though how fast the agents move varies depending on where it is in the simulation. Since in the beginning its pretty fast, and the further it gets they move slower, and then start moving faster at the end when some agents finish up. But the time should be consistent through all of these, i dont want it to count as if its taking longer just because the agents are slowing down.
I'm using this code to read the ground color to determine footstep sound
Texture2D texture = renderer.material.mainTexture as Texture2D;
Vector2 pixelUV = _pushing.groundHit.textureCoord;
Color pixelColor = texture.GetPixelBilinear(pixelUV.x, pixelUV.y);
this works fine in editor, but I just tried building an executable (on osx) and I see in the logs that the color I'm getting back is just "(0, 0, 0, 1)" is there anything special I need to do with materials / textures to do this in the executable? I had to mark the texture as readable in import settings to make this work in the editor, but unity gave me an error suggesting that, in the executable it just gives the wrong value
Since they are only slowing down due to the complexity of the code getting more and more demanding in the middle of the simulation.
both are just ways of measuring time
Stopwatch measures system time between two points of code.
Time.time will get you ingame time for a frame
so if one frame takes 12 ms and another takes 130 ms, Time.time will tell you that
if you want to isolate just the amount of system time it takes to execute a block of code, you start a stopwatch, run the code, and then see what is on the stopwatch
does this make sense?
Time.time is slightly decoupled from realworld time. System time is basically looking at how many clock cycles your processor took between lines A and B
what should be added ?
com.unity.cinemachine only shows certain methods, but will still recognize the missing ones like CinemachineVirtualCamera
But I thought we were interested in the actual simulation-time navigation speed/duration of the characters, not the execution time of the algoriuthm
i thought he wanted to know about how fast his algorithm executes to compare two algorithms
Trying to give my Teleport Location as a Transform parameter in my SO. It doesnt work?
you cant reference anything on screen in asset
SO always exists. Transform is a component on a gameobject that only gets instantiated during runtime
Wait, so how do I achieve this? 🥲
so pass it as parameter, as what i told you
sorry if not, but are you talking to me ?
SO cannot hold a transform well because the SO can exist when the transform does not yet
Assets can't reference objects from the scene
you need a different way to reference that position
Not sure how to 🥲
there are many ways
Where would I do that?
bottom line is: SO should only reference something that always exists
eg int teleporter ID. Then have a monobehaviour that searches for the gameobject/transform that matches that ID
that isn’t the only way, but there are many ways
Can you explain more about this? I am really not sure how to do that
i gave my SO a field for something that only exists at runtime. I made it work through lots of patching, but it was a really incredibly stupid idea
make a singleton that manages all teleporters, and puts them into an array by ID. And let every teleporter have an ID. Write the ID into your SO.
singleton can connect teleporter to SO now
Can someone help me with a button? I used this code before adding the ability for the box to press the button. But now, every time my player moves away, the button deactivates, even if the box is still there.
1 sec, I will look up how to do that
Since I'm using flat shaded assets and the color / uvs aren't interpolated I though I'd getaway without calling getpixel. So now I just examine the uv coords to determine the color, and again this works in the editor, but in the build executable RaycastHit.textureCoord comes back as 0,0???
ah now that the problem is reading uv's and not the texture I could find an answer: https://forum.unity.com/threads/raycasthit-texturecoord-working-perfect-in-editor-defaulting-to-0-0-in-build.1140568/
This stuff looks too advanced for me 🥲
General Question: What would be the best way to handle Pokemon style gameplay? Not the turn based stuff, I'm more meaning the way they handle movement and gameplay. As in, they move around in a 2D top-down world and then enter battles which takes them to an entirely different screen dedicated to the battles.
If I was to recreate that idea of gameplay (switch between movement and battle), what would be the best way to do this? To have the 'battle' screen be GameObject overlaying the main scene and just SetActive(true/false) a parent to enable/disable the battle screen - or have the battle happen in a different scene altogether. Would there be any advantages/drawbacks to either?
I understand I'm asking a rather vague question of a rather in depth mechanic, a generally vague answer will also do just fine 👍
Is there a way without singleton to just hardcode 1-3 teleport locations and then in the SO you select one of them in a drop down menu like:
TeleportLocation: {Homebase, Firing Range, Arena}
If so, what class do I put it in?
you'd use an enum for this.
// Define the enum
public enum TeleportLocation {
Homebase,
FiringRange,
Arena
}
// make a field of that type
public TeleportLocation location;```
How/Do I give the coordinates of those locations in the Start()?
why in Start?
why not something like:
Vector3 GetPosition(TeleportLocation location) {
switch (location) {
case TeleportLocation.Homebase:
return new Vector3(0, 5, 10);
case TeleportLocation.Arena:
return new Vector3(5, 1, 6);
// etc...
}
}```
ohhhh, that looks very good
I wasn't sure, my brain is melting and I have my exam tomorrow 🥲
Not sure how to fix these mistakes
transform is a property of a game object, your location is an Enum type
And your GetPosition function doesn't return in all cases, you need to include a default: to your switch statement.
the errors are pretty clear I feel 🤔
why are you tryin gto do location.transform.positon (which makes no sense??) instead of calling the function we just wrote?
Like this?
Yeah sorry, my mind cant focus much at the moment haha
do you know what is enum
I did, but it printed out nothing
I tested in another engine, and without printing length I was able to get output
To reproduce: 1. Open the project, attached by tester (windowsStoreEmpty.zip) 2. Open the "scene" scene 3. Open the TestScript 5. Op...
looks like you'd have to use a native plugin if you want this information
thank you for the reference. yes, in my case i have to use Unity so that is a good suggestion
it's a big component of my project so it kinda sucks
So i used this Unity docs example so I could "make" a dict in my inspector, all worked fine until i tried to edit the list after i compile after correcting an error.
now i cannot add items, but i cant still remove
here is my code and inspector:
What happens when you try?
your code won't let one of the lists be longer than the other
it will only iterate up to the min of the two
I wouldn't use two separate lists here
I would use one list containing a struct with both the key and value data in it
I would like to request feedback still, on the topic of: does this sound like a good system to use for collectibles?
its weird Untiy showcase a code snippet with this limit
The docs example isn't complete. It just shows the gist of it.
i'll try ty
I do know what it is and have used it before, doesn't mean I can focus well with a strong migraine, I just need to finish this code ASAP so I am ready for my exam tomorrow
@leaden ice@vagrant blade I am a bit lost with trying to make my enum list showup in the inspector for the SO
the default access modifier is private
it needs public or [SerializeField]
ohhhh, damn my brain really is turned of 😭
is your exam related to this game you are making on?
Yes it is this game
Hey everyone,
In this tutorial we cover the controversial SINGLETON! Many people will hate me for teaching this but I think it is a useful tool to have, or at least know about when programming. Hope you learned something and thanks for watching!
Example video of singleton that exists in scene (Canvas Manager):
https://www.youtube.com/watch?v=v...
you should use this singleton implementation
very simple way to implement singletons in unity
I have multiple kinds of singletons (how ironic)
using UnityEngine;
public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Instantiate(Resources.Load<T>("SingletonPrefab/" + typeof(T).Name));
}
return _instance;
}
}
}
my fave
this is used to set up some DontDestroyOnLoad objects
the singleton class I linked derived from monobehaviour
it's got everything you need for singletons in unity
its GetInstance() is thread-safe, can check scene for already-existing monobehaviours in the scene, and allows DontDestroyOnLoad optionally
it's just a lot better
this singleton yoinks itself from the Resources folder
returning null when the game is quitting is a decent idea
i ran into a similar problem when unloading a scene
the singleton object could get destroyed before something else tried to use it (to unsubscribe from events)
i think I added in an oprional protected field to avoid DontDestroyOnLoad
using UnityEngine;
public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
}
return _instance;
}
}
}
extremely similar idea to the first one
hold up something is wrong with the implementation I linked. The implementation I know has a lock for threads
is accessing a unity object from anything but the main thrad ever legal
i haven't really wanted to do that before
I know that the video said that implementation wouldn't handle multithreading correctly.
yeah. I'm pretty sure you need a lock
do you guys actuall watch then do in unity learn or do while watching ;-;
i feel its easier for me to do the latter ahsdbahwdb
Hello everyone! Did anyone experience any issue with the camera movement after switching to new player input system? When I'm just moving with A/D around an object or corner or anything looks smooth but if a move the camera and press A/D it's becomes really jittery. I'll attach a video below if anyone had this problem. I've been spinning around it all day long 😭
I will get to that if I have time
Are you using deltaTime to scale your mouse input, by any chance
That can cause gnarly jittering (because it's wrong)
Could the mouse_x / mouse_y cause the problem since I'm using deltaTime there?
Yes, that's wrong
Mouse input is an absolute amount. It's not a rate of change, like a joystick would be
Don't scale it by deltaTime.
I'll try it and get back to you, thank you!
I cant seem to get the player to teleport when they get close/touch the soldier. What am I missing here?
You'll need to adjust your mouse sensitivity to compensate for this (cut it by a factor of 60 or something)
'right
If you multiply deltaTime in, you'll wind up making small movements really small, and large movements...less small
since longer frame times mean the mouse moves further
@leaden ice@hard viper@fervent furnace (sorry for mass ping, just need this quickly solved 🥲 )
where is the update
This should have taken care of it
It worked for the wanderingbrain
why is it taking so long? What should i do?
If unity gets stuck for that long, just kill the process and reopen it
will it damage my project?
@fervent furnaceIt does print out this
Seems like the player teleport line is not working correctly
Nope. It could mess up the Library, but that can be completely deleted and recreated without issue
the library is full of cached files, basically
log the return of GetPosition not the enum value
Somehow it's still not working. I've also adjusted the sensitivity
But it still does the same
alright, 1 sec
Does it still happen if you maximize the game view?
I was thinking that the problem might be cuz i have the movement inside fixedupdate and the cam movement inside update, maybe?
Ah
Yeah
So its correct location
If you’re using a rigidbody, turn on interpolation
magic numbers 😮
If you’re using a character controller, just move in Update
😭
magic hard code number, btw where is the player after teleported, probably the magic number is wrong
The player doesnt get teleported at all
it SHOULD teleport the player exactly there in the back of the tent
is there any other thing control the player position
There is this script
public class PlayerMove : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f * 2;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
bool isMoving;
private Vector3 LastPosition = new Vector3(0f, 0f, 0f);
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//Ground check
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//Reset velocity if grounded
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
// Getting the input
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
// Creating the moving vector
Vector3 move = transform.right * x + transform.forward * z; //(right - red axis, forward - blue axis)
// Actually moving the player
controller.Move(move * speed * Time.deltaTime);
// check if the player can jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
// Going up
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
//Falling down
velocity.y += gravity * Time.deltaTime;
//Executing the jump
controller.Move(velocity * Time.deltaTime);
//Check if the player is moving
if (LastPosition != gameObject.transform.position && isGrounded == true)
{
isMoving = true;
// for later use
}
else
{
isMoving = false;
// for later use
}
LastPosition = gameObject.transform.position;
}
}
My groupmate made that
I've changed from interpolate to extrapolate, it's still jittering but not as fast as before, but still visible
havent used character controller, but try to use controller.move position? , cc will override transform position iirc
ohhh, I will try that, 1 sec
It's very easy to get jitter if your camera's movement and rotation happen at different intervals
I'm not sure I'd want to use a rigidbody for a first-person camera like that
is it possible to swap it to a cc and still use the new player imput system?
Absolutely.
two unrelated things
#854851968446365696 on how to post code
alright, i ll give it a shot, thank you so much!
just checked docu, there is no method likes rb.move position in character controller....just follow the link posted by navarone
i dont know where to ask but how do i fix this error? Internal build system error. read the full binlog without getting a BuildFinishedMessage, while the backend process is still running
I tried putting that code in the NPCTeleporter class, getting the following error.
Not sure how to call the controller in the PlayerMovement class from the Teleport class
where did you put the script cause if you already have a refrence you should have no errors..
also this is more of the realm of #💻┃code-beginner
I thought it would make sense to put it where I am supposed to teleport the player in
Should we move there?
yes, and also did you assign controller..?
hi everyone. i have problems with connecting my unity to sql. someone please text. its very important
you're going to need to share code and provide some more information
is there evrything ok?
because when i trying to register an user i have :User creation failed. Error
Considering your !ide is not configured properly no
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
• Other/None
But since you are getting the debug.log it means you are getting a response different than 0 from your php script
btw
i was trying but nothing changed
this has nothing to do with SQL, it's a php problem I guess
so you should be looking at the server log
I'll name myself ', '', ''); DROP TABLE players -- and register, brb
Please parameterize your queries
Hey, just curious if you were able to solve the issue?
I found out I'm rotating the camera and I should rotate the rigidbody instead. Idk how to do this but trying now
Ok thanks, I'll try that too.
I tried using Cinemachine, set Update Method to Fixed Update and it seems to be better.
What is your rigidbody's interpolation setting?
would anybody be able to tell me why my script isnt detecting any collisions
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting.Dependencies.NCalc;
using UnityEngine;
public class ScoreTrigger : MonoBehaviour
{
private ScoreCounterBlue counter;
private float Score = 0;
//public Collider colliderZone;
// Start is called before the first frame update
void Start()
{
counter = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ScoreCounterBlue>();
}
// Update is called once per frame
void Update()
{
//counter.countScore(Score);
}
private void OnCollisionEnter(Collision Col)
{
if (Col.gameObject.layer == 3) {
Score++;
Debug.Log("BoxEntered");
counter.countScore(Score);
}
}
private void OnCollisionExit(Collision Col)
{
if (Col.gameObject.layer == 3)
{
Score--;
Debug.Log("BoxExited");
counter.countScore(Score);
}
}
}
2D or 3D game?
3
!code
also https://unity.huh.how/physics-messages
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
'3d
Does the other collider well have a collider?
I believe one of the Gameobjects should also have Rigidbody
well im trying to have a certain spot on the ground be the trigger so that has a collider ith the box set as a trigger
no rigidbody
but the gameobject im trying to detect has a rigidbody and a collider
click the link i sent
im not sure what type of collision i have
its a box collider in one object with a box collider set to trigger on another
ive tried detecting with layers with tags and with my objects name that im trying to detect
nothing works so far
have you gone through the link i shared that takes you through all of the troubleshooting steps you need to check? i'll give you a hint, it will show you what you've done wrong
i did and i got to the collision matrix chart but im a bit confused as to what im looking at
scroll down to see what each thing means
im still a bit confused
i tried checking the kinematic box on my gameobjects im trying to detect but that just freezes them in place unless im actively moving them
your issue isn't whether they are kinematic. you are using a trigger collider and expecting to get a collision message.
because you do. again, see the link i shared
alright
yes, because OnTriggerEnter takes a Collider not a Collision
ah i see
ez to miss since they look so simmilar 😄
sorry im pretty new to these things and its all the little stuff that i tend to miss
and OnCollisionEnter takes a Collision
yeah
its all working the way i want now
thank you simex and boxfriend, probably wouldve been banging my head against a wall for a few more hours without your guys help
I am having a bit of trouble compling for linux;
cannot execute binary file: Exec format error unity
I get that when I run the complied file. After some research I have seen it is because my unity project is suported for 64bit only, and my OS is 32bit. Is there a solution for this? I am using unity 2022.3.16f1
I don't think you can make 32-bit linux builds.
Hi, is anyone free to help me go through some issues im having. I am using the new input system and using the rebindUI sample from it but the keybinds aren't being preserved across scenes
damn i spent ages working on this
does anyone know how i can fix this or help debug it?
thanks anywayy
I would think #🖱️┃input-system is the place to be
Hello, i have ScriptableObject X. I used to Instantiate X for creating instance of class. Now i added List<ScriptableObject> Y to X. After that in editor, i add ScriptableObjects to Y.
So if i instantiate X, do i get instances of Y objects too? or Is there any way to get instances of Y?
No. The original object and the new object's lists will refer to the same objects.
You know, I'm not as confident as I thought I was 30 seconds ago. Let me go look.
Then I need to instantiate the objects in the list separately
What are you trying to accomplish here?
I have Gun SO and GunSkin SO, so list will be List<GunSkin>.
I need to add GunSkins to Gun
Also i am trying to get instances because i use SO as pre defined datas
So i can save and load easily
Long story short, i just need to get instances of every object in list.
okay, yes, it's as I expected
instantiating an object just copies over the references it has
that makes sense; otherwise instantiating an object would give it copies of things like materials
are you mutating these GunSkin objects?
Actually, i don't know really meaning of mutating but in GunSkin SO, i have fields like CurrentAmount, LevelOfSkin etc.
Yes.
I would suggest storing the data that changes somewhere else
GunSkin is a definition of a gun skin
something else should keep track of which gun skins you have
that completely avoids the issue
Okay, i will try to do that way. Thank you so much!
hello, i have a basic game on google play. For production release i need to complete closed test. For closed test i need 20 volunteers. Can anybody help me to download my game to their device?
This is a code channel, you may try your luck in #1180170818983051344, or on the Forums. In either case, read the posting rules as you'll need to include more information about your game than this
when im playing a timeline using PlayableDirection.Play() it seems like the music starts playing before the entire project gets compiled resulting in the timeline signals being off. Is this a problem that will be resolved if i just compile and build the game?
Whats the best (working) way to use google apis in unity. I looked at the .net client but it says unity isnt supported. for context I am trying to acsess google sheets api through http requests but oauth is needed and to my knowledge that requires google apis. let me know if this is inncorect
how do I define a generic with the constraint that < is defined?
Operators overloads are static, and interfaces forcing static members to be implemented is not supported by Unity
unfortunate
well, is there a catch-all for T being a numeric type?
like int, float, uint, long, etc... which would have those defined?
Not that I know of. Generic math and stuff like INumber<T> was added in .NET 7 or so
hmmm, maybe I'll try IComparable
Ah yeah there's that one, should work for most of these types
yeah. i just wanted to constrain more, so I don’t think in the future to put random Icomparables into this generic
future stupid proofing
Is there an easy way to draw a few lines between vertices without applying a bunch of LineRenderer components in the editor?
I have a few quads and I just want to be able to draw an "outline" between the four corners of each quad on demand
So to get the full performance out of Unity, i should learn/use DOTS and ECS? Or have they changed to some other paradigm already?
whats wrong with line renderer?
it’s a different workflow
If you want, you can use ECS, otherwise you use MonoBehaviours (and OOP).
Data Oriented Design like ECS is more performant in many cases yes
DOTS/ECS is more efficient because it is a different representation
Would I need 4 LineRenderers for each quad though, or can I draw 4 lines using just the one?
Ok, thank you both
ofc.. you only need 1
line renderer takes an array of points, you can make as many as you need
it’s like how you can represent everything with Matrices or gameobjects. Obviously matrices will make everything fast af, but that requires you to create matrix representations. Similar thing
i see. Ok, i will have to see if i can even comprehend the different way of thinking then
note that computational time you save may come at the cost of more time programming
you could code a game in assembly, and it would be fast as shit. but that involves coding in assembly
an important consideration as a single person 'team' :/ not counting my extended team (you's guys)
the whole point of unity is to use the engine to save time coding
ECS is worth it if you're building some large unit game like an RTS
I am working on a RPG, with a limited number of units on screen at the same time. Complex customizable character though, so i have to figure out how to handle the 650+ morph targets/baking
cool deal. so no benefit trying to'ECS' a bunch of trees or the like.. that is a different system entirely? (Just today starting to look at ECS)
it’s a very different way of programming a game
You would most likely see some benefits, but the drawbacks are going to make it not worth it for your game I believe. You can't use most components directly (like, notably, the animator) without creating a workaround or buying an asset
I am coming from the Unreal way of doing things, so a lot of this optimization was automatic there. completely different here
ECS excels at processing a huge number of separate things at once
Ah. Ok. That definitely tips the scales
imagine trying to process a simulation for a real gas, for example
where you have 10 million particles, all colliding with each other
you will not make it with 10 million dynamic rigid bodies
i see. that makes sense. So i should just depend on the Unity 'standard' way for the usual things like Instancing multiple trees/meshes and not even bother considering it for that then
that is how I would start
or start with godot if you know nothing about unity
godot is growing, while unity is shrinking
Nah, godot cannot even handle my Character due to the massive initial size because of the Shape Keys
Ya think? hmm. i was hoping Unity was about to do a big push forward
last year’s big announcement screwed up unity’s upward trajectory. lots of people jumping ship to godot
Familiarize yourself with basic building blocks of ECS: Burst compiler and Job system. Those can be used independently and can provide substantial benefits without switching to full DOTS
sounds good, thanks
that said, Godot isn’t fully ready, but being a part of the community as it grows will give you a big advantage if you stay with them
whereas Unity is very established
and most new features are experimental and half-baked
its making good progress but will actually catchup to unity any time soon. don't think so
coming from Unreal, i am used to half baked, and flat out broken in some cases😄
I hate that part of unity
puts an amazing feature and then just kinda abandons it
it will take time for godot to catch up. but they will steadily grow
and being open source will lead to far fewer “sealed class fuck you lmao” moments
indeed
and no “i have no idea what this does because this code injects proprietary C++ code” moments
the terrain tools looks better than the unity one somehow 😮
unity terrain tools haven't been updated since 2012
unity terrain tools are ass
exactly
what has driven me nuts is the whole physics2D being injected
That does bother me, but after working with Unreal for years, i realized that while it can do 'everything', the amount of time it takes to do basic things is not feasible for an individual. On the other side, Unity seems to have a faster development cycle for individuals. and Godot, while deserving of a big thumbs up, is just not technologically on par, yet
with that being said, terrain editor is still pretty good at optimization and culling
want to see what effectors do? gfy
want to know how joints work? gfy
want to modify physics simulation? gfy
want to actually make custom parametrized colliders? gfy, and CustomCollider2D wasn’t even properly tested lol
Things will change a lot in the coming years; it's been a while coming. When they transition to modern .NET it will take huge leaps
Awesome! looking forward to it
i’m still holding my breath for full C# v9 support
yeah… given godot is building their C# compatibility now, I expect the first version they support to be C#13+
anyway, point being, it’s worth checking out godot as it grows if you have no experience with unity
think of how many lines of code ill be saving with struct initializers
and records
primary constructors, namespaces without scopes
regex and json source generation
nuget...
raw string literals 🤤
string interpolation that doesn't allocate at the point it's declared
a non-shit GC
doesnt box2D have documentation or you mean specifically unity components and how they're implemeneted
unity interfaces into box2D. You can see how box2D works. You can see how unity works within C#. But you can’t see the critical junction in C++ where unity actually works with box2D
ah yeah 😢
as in, the actually important part is invisible and non-editable
which is part of why i built my own physics engine from scratch
i needed to modify some critical things where Unity did not allow me
hey there, i am having a weird issue that i hope someone here has been through before. for some reason just moving the unity scene is causing my high end computer to reach 95 cpu and high gpu usage and as soon as i stop everything comes back to normal. is there a setting that i need to turn on or off that i should know about?
Profile it and see what is happening
how do i profile the scene? i though i could only profile the game running
I have a Light 2D component on a tiled sprite and I'm wondering how I can find the corners of said sprite to align the light's shape to so I don't have to manually resize it
nvm found it
i don't think sprites really have corners, unless you read the pixels in it
and then actually search for specific patterns etc
well I do have a collider on it
then use the collider shape
call GetShapes on the collider, and sift through the shapes.
alright
also, graphics and hitboxes don't mix well
I tried using a polygon collider's path but that didn't work out lol
it's lava
is it a big complex shape?
bruh, just calculate it
welp windows shift s isnt working
but is turns out that the main thing that has spiked
Open snip and sketch once
Should work after that
i did that that didnt help but that should be a big problem just a restart from my computer, but the main thing that spiked in the unity editor is just application.idle
what does that mean?
ama restart until i get a response ill be back shortly
im back
damn, after i restarted the performance only is affecting the gpu now the cpu only increases by like 5%
does someone know how I would fix this. I dont want the player to be able to float like this on the edge but If I shrink the width of the collider it will be smaller then the body.
this is a tricky problem to solve
a raycast can help you check if you're not grounded then push the player slightly off
Ok Il try that thank you
Maybe use a capsule collider instead?
Then you'd naturally slide off if the center is out the edge.
It's too much code, but I changed it and put the management of the values in a component in the gamemanager. It seems that ScriptableObjects are "baked" in the build so the values are not really editable on runtime, it's just confusing the Editor has a completely different behaviour.
They are editable as any other object. They just don't save between the sessions like they do in the editor.
That's why if you save them to a file as json to load later it should be working.
If it doesn't there's something wrong with your code, which is why I mentioned that we need more details.
I did that, and I debugged the messages, the values were saving and loading correctly in the json. The code worked in the Editor but not in the Build. I am using 2022.1.18f1
But I like what I did now, so I think I am just gonna refrain from saving data to ScriptableObjects
Hey there, so I've been making a game with powerups, and for each 'powerup state' I've made a scriptable object. In it, I have a 'HandleMovement' method, where the necessary stuff is done to make him move. This method is then called in FixedUpdate in my PlayerController script. Sadly, the velocity value doesnt add up like it should, so my player just stands still and cant move around. When I set the HandleMovement method directly (without using SO's) in the PlayerController script, it does work. Through the Scriptable object though, it doesnt.
Below you can find the (simplified) HandleMovement method, and the place where it's called in my PlayerController script. Could anyone help me with this, or explain why it doesn't work?
HandleMovement():
velocity.x += inputDir * physicsConstants.walkAccel;
PlayerController, FixedUpdate();
playerPowerupStateController.GetActivePlayerPowerupState().HandleMovement(controller, directionalInput, velocity, this, isDucking, isSkidding, isRunning);
controller.Move(velocity * Time.fixedDeltaTime);
how does your SO encode the information for which function to use
Sorry I dont understand I think, what do you mean?
if I understand, you have one SO for normal mario, and one SO for frog mario which would have different controls in water, or something like that
Yeah
and each SO is a different asset of the same type?
No, so let's say we have FrogMario, he would have a different script which derives from a general PowerUpState SO, which can then override the HandleMovement() method so it fits the frog behaviour
ok, so this sounds like a case to use an interface or abstract class, potentially
eg IPlayerMovement
then your powerup SO (eg an SO with info about a mushroom, with sprite and state etc) can take a TypeReference to a type that implements IPlayerMovement
class typereferences in a plugin that lets you serialize a reference to a specific type, btw
then I would define methods:
public interface IPlayerMovement {
public bool AllowJump {get;}
public void HandleJump();
public void HandleMove();
}
etc.
it’s what you’re doing now, but with an interface (or abstract class) instead of SOs
Hmm I see yeah, I might have to try it. And is there any reason why the HandleMovement() method doesnt work through the SO? While it does work if I place it directly into my PlayerController script?
you could probably use SOs, but it is a weird use case because you might want to instance to hold variables in future, and SOs are weirdly persistent
like if my SO has bool isGrounded, which it uses to figure out what to do in HandleMovement(), you’re going to see some weird stuff happening with respect to starting with old values
which you can totally overcome, but is an additional pain point which is avoided with non-SO solutions
if I had to guess, you are storing fields in your SO which are used for calculation?
or a reference to the rigidbody, or other things which only exist in the scene?
Alright thx! My SO has data for the Animator it has to play, base -and crouchsize, ... so i can set it whenever a new powerup is picked up. It doesnt store the rigidbody though or speedvalues, those are stored in a seperate class PhysicsConstants
I see. Also, I believe what you are doing is called the Strategy Pattern. That might help you find resources on different ways to implement it.
Alright that could be helpful thx
good luck
Thanks!
btw: https://openupm.com/packages/com.solidalloy.type-references/?subPage=readme
This plugin is very useful if you need to serialize a reference to a class.
in your case, it would be something like:
public class FrogMovement : PlayerMovementStrategy {…}
public class Powerup : ScriptableObject {
[field: TypeExtends(typeof(PlayerMovementStrategy)), SerializeField] public TypeReference playerMovementType;
// Animator settings…
}```
this defines the powerup’s SO as having whatever settings are completely immutable and locked in. Then TypeReference lets you instantiate whatever powerup movement behaviour you need based on the SO. Since the PlayerMovementStrategy isn’t an SO, you can create, nuke, reset etc it at will, without worrying about old values.
Hey guys
I have a problem
Where my damage prefab is not showing at the objcet being damaged
Here is how i instantiate:
Thanks a lot!
The prefab is not spawning at the damaged object
I don't even use localPosition
What's the error here
where is it spawning
I'll show you a screen recording
Cause it's kinda hard lol to just show it
Navarone
It's a little laggy, I apologise
But here you go
all good
so its not appearing at all ?
No
It is
Let me tell you the timestamp sorry
At around 0:18
It's the yellow "1"
oh ok and which object has the script you posted
and the prefab for text
also maybe try transform.localPosition for Instantiate param
Im thinking it might be spawning behind the sprite as well , so maybe an offset would help. along with rotation
ie make the rotation look at camera
oh?
hang on
Popup text
im thinking rotation / position
hmm first add localPosition and add offset, because position spawns it at center of npc since thats where ur pivot is
rotation wise you could do LookRotation from camera
why local position?
wont that mess it up
when you have a child object, localPosition will give you the position relative to parent
exactly
let's see
the term for this is sprite billboarding right?
or is it different
yeah sort of
alright
you could also put Debug.Break after Instantiate, and it will pause the simulation so you can see where its spawning exactly
yeah navarone
it's not working
because i dont move the sprite
i move the parent
which means localPosition can't change
it'll stay in the same place
let me make it debug.log transform.rotation
try this one first
#archived-code-general message
alright
you will see it inside the hierarchy and press F to focus on it
this one doesnt help much, show the one in the scene while game is paused
like where is it inside the scene view
this is the butter parent
sure
OH
Do you reckon its the width of the text box?!
Oops
💀
It is
lol
you're welcome! glad its sorted
:)
lol 1 more thing @rigid island concerning this game if you could help
i might as well as right now
sure
when my player rigidbody hits one of the butter guys, he goes flying
same with when i make the terrain a little bit elevated
increasing mass doesn't just help
because theni n eed to increasethe speed a ton
are you using physics to move?
anyone know how i can get the rotation to look more natural and less forced?
code:
rayHit.rigidbody.AddForceAtPosition(direction * 10, rayHit.point, ForceMode.Impulse);
rayHit.rigidbody.AddTorque(Vector3.Cross(Vector3.up, direction) * 10, ForceMode.Impulse);
you could potentially Lock all constraints on rigidbody
also inputs should be grabbed in Update. rigidbody in FixedUpdate
yeah
anything you dont want moved by other colliders
oh
since you're moving it with code constraints will have no effect on your code but help lock in rigidbody
i didn't know that
oops
it's not letting me move
💀
but then how do i make him jump in the future
maybe just use a character controller so your player dont go flying on collisions?
sure
change rb.velocity to character Controller.Move(moveDir * Time.deltaTime * speed)
Aight
Thanks man!
If I have any more problems I'll write them down here
But you helped a lot
🫡
good luck!
hi is there someone here who would like to help me on the Generics or do i need to go in the beginner channel ?
You mean generics the code term with a specific meaning? Or generic like the english word?
no generic like the code term
Ok, then just ask.
might be abit long i will write it in a txt and write here in one blow (sorry again 😭 i'm new)
So I'm trying to implement a A* pathfinding algorithm.
I have created a grid class where i can put a generics in the constructor to put a custom type for example a PathNode class that i made.
So when i try to create my object in my script here is my A* script,my grid script and my nodes script
public class Astar
{
private Grid<Node> grid;
public Astar(int width, int height)
{
grid = new Grid<Node>(width, height, 5f, Vector3.zero, (Grid<Node> g, int x, int y) => new Node(g, x, y));
}
public class Node
{
private float Gcost,Hcost,Fcost;
private int x, y;
private Grid<Node> grid;
public Node LastNode;
public Node(Grid<Node> grid, int x, int y)
{
this.grid = grid;
this.x = x;
this.y = y;
}
public Grid(int width, int height,float nodeRadius, Vector3 Origin, Func<TGridObject> creategridobject)
{
this.width = width;
this.height = height;
this.nodeRadius = nodeRadius;
gridArray = new TGridObject[width, height];
debugTexture = new TextMesh[width, height];
//Debug.Log(width+"/"+height);
for (int x = 0; x < gridArray.GetLength(0); x++)
{
for (int y = 0; y < gridArray.GetLength(1); y++)
{
gridArray[x, y] = creategridobject();
}
}}
i get an error, that say incompatible anonymous function signature (i'm on RiderIDE )
i don't really understand what is an anonymous function beside my research
An anonymous function is a function that has no name.
You declare an anonymous function by using the => operator
The only anonymous function I see in your code is this
(Grid<Node> g, int x, int y) => new Node(g, x, y)
This is a three-argument function.
Grid's constructor takes a Func<TGridObject> as the last parameter.
That's the type for a function that takes 0 arguments and returns a TGridObject
These are incompatible.
oh okay so if i make a function that create 1 node with 3 args it won't work then but it will not be anonymous at least ?
I think you need to rewrite the Grid constructor.
It sounds to me like you want to be able to pass the x/y coordinates to the "create grid object" method
as well as the grid itself
But Func<TGridObject> doesn't allow for any arguments.
What does allow for arguments is Func<Grid<TGridObject>, int, int, TGridObject>
This is a three-argument function that returns a TGridObject
If you switched the constructor to take that, and then passed those arguments on this line...
gridArray[x, y] = creategridobject();
...it would work
okay i need to work back on my grid then thank you 👍
back to work
So my terrain is made of closed spirte shapes. Using that with Unity's 2d lighting system though causes the shadows to cast incorrectly around a rectangle outlining the terrain shape. Is there anyway I can fix the shadows without manually setting each point of the shape of the shadow myself? Or, an alternative to using sprite shapes for my terrain in general that still gives me the freedom to create levels not on a grid
You could probably make your own script to set the shadow points to the vertices of the sprite shape in edit mode, probably via some button in the inspector or something.
I believe that all the necessary API exists to do so
Hey, I tried this out but get an error when using the 'TypeExtends' as it says it doesnt exist. Any idea what I did wrong here?
I changed it to 'Inherits', but afterwards when I try to call the methods from the PlayerMovementStrategy class, it can't find the method due to this error:
Any idea how to fix this? 🙂
Doesn't this thing serialize types, not instances of types?
Not sure I'm not too familiar with it yet
void Awake() {
Collider[] colliders = GetComponentsInChildren<Collider>();
foreach(Collider c in colliders) {
if (c.gameObject != this.gameObject) {
ragdoll_colliders.Add(c);
}
}
Rigidbody[] rigid_bodies = GetComponentsInChildren<Rigidbody>();
foreach(Rigidbody r in rigid_bodies) {
if (r.gameObject != this.gameObject) {
ragdoll_bodies.Add(r);
}
}
foreach(Collider c in ragdoll_colliders) {
c.isTrigger = true;
}
foreach(Rigidbody r in ragdoll_bodies) {
r.isKinematic = true;
}
}
void turn_ragdoll_on() {
if (cached_animator != null) {
cached_animator.enabled = false;
}
if (cached_third_person_controller != null) {
cached_third_person_controller.enabled = false;
}
if (cached_character_controller != null) {
cached_character_controller.enabled = false;
}
foreach(Collider c in ragdoll_colliders) {
c.isTrigger = false;
}
foreach(Rigidbody r in ragdoll_bodies) {
r.isKinematic = false;
}
in_ragdoll = true;
}
void turn_ragdoll_off() {
foreach(Rigidbody r in ragdoll_bodies) {
r.isKinematic = true;
}
foreach(Collider c in ragdoll_colliders) {
c.isTrigger = true;
}
if (cached_character_controller != null) {
cached_character_controller.enabled = true;
}
if (cached_third_person_controller != null) {
cached_third_person_controller.enabled = true;
}
if (cached_animator != null) {
cached_animator.enabled = true;
}
in_ragdoll = false;
}
i think i got my ragdoll to work o.o
How do I make numbers line up in my leaderboards?
It took me a bit of reading to see this isn't a bug, but rather my score simply just has less numbers that require a lot of space
CombatActions = CombatActions.OrderByDescending(i => i.Move.MoveSO.Priority).ThenBy(i => i.Character.Attributes.Speed).ToList();
Doess the .ThenBy sort in descending order or ascending in the above example?
considering there is a separate ThenByDescending, i'd assume it sorts in ascending order
makes sense
Yeah it sorts in ascending order on default
Ah there is ThenByDescending 😄
Error:
NullReferenceException: Object reference not set to an instance of an object
When debugging the above line everything seems fine, until `.ToList) I think
So I am getting Speed of character
This line:
CombatActions = CombatActions.OrderByDescending(i => i.Move.MoveSO.Priority).ThenByDescending(i => i.Character.Attributes.Speed).ToList();
dont use (one line) lambda expression and debug inside?
How can I change this to multi line?
The idea is to sort moves by their priority, but if the priority is same then by character speed
()=>{statements; return value;}
i.e. Move priority -1 and -1 would be sorted by character.speed
btw you can have a custom comparator then just inplace sort
I dont know how to make it work with what I need other than making a list for each priority then combine those sorted lists.
FireBall: Priority 1, CharacterSpeed: 10
IceBall: Priority 1, CharacterSpeed: 5
MetalBall: Priority 2, CharacterSpeed: 1
Priority: MetalBall, FireBall, IceBall
just gotta code your whole project on one lambda line
i know, Icomparator can sort the list in any order you like, since you have full control on the return value
public int cmp(type a,type b){
if(a.priority==b.priority){
return a.speed-b.speed;
}
return a.priority-b.priority;
}
Found the error with my code, for w/e reason it was setting Character to null.
If the previous solution works then I'd keep it
For some reason, my sprite is not showing on the screen in unity 2d. Any ideas?
im talking about "player"
Not a code issue. It's too close to the camera.
Put your camera at -10 on the z axis and everything else at or above 0
all axis?
Oh actually it's not too close to the camera, it's nowhere near it
It looks like it's on your canvas for whatever reason
Why do you have non UI objects as children of the canvas?
Did you also move it to where the camera is actually at?
Yes. Notice how you've made the player's scale 50x50. It's huge
Your ground shouldn't be on the canvas either and if you go trying to use UI objects for this you're gonna have a bad time
alright
public int Defense
{
get { return (int)(((float)CharacterSO.BaseDefense + (float)_Defense) * (Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f)); }
internal set { _Defense = value; }
}
Looking for recommendations.
Should I store defense/base defense as floats to make the above cleaner or is there a better way?