#archived-code-general
1 messages ยท Page 402 of 1
uhh how are you setting the velocity then
you can't set velocity on a kinematic rigidbody
Probably not a rigidbody velocity...
You absolutely can!
well
Aside fron setting _jump through an event rather than inside Update(), this is exactly how I'd do stuff
Not by changing linear velocity, I use the rigidbody's MovePosition function
I see, thanks!
Maybe I'll just have to deal with that
You could probably figure out a wrapper that fires an event on the next fixedupdate after the respective inputsystem event got recieved
Which means you wouldn't need _jump at all
But that might be too much work
is this not working?
It is
then why mess with it?
ya for code thats scattered around
i making a system for hiding behind props and the code works but when i leave the prop midair it stays there as it has no rb. but if i use rb on the prop when entering it i fall through the floor. https://paste.ofcode.org/kDxyeqkMwJce9WuwTMHHwd <-my code
How do I see the sample rate option in Unity 6 ?
context?
doesn't sound like a code question
he is talking about audio sampling i pressume but still needs more context
anyone?
ig you could try disabling rigidbody once it reaches the ground
you would think that but i realized the the rb on the player is using the collider on the prop as its collider so even having a static rb on the prop would break the connection between the prop and player stop resulting in it falling into the ground
no i mean like totally get rid of the rb after ur done with it
like how there is no rb.enabled or disabled feature
rb.enabled=false;
im pretty sure thats not a thing
it's for components behaviors in general, but enabled doesn't nuke the script, it just makes the script not receive certain messages
okay so u can just get a reference of the rigidbody and destroy it once ur done
Rigidbody and Rigidbody2D inherit directly from Component so they do not have an enabled property. That is a property on Behaviour
ya but we can remove the component itself right
Sure, but I was not responding to any of that.
ya i am just making sure
i want to be able to hide in the same object after leaving in it
ya thats fine once the object is on ground u dont need it to have any rigidbody only colliders
yes but when i hide it in again and then leave the rb is already destroyed so the problem returns
like how do u mean?
my fault i dont think i explained this well enough
when ur props are on ground they dont have rb to begin with right?
so do you know in cartoons like when sneaking around a person will hide behind a tree and waddle to move and stop in their place to avoid detedtion from the gaurd or whatever. im trying to remake that but the issue is when i stop hiding in the prop it remains at the position where it was left not a problem if i was on the ground but i was in the air the prop just remains the floating
do you get what i mean
so u want the floating prop to fall after u leave it?
exactly
same thing give air check and isIn check if (!isIn && inAir) then add rigidbody till it falls to ground then remove rb
but if i hide in the same object again and if i do the same thing again i will need the rigidbody i had just deleted to make it fall again
ya u need to look up how to add a remove components from script
u can make it so that whenever ur in it it doesnt have a rb but when u exit it gets back its rb
is there a difference between Camera.WorldToScreenPoint and RectTransformUtility.WorldToScreenPoint?
Yes of course
documentation doesn't give me a clue. What is it?
one is based on a camera, one is based on a RectTransform
uh, but the RectTransformUtility takes in a camera as well...?
It's optional, and it only makes sense for screen space - camera or world space canvases
does it give the pixel data in the reference resolution...?
from the canvas
not sure
or what could it be
Praetor could you help me with my problem im lost
if you're not sure, then I still don't understand what the real difference is. How is one local to screen space different from another local to screen space?
imagine an overlay canvas
there is no camera involved in that at all
is that the only thing? it just doesn't need a camera and uses the canvas instead?
pls help, my pf is overreacting:
I'm not sure the specific details buit that's a pretty significant difference in functionality. You should experiment and see.
so, i tried to put heaps into it
and for some reasons it doesn't calculate my costs right
Please be specific about your problem and explain what you are doing, what's going wrong, and share your code. We're not mind readers.
What even is "pf"
im one sentence per message writer hon
I assume "pathfinding"? But yeah it would be nice if you were clear.
wait a sec
well please don't be here
could anyone help with this i still dont have a answer?
public int CompareTo(Node other)
{
int compare = fCost.CompareTo(other.fCost);
if (compare == 0)
{
compare = hCost.CompareTo(other.hCost);
}
return -compare;
}
heres the full explanation of the required systems
it doesn't compare right
couldn't figure out why it sets the priorities so weirdly
as you have seen the pic
We don't even know which algorithm you're using.
i told you before but the server wouldn't let me send the message
so im gonna be more formal
i am using Astar
a* pathfiding?
yes
They're using the A* algorithm, not the "A* Pathfinding" asset store asset, presumably.
algorithm, algorithm, im not usin any assets
Just add a rigidbody to the prop and let it fall down with gravity?
You can lock its rotations
And you can remove the rigidbody once it hits the ground if you want
Or make it kinematic
if i do that. when i actually try to hide in the prop i fall through the world
becuase of this
You can ignore collisions between the player and the prop
And you dont need to make the prop a child of the player, you can just move it manually
already do, results in the same as if it was the child
Show a video of the issue?
What makes you fall through the world here? I dont get it
Show what you tried also
ill explain then ill send the video
presumably the teleportation of the object into a degenerate position like inside some other collider(s)
gameObject.transform.position = ... is definitely problematic, yes
so im disabling the players colliders , so the active rb uses the collider of the prop which is a child of the player . this is great but if i make the prop have a rigidbody the player rb now isnt using the box collider so it falls trough into the ground and since the box collider is a child it falls with it
dont disable player colliders to begin with
disable the prop's colliders
instead
then i cant walk by enemies which is the entire point of the system
Which is why I suggested this ^
just give them a layer mask
props and enemies dont collide already
i want player to collide with the enemy when its not hiding
This can be used to ignore collisions between two specific colliders
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.IgnoreCollision.html
ya just ignore collision with enemy layer while inside prop
thats the point of the layer
With prop layer* or prop collider.
i was using layer collsion matrix but ill try this out
i believe its physics2d.detectCollisions=false; for 2d stuff
Use the 2D version if your game is 2D
You don't want to disable all collisions.
yes
right better to use ignore collions with layermask
Also FYI, there is a separate collision matrix for 2D and 3D
yep
also how do i make it not ignore collsions again
I'm overriding ScrollRect. How do I get my variables to show up in the inspector? Bonus points if I don't have to make a custom inspector ๐ญ
my AnchorPoint doesn't appear in the editor, it's only the ScrollRect stuff
Oops, misread
ScrollRect likely has a custom inspector so you'll need to write your own for SnapScrollRect
but writing custom inspectors is a lot of wooork, I hate doing it... is there really no other way? I wanted to use the EditorAttributes package too, and I'm not sure if it works through a custom inspector anyway
there's always debug mode in the inspector which shouldn't use the ScrollRect's custom inspector, but that comes with its own drawbacks
the drawbacks being that I can't use EditorAttributes, which is also a big issue for me :/
custom inspector it is, ugh
does that need to inherit from ScrollRect? if not, then you can just make it a separate component that controls stuff on th ScrollRect. then you wouldn't need a custom inspector for it
I'm currently having an issue with this SimpleRotator script in JetBrains, as the software won't autofill the coding prompts, any advice?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
great, so that's one step
Is there something going on with the package handler maybe?
I mean I guess it doesn't NEED to inherit from scrollrect. I'd just have to copy and paste the entire ScrollRect code afterwards
why
have you tried completing all of the steps for configuring it?
Yup! I did that about a few-monthgs ago.
because it's directly manipulating the ScrollRect behaviour, I'm making a ScrollRect that snaps to indifidual elements inside it
Literally just yesterday, JetBrains IDE was autompleting all of the code I was inputting.
so then yes, if you need to call protected methods on the ScrollRect class it would need to inherit from it.
okay and have you tried completing those steps today now that you are having issues?
...unironically try rebooting your PC, sometimes stuff like that just happens
that's literally step 4 in the guide that was linked
Lol, literally as I was updating the JetBrains Unity plugin. My project crashes. Is tha supposed to happen?
@obsidian anchor ^^
Unity's Input System and detecting when the button is no longer pressed.
Thanks for the help btw
Has anyone made a card/effect stacking game before? Im trying to find a practical example online I can use to guide my sorta design philosophy in making this project.
Essentially I am making a game about comboing effects from a large list of possible effects. And managing interactions between those has been sort of hectic. Same design problem games like the binding of isaac and whatnot likely face. Like ill have an effect that generates 10 projectiles. But then if those projectiles gain an onhit effect, or a traveltime effect. Id then have to manage that interaction somewhere. Currently I just have a long list of super abritrary stats that I modify, but I doubt this is sorta the philosphy that other designs would use as its unruly with just 15 abritrary stats I can read.
So yeah, rambly message aside, does anyone have a good open source practical example of a game that handles stacking multiple effects and handing interaction between a large set of these effects. IE like the binding of isaac, or really any card game as well. Even games like vampire survivors likely manage a similar problem at a smaller scale. Im hoping the standard solution isnt just going in and hardcoding things that dont stack quite well. As that would feel awful lol
I play so many games that do these things that Im hoping theres a solid like, design principle out there
theres no way TBOI is spaghetti code
spaghetti code is more common than you might think (:
How might I recursively iterate through a chain of game objects in a specific direction?
I'm trying to create gears which turn each other, however this requires me to have a drive gear and a driven gear. My current method of checking what gears are touching each other is using Physics.OverlapSphere. Currently I go through a for loop of all adjacent gears and set the colliding gears to the drive's inverse, although my issue is defining which one is the drive.
I have a stupid little fix which makes it work for two gears only, which is having a bool called driver, however this wont work for a chain of gears.
here's my update method if anyone else can give me any ideas on how I can fix my issues.
void Update()
{
transform.Rotate(rotation * Time.deltaTime * force);
Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius);
foreach (var hitCollider in hitColliders)
{
if (hitCollider.GetComponent<CapsuleCollider>() != GetComponent<CapsuleCollider>()) // Doesnt collide with itself
if (hitCollider.GetComponent<Gear>()) // If the part is a gear
{
Debug.Log("Colliding with a gear");
Gear drivenGear = hitCollider.GetComponent<Gear>();
if(driver) drivenGear.calculateRotation(force);
}
}
}
Assuming you just don't want to proliferate the values, you're probably looking for the tail of the gears that's dictating the direction of all gears if I'm understanding this correctly.
Unless you don't have like a list that's predefined of all the gears, you're probably populating all the gears to some manager and resolving it all from there.
so it's a question of resolving sets with other sets of gears
My current method of checking what gears are touching each other is using Physics.OverlapSphere
Physics is probably not the way to go here. Is your game grid-based?
The gears rotation direction and speed is just going to be the inverse of what's controlling it. I was hoping that I could have one gear which is manually given a force, which then passes that force on to the neighboring gears and recursively down the chain.
No my game is not grid based
When you place gears you should do something like find the nearby or touching ones and have each gear store which other gears it's touching
then you end up with a graph structure
and you can do all the normal graph algorithms like DFS to find the connected ones
sounds like a fun problem
I'm still kind of confused. I should have a manager which this is all put into which will then run it through a graph algorithm? I'm going to assume the DFS can handle my issue of the driven gear controlling the driver? I haven't worked with graph algorithms much, but I'll definetly look into it
I should probably research graph theory a bit more lol
I'd probably make the gear object contain a list of other gears it's connected to in the moving direction
Rather, other gears that this gear is applying the force to
yeah thats what I currently have I believe?
Probably fine honestly if you don't care about keeping track of the set
im thinking i can just call the method of the next gear with the driver as an input, then the method controls the connected gears and so on, ignoring the driver. Do you think that would work?
I know I should probably do the graph way, Its just kind of confusing me
Doing it recursively is fine, as long as no two gears can act upon the same gear. My only concern is the amount of physic queries you're doing if you do have multiple gears.
Maybe better off using Trigger events over querying every frame
Alright
they also offer events for when they stop intersecting so that would be helpful
okay
Would anyone know why line 55 is unreachable code?
https://paste.ofcode.org/f4i4QpYivzNXg9qzL2gJVJ
Do you have an extra bracket there
I do not
If line 51 is entering, I don't see why 55 wouldnt
But you've not shown the source for LocalTeam
yep will do that now
Better indented FOVandHearingsystem
https://paste.ofcode.org/kr4PBA4GnjzsdxiBgVUrLY
So you're just comparing if 0 == 1 in that if statement
What's the point of it
What's the point of either of those if statements
ah yup sorry, that fixed it
oh yeah you're casting the enums
ah yeah I could use a switch statement, give me a second
I am trying to add controller support for my game, and also allow it to be played on the Steamdeck. Not only would I need to allow the controller joysticks and buttons to work for my player movement, aiming, shooting, but even for the GUI navigation in main menu, character selection, using dropdowns for display resolution, checkboxes etc.
Would you use using the new input system is easy to do this? Or you recommend something like Rewired?
yes, the input system is designed to be fairly easy to implement support for different input types. check the documentation pinned in #๐ฑ๏ธโinput-system to learn how to use it
Thank you. Will do. I am reading both ways on how certain things are way complicated to do using the Unity input or Rewired. I am hoping I don't spend weeks integrating to find out something is way more complex than I can handle
Composition.
//Simple
public class Projectile : MonoBehaviour
{
private List<Effect> effects;
...
public void Initialize(IEnumerable<Effect> effects)
{
this.effects = effects.ToList();
}
public void OnHit()
{
//Invoke OnHitEffect
}
}
public abstract class Effect {}
public class OnHitEffect : Effect {}
//MoreComplex
public class Projectile : MonoBehaviour
{
[SerializeReference] private List<ProjectileBehaviour> behaviours;
private List<Effect> effects;
...
public void Initialize(IEnumerable<Effect> effects)
{
this.effects = effects.ToList();
}
private void Update()
{
foreach(ProjectileBehaviour behaviour in behaviours)
behaviour.Update();
}
}
[Serializable]
public abstract class ProjectileBehaviour {}
[Serializable]
public class ImpactProjectileBehaviour
{
public virtual void Update()
{
//Impact Logic.
//Access projectile effects
}
}
Hey I need help i cant figure out how to build a navmesh at runtime
I have the latest navigation ai package (1.1.5) yet i dont have an assembly reference to NavMeshSurface ?
I watched multiple videos but they were all outdated
I am on unity 2022.3.16f1
Even with the navmeshcomponents package on github it doesnt work
Like I cant put a navmeshsurface as a navmeshsurface variable
Hello everyone! How can I get ALL the tiles in a tilemap? I've been trying to add some overlay tiles in random spots taken from the floor tiles but I'm having some difficulties
{
return list.OrderBy(x => Random.value).Take(count).ToList();
}
[Button]
public void Run(){
cells = new List<Vector3Int>();
//floorTiles.CompressBounds();
BoundsInt bounds = floorTiles.cellBounds;
TileBase[] allTiles = floorTiles.GetTilesBlock(bounds);
for (int x = bounds.min.x; x < bounds.max.x; x++)
{
for (int y = bounds.min.y; y < bounds.max.y; y++){
TileBase tile = allTiles[x + y * bounds.size.x];
if (tile != null) {
cells.Add(new Vector3Int(x, y, 0));
Debug.Log("x:" + x + " y:" + y);
}
}
}
int randa = Random.Range(3,10);
randCells = GetRandomItems(cells, randa);
foreach (Vector3Int t in randCells){
overlayTiles.SetTile(t, chest);
}
}```
That's the code I came up with, but it gives me an error about index is outside the bounds
how important is putting the private namespace?
private is an access modifier, not a namespace
In C# things are private by default so it's just a style choice
oh I kinda don't really know what all the terms like namespace actually mean
It seemed like it kinda made sense
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/namespace
the array you get is going to be 0-indexed (like all arrays). It's not going to start at e.g. bounds.min.y
This is broadly speaking the approach I am taking now.
I mean more ensuring effects work together as intended. Layering effects that likely impact eachother is the larger issue at hand. Making a bolt explode and also do other things isnt as huge of a task as those are independent effects.
Can you "overuse" monobehaviors for UI elements?
whats the alternative?
lose a bit of seperation and have the parent class (monobehavior) make calls into the class constantly.
I guess in this sense it's not a UI element, more of a runtime editor
The class is for showing and validating placement of blocks
Using Binding of Isaac as a reference, there is some layering on some of the abilities such that some do completely modify your attacks completely. Ideally you group your effects, and perhaps some exclusion groups that prevent interacting with each other.
And, probably a pipeline for these groups for which should come first if needed.
so the question is rather whether you can "split things up into too many classes/components", answer is: definitely. Typically, when you are clear about the problem you want to solve, it doesn't happen since the criteria for cohesion and separation are obvious. If you separate too much, its indicative of unclear goals.
I'm just trying to have clear seperation of my classes, but dependencies are making that difficult.
what does separation mean to you? and why do you want it?
Well I had a class that did many different things, and it became unmanageable. So I'm seperating it out based on the states of my state machine so it's clearer what they do.
the code will likely be just as unmanageable (maybe more so) if you just spread it out, thats not getting fixed by making more classes. Its a structural/modelling issue in most cases.
what would improve maintenance is potentially abstraction, followed by separation.
but since you're dealing with a state machine complexity issue, for that to be successfull you would have to primarily separate transition rules from state implementation.
I think I hvae that, I'm just trying to keep it lol
I mapped it out
Before I started making changes the state machine just called into an assembler class which everything under this was a apart of (except the gizmo subclasses)
I could still put another class inbetween the state machine and the other classes that holds the selected object and the grid and pass them through on method calls for normal classes and events for monobehaviors?
@cold parrot ?
ahh bummer, well if I continue to stare at it long enough I might come to a solution.
what's going on here? I don't remember making this script
It's the event system trying to read the mouse position.
Oops sorry about caps lock
that scared me for a bit lol
Anyway - like it says - you are using the StandaloneInputModule still
you need to upgrade it to the input system input module
Select your event system object and click the button on the input module to switch it.
Oh I didn't realize the new event systems would be different than my other one
hi, how should i properly take an object from an array and use it as a target for a navmesh agent? i have a script to detect targets in front of the agent and add them to an array as visible targets. my enemyAI script takes that array and turns it into the target for the navmesh agent. it works like it's supposed to but whenever the player leaves the agent's field of view it starts throwing up index errors. i followed a tutorial from sebastian lague for the vision cone. i added the hasTarget bools trying to find a workaround to the errors but they haven't worked. the specific error says ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
This error itself is fairly straightforward. You're trying to access an element that doesn't exist in the array. For example the array has a length of 4 and you're trying to access element 7.
As for where the actual error is happening you would need to check the line number and filename from the error
every exception will have a line number and a filename
you need to look there
-
target = fov.visibleTargets[0];
it's this one specifically. (and the ChasePlayer() function in Update) the player gameobject is the only thing in the array when so when it leaves vision the array becomes empty.
ok it's pretty clear then that the visibleTargets list has a length/count of 0
you cannot access index 0 (the first element) of an array or list with 0 elements in it
Sounds to me like hasTarget should not be a separate variable at all. It should just be a property that checks if there are any items in the visibleTargets list. For example:
public bool hasTarget => visibleTargets.Count > 0;```
it shouldn't be a separate variable that you set (incorrectly in this case)
okay let me tinker with that and i see if i can get it working, thank you!
do you at least understand why you have an error there?
it seems like hasTarget has been set to true improperly, since there are no visible targets
yeah, that much i had understood. i just couldn't figure out how to get around it
and you are trying to read element 0 from the list, which has no elements.
btw this is a List, not an array
it works now, thank you!
ah right ๐ i just finished up a udemy course and this is my first coding experience so not everything is really there yet
Yo I've been having some trouble, I have an prefab which is an empty object with a few scripts in it and then a 2D sprite as a child. I have a manager that is supposed to spawn in this prefab and set its parent to a specific canvas so it is visible to the players, its currently not working as it copies the prefab but has the parent of it null, making it clone outside of the canvas, does anyone know how to help? Here's the script ```using UnityEngine;
using System.Collections.Generic;
public class MilitaryManager : MonoBehaviour
{
public GameObject militaryPrefab;
public Transform stagingArea;
public List<GameObject> ownedUnits = new List<GameObject>();
public Canvas canvas;
public void PurchaseUnit()
{
GameObject newUnit = Instantiate(militaryPrefab, stagingArea.position, Quaternion.identity);
newUnit.transform.SetParent(canvas.transform, false);
ownedUnits.Add(newUnit);
}
}
a 2D sprite as a child
Wdym by "2d sprite"? A UI Image? A SpriteRenderer? Which one?
it copies the prefab but has the parent of it null
That's because you're not using the correct version of Instantiate, which allows for a parent.
Sorry a UI Image
you should just be doing GameObject newUnit = Instantiate(canvas.transform);
that's the right way to spawn any ui prefab
although I imagine you would actually want a better parent than the canvas itself - usually a panel or something.
o yea that'd prob be better
ok it all worked tysm
Is it me or while doesn't work in Unity 2022?
it's you
Well I'm going crazy because while really doesn't seem to work. It's completely skipped.
Break out the debugger and look closer
Because these questions are so easily interrogated
while loops are skippoed when their conditions are false.
Your code is wrong then
If you want help, share the !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ 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.
As a baseline I donโt see much reason why you would need any separation into classes here. I would think about why any piece of code would maybe have to change in the future and try to isolate the rest of the system from those changes (within reason). Typically these have boundaries along input/control/presentation/view/feature and other concerns specific to the project. This doesnโt necessarily mean making more classes, it could be methods, blocks inside a method, groups of fields, context structs, states, named signals etc. Additional classes/interfaces would only happen when additional instances are required because of composition, I.e. one thing/service being multiple things to different clients; or for technical reasons derived from the way Unity works. Gratuitous separation where you canโt really explain why the separation is necessary leads to low cohesion and unnecessary API surface area that can be misused/misunderstood in the future.
Bump
Hey you guys, is peer-to-peer difficult to implement in a card game?
can unity crash cause of an infinite loop?
Could anyone give me insight to make my code work, it's not counting to 5 seconds, instead it's skipping the if statement and deleting the game object right away.
GameObject.Destroy(gameObject);
should be inside if statement
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Linq;
[CreateAssetMenu]
public class ruleTileCombine : RuleTile<ruleTileCombine.Neighbor> {
public bool alwaysConnect;
public bool isWallRun;
public TileBase[] tilesToConnect;
public bool checkSelf = true;
public class Neighbor : RuleTile.TilingRule.Neighbor {
public const int Any = 3;
public const int Specified = 4;
public const int Nothing = 5;
}
public override bool RuleMatch(int neighbor, TileBase tile) {
switch (neighbor) {
case Neighbor.This: return checkThis(tile);
case Neighbor.NotThis: return checkNot(tile);
case Neighbor.Any: return checkAny(tile);
case Neighbor.Specified: return checkSpecific(tile);
case Neighbor.Nothing: return checkNull(tile);
}
return base.RuleMatch(neighbor, tile);
}
bool checkThis(TileBase tile)
{
if (!alwaysConnect) return tile == this;
else return tilesToConnect.Contains(tile) || tile == this;
}
bool checkNot(TileBase tile)
{
if (!alwaysConnect) return tile != this;
else return !tilesToConnect.Contains(tile) && tile != this;
}
bool checkAny(TileBase tile)
{
if (checkSelf) return tile != null;
else return tile != null && tile != this;
}
bool checkSpecific(TileBase tile)
{
return tilesToConnect.Contains(tile);
}
bool checkNull(TileBase tile)
{
return tile == null;
}
}```
This is my custom rule tile script to make different rule tiles connect and work with each other. I'm trying to make a rule override tile for the tiles that use this script, but it doesn't seem to work.
Need help with player respawn when falling off platform in Unity - Zip file attached
Hi everyone,
I'm currently working on a Unity project and I'm facing an issue with player respawn. My goal is to have the player respawn at the initial spawn point when they fall off the platform.
I have tried several approaches, but nothing seems to be working as expected. I've attached the entire project (without the Library folder to reduce size), including all necessary scripts and assets, in a ZIP file for reference.
Here's the problem:
When the player falls off the platform, they should respawn at a designated spawn point.
The platform and player are set up, but the respawn logic doesn't seem to work correctly.
I would really appreciate it if someone could take a look at the project and help me identify what might be going wrong.
Thanks in advance!
It always shows the default sprite, despite the tiles being in the correct places.
Respectfully nobody is going to download your project and see about providing a solution
If you want players to respawn when falling out of bounds, I suggest placing a big plane at the bottom to catch players and have them respawn. Alternatively, hardcode a base Z position that when players go below respawns them
Yes, it will either become "Non Responsive" in Task Manager or after a while, it will just straight up close with a crash report window when your memory gets maxed out
Any idea?
I'm also open for other ways to use the same rule tile pattern for different sprite sets
Its not clear where that function is being called or when you are resetting your timer variable, though in general, you can use Time.time with a variable and calculate the difference - as Unknown mentioned, if you want the delete to happen after your timer, youd want it to happen inside your if-statement, for example:
float someTime = 0f;
void SomeFunc()
{
if(someTime > Time.time) {someTime = Time.time + 5f; DoTheThing();} //every 5 seconds, "TheThing" will be called
}
In that example, DoTheThing would represent your log and destroy logic, if you stick with the code you have, youll want to make sure you also reset your timer after it does "the thing"
For some reasons there isn't any info on it online
Thank you for the suggestion! I tried using the plane at the bottom to catch the players, but it didn't work as expected. The problem seems to be that the character is not being teleported to the starting position. Additionally, I have already tried the hardcoding idea, but I didn't have success with that either. Any suggestions on what I can check to fix this? I am using the Kinematic Character Controller, which I think might be interfering, but I don't have much experience with Unity.
I'm not too familiar with Kinematic but I believe it ignored actual collissions?
Regardless hardcoding should work and seems most reasonable. If it didn't work I suggest sharing the related !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ 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.
Since falling is usually only a change in the y-axis, you could setup a check with the transform instead, for example if(player.transform.position.y > 25) {Respawn();} - if your respawn logic happens in a different script, you could setup an event and pass your player as a param to have your respawner know when to hard-set the position of your player transform (and if you cant override the player transform because of the asset your using for your character, that asset may have some API that sets the position instead), this way you dont have to rely on physics and colliders (although as Fused mentioned, seeing your scripts setup on a paste site may help)
Anyone knows about this?
I've tried several ways to solve the problems I've encountered, but I'm just getting more confused with each attempt. Since things are getting complicated, I've decided to try a different approach. I'm going to create a new project, but this time without using Kinematic on the Rigidbody, to see if I can simplify the movement and platform mechanics.
I hope this will help me better understand how the components are interacting and avoid some of the errors I've been facing. I'll update you with my progress as soon as I make more headway.
Thanks for your patience!
Anyone got a fix to this?
post your !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ 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.
in a loop, which would be more efficient, iterating trough 8 elements each time in the loop or making a bool with Physics.OverlapCircle? I don't know how overlapCircle operates so idk which would be faster
hello guys when i click my script and its supossed to take me to my script in visual studio it show nothing how do i fix that
do not cross post
honestly, with such a low amount of things, efficiency really shouldnt matter
even if you used a very slow function, the actual impact it would have is negligible
now if you had 8,000,000,000 elements, thats a different story
consider a function taking 100nanoseconds, vs 1nanosecond. Sure its 100 times as slow, and that would matter if you're writing very advanced code where performance is incredibly vital.
Then consider that in the time it takes you to blink, the 100ns function could be called 10 million times
hey, how do I reference gameobjects from a different scene in the editor?
I have Scene A (The player starts there) and Scene B
When I switch to Scene B the player is a DDOL object
Scene B has gameObjects with scripts, that need to reference to the player. But I can't select them in the editor as the Player is in a different scene
I am pretty sure there has to be a solution to handle these types of situations, but I just couldnt find anything useful right now
DontDestroyOnLoad is what you are probably looking for
Yes, my player is a DontDerstroyOnLoad object, but in the editor I can not reference him as he is in a different scene
Basically the player has the PlayerHealth script attached to him, which I am trying to acces in Scene B with a DealDamage script
How will "DealDamage" do this, if its via a TriggerEnter for example then you can get the component via this.
otherwise you need a solution such as the singleton pattern or using Find() to find this object/component.
I haven't really decided on how the damage is being dealt yet, I just have a simple debug object for it as of now.
Interacting with it will Damage the player.
In the future, I would probably plan it via triggers? My plan is to make it check weather I was hit by any objects (bullets, bottles, lego bricks or whatever)
Then if the player object/scripts perform the interaction (i presume via some raycast + get component) and calls some function (e.g. public void OnInteract(Player player)) then this solves the "getting ref to player" issue.
A common design is using an interface to make a generic interaction system that many scripts can utilize (e.g IInteractable)
give me a sec so I will be able to provide further information that might help
What would cause visual studio to be unable to detect certain errors, yet still show others?
public struct Rectangle
{
...
...
public static int Padding => 5;
}```Like in my Rectangle, various classes access the Padding property. Commenting it out, Unity correctly detects the error, yet Visual Studio does not
its not like VS isnt able to detect any error
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
only explanation for it not giving correct intellisense info/errors
if the script is opened correctly VS opens the generated .sln and understands the project
visual studio has no problem with actually making use of Unity
clearly not if you say it fails to show errors correctly
if its not opened correctly it can give generic c# syntax errors but nothing more complex relating to the whole project
well for here, the padding property doesnt exist
can you do "Find all references?" @wheat spruce
then vs is not working as it should
also, neither my Grid or Rectangle have any relavence to unity, only that theyre using the Vectors that unity provides
Interactable Objects script:
public class basicinteractableObject : Interactable
{
protected override void Interact()
{
//do stuff
}
}
PlayerInteract script:
public class PlayerInteract : MonoBehaviour
{
private float distance = 3f; //raycast length
private LayerMask mask;
private PlayerUI playerUI;
private InputManager inputManager;
void Start()
{
playerUI = GetComponent<PlayerUI>();
inputManager = GetComponent<InputManager>();
}
void Update()
{
playerUI.UpdateText(string.Empty);
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
Debug.DrawRay(ray.origin, ray.direction * distance);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, distance, mask))
{
Interactable interactable = hitInfo.collider.GetComponent<Interactable>();
if (interactable != null)
{
playerUI.UpdateText(interactable.promptMessage);
if (inputManager.onFoot.Interact.triggered)
{
interactable.BaseInteract();
}
}
I left out some parts of the script that are not important to the core functionality
Does your unity project appear from the solution (sidebar)?
๐คทโโ๏ธ close vs, in unity make sure VS is configured as your code editor, re gen solution via button, open script by double clicking it in unity project window.
no, it only shows the C# files
Id do as i suggested, add an arg to Interact() so the main "player" can be passed to the object to do work on the player.
Or have a static field for the player to be accessed anywhere. Or some global script per scene to init/provide this reference to interactables.
this is how its always been set up
wheres the button to regenerate the solution?
Right by where you can configure the code editor
hell you can even open the .SLN in the project yourself and see what it does
Then it's not correctly configured . . .
pass data from scenes
IN UNITY
something seriously wrong there
check these
yeah, its the same for me
also make sure this package is updated (if not there use a newer unity version)
already did
also when you press the regenerate button, does it do it instantly?
I can press it over and over again, it doesnt make anything appear
- Close project and VS
- Go to project folder in File Explorer
- Delete .sln amd .csproj files
- Open Project
- From Unity open C# project
- Screenshot VS Window
something in your VS must be miss configured or outdated then ๐ค Is it VS 2022?
done
nope
no way Assembly-CSharp-Editor.csproj is a sub element of Assembly-CSharp.csproj
this looks fine actually which is strange, can you find references for your Property now?
let me open a non-unityt project, want to check if the csproj and sln files show up without showing all files
Im doubting whether they do typically show up for me
yeah, sln is always hidden
I cant no
which makes no sense because it absolutely should be producing errors
its not like it makes it impossible to actually work without VS creating 100% of the errors it should
it just makes it damn slow to work
If you modify your VS installation does it have the unity tools?
yeah
wtf is wrong with it ๐
the VS installer was the first thing I checked
all up to date, unity tools are there
yeah, thats one of the last things to do
and im almost out of options
doubt its the issue, but I do have 3 versions
and also visual studio code
whats strange is ive only noticed this occur as of late, its never done this in my non unity C# work
and I only switched back to unity a few months ago, so for all I know its always been borked since I moved back, but I never noticed it until now
fuck it, im uninstalling every single IDE
I really hope it fixes it, cause what is there to do if thats not the case
nothing good, thats what
Is there a build in way to make an UI sprite being tiled only by one axis?
If not, what is the easiest workaround? Cause I ve found one, calculating needed pixel per unit multiplier each time resolution updates, but it's lame
I am working with this Helicopter script, its a tiny example from the asset store. I have found two "issues" that I am going to work on resolving. And I've put TODO comments on the two sections of the script I believe where to focus on these two issues.
-
When you land the helicopter on a higher elevation of the terrain, it requires more
EngineForceto "lift off".
This happens inLiftProcess, and I believe the issue here is taking the raw value ofHelicopterModel.Y, instead of the difference between the Ground and the Helicopter? -
When I switched to my models, Synty which are much larger in scale, and then later resize the Capsule Collider to fit within the model, and two Box Colliders for the "feet" (but unsure if they affect this), the "360 turn" on E/Q buttons, is much slower.
Now this one, I don't fully understand just yet. The script usesHelicopterModel.AddRelativeTorque, so my assumption is the capsule collider affects the physics... Though not sure why a longer one didn't have the opposite affect, but I also don't know where the pivot point is on these calls yet.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Now I understand, within the script as is. I just need to increase the variables for the Forces exposed. But Id like the actually understand more what is happening, so its not just "magic numbers" I am randomly setting.
I just cant get my head around why it wouldnt show such a plain and simple error
Trying to get a configuration comparison .. sadly I am still understanding how the colliders affects the physics, so I size them properly as well.
reinstalled
deleted the sln and csproj files in advance
๐คฌ
wait a second, opening up those files makes the errors appear
but then uncommenting the property, unity doesnt show the errors, but VS doesnt update to clear them
it almost seems like VS somehow isnt scanning the solution correctly
it only shows errors up once i actually interact with a file
Have you regenerated the project files
yeah
before I opened unity back up, I deleted the .sln and .csproj files first
then the regenerate button
at least it is showing the errors it was meant to now
just that VS somehow isnt scanning the entire solution to find all the errors until I nudge it
ill see if I can get help elsewhere, it doesnt seem like its a unity problem
I might have solved it
this was set to current document
what a pain 
When referencing a text component made using text mesh pro, is there a reason why would I ever use TMP_Text over TextMeshProUGUI?
or vice versa? I've always been using TMP_Text but the project I'm working on seems to have a mix of both and we should probably standardise on something, but I'm not sure on what
TMP_Text can refer to both the UGUI version and the 3D version
that makes your script more versatile
Unless you are using some feature that is specific only to the UI version, I recommend always using TMP_Text
by 3D do you mean worldspace canvas...? Or am I actually missing a whole world of 3D text through TMPro
no I mean the TextMeshPro component
geniunely didn't know it existed
TMP_Text can hold references to both TextMeshPro and TextMeshProUGUI
most people don't.
even though it's kind of the reason the asset is named TextMeshPro
Unity has a 3D text component called TextMesh
TextMeshPro is the "improved" version of it
and hey they have a GUI version called TextMeshProUGUI too
TMP documentation is so unhelpful, wtf...
I'll definitely check it out, that's pretty cool
they're pretty arse but sometimes you get lucky and there's a line of documentation
seeing TextMesh finally made me understand why MeshFilter exists
both of them can provide a mesh to a renderer!
great doc string
mildly scary: why is there a RequireComponent(typeof(Transform)) in there
๐ค
That code was probably incredibly old
they might not have always thought of Transforms being guaranteed on GameObjects at the time.
yeah
thus transform surviving when, say, light did not
cowards. every game object should have a light on it.
Does anyone know how to get the unity newtonsoft package imported? I heard unity added it in as an official unity package but I haven't been able to get it to show up in the unity registry when I search for it even though I updated to the latest version of unity
You can add it by name com.unity.nuget.newtonsoft-json
Thatโs what I saw when I looked it up but I tried searching that in the unity registry in the package manager and it didnโt show up. Is there a different way Iโm supposed to add it?
The plus sign on the top left, add by this name
Oh ok, thanks
Is there a nice way to get a callback when the number of children on an object changes?
it's a ui element (so with a recttransform) if that helps
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
There's some events there you can probably use
You can use a layout group (abstract class) to receive such callbacks on a canvas.
I have it in my project now but it still isn't recognizing the namespace, which I believe is Newtonsoft.Json
OnTransformChildrenChanged, cool! that's pretty useful
if you're using asmdefs in your project you need to make sure to reference the assembly in yours. or if the error(s) are only showing in your IDE and not in unity then you just need to regenerate project files
Actually not sure if those work with UI, assuming Transform implies recttransform too
but Anikki may have the better answer if so
RectTransform inherits Transform so it should work
What are asmdefs if you don't mind me asking?
What is asmdefs? I am just trying to use newtonsoft. All I did was import the package into my project in the project manager and put the using statement in the file I want to use it in, where I'm seeing the namespace not being recognized. Are you saying there's another namespace I need to include in order for it to work?
assembly definitions. and at no point did i say there was some other namespace to include
are you seeing the error only in your IDE? or does it appear in the unity console when you save too?
That function is known to be quite annoying to use. I would, if possible, hook into the layout group system to get clean notifications. Otherwise you simply have to deal with the quirks of that MonoBehaviour callback.
Oh, I didn't even think of that it could only be showing an error in my IDE. Yes, I am not seeing an error in unity. Would a using statement to a namespace that doesn't exist throw a red error?
go back and reread my first reply to you
oh, I will try regenerating the files then
I was using the script to control a HorisontalOrVerticalLayoutGroup so it's a bit silly to make it a layout group too
but I found a different solution, so nevermind
Little known fact: the canvas ui system is designed to be modified by you. Nothing wrong with forking the H/V layout group and adding the features you need.
they're pretty barebones as they are anyway
yeah but then I'd have to implement both the horisontal and the vertical layout groups, and that's rather unnecessary for what I want to accomplish
too bad you havenโt told us what that is, x/y problem and all that.
Phidgets with Unity
anybody know it it's possible to get a reference to an instance into an editor script? I haven't been able to figure out how to do it while the game is not in runtime but I need the reference for the behavior of the editor script

can you be more specific about what exactly you are trying to do?
I have a series of nodes and I have a pathfinding algorithm that depends on which nodes are connected, which I am going to be doing manually as I make the map for my game. So I am making a script to let me easily choose the connections by using handles in an editor script and saving the connections in a json file. I represent the node positions using game objects which are all children of a main game object, which allows me to get the list by retrieving all children of the object. I need a reference to this object in my editor script in order to place buttons on all unselected nodes, which I can then click to add a connection between the selected and clicked node
well you have a few options, there are obviously the Find methods which aren't really ideal but definitely work, you could trigger whatever this directly from the instance of some component on that object which would allow you to just pass the reference (you would wrap this in conditional compile symbols so it isn't compiled into the build to avoid build errors), have an editor window that you directly assign the reference in. there are likely other ways and you'd probably have to ask in #โ๏ธโeditor-extensions for any other suggestions if these don't work out for whatever reason
Oh thanks, thats perfect actually. I would never use find in anything that is a part of the games code but this is only a tool for editing so it's fine
if I ever finish and build it I could actually take this whole part of the code out and just put the final json file in
is it a good idea to apply slope movement to everything? i mean it activates only on angled surfaces but replacing the ground movement with slope movement saves some space
Flat ground is simply a slope of zero degrees (:
It seems reasonable to me.
In fact, that seems like a great idea to me; it means that movement on various floor types will be more consistent
Is the type var a broad type that can be used for specifying any type?
I have never used it and I have encountered an area of which is may be useful (in this case I'm using it to get a tuple from a function of mine to return multiple items)
var is fake. c# is a strongly type language so the compiler knows the type of it anyway, what you'd be doing is denying yourself clear code
so it's best not to use it?
unless you don't want to type out a large dictionary typing, no
as in no, avoid it ;P
alrighty thanks for the insight
it's more of a thing for dynamic languages when you care less for the type at the time
but in reality, web devs are lazy
You have to use var with anonymous types but not as likely to be using those in unity i believe.
@heady iris so let me see if I can understand this properly
In Identifiable Processor:
private static void OnWillCreateAsset(string path)
{
EditorApplication.delayCall += () => HandleAsset(path);
}
private static void HandleAsset(string path)
{
if (typeof(Identifiable).IsAssignableFrom(AssetDatabase.GetMainAssetTypeAtPath(path)))
{
var identifiable = AssetDatabase.LoadAssetAtPath<Identifiable>(path);
identifiable.ConfigureGuid();
EditorUtility.SetDirty(identifiable);
AssetDatabase.SaveAssetIfDirty(identifiable);
}
}
this section basically, when the Identifiable script is added to a gameObject, will generate a GUID for it? And the GUID is generated based on the path, but what it's based on doesn't really matter a ton it matters what the GUID is? And it's based on the path because then there's no off chance that there's a duplicate GUID?
What's the significance of Identifiable being an abstract class, what is that?
I'm also wondering how you find what object corresponds with the GUID
The GUID is not generated by the IdentifiableProcessor. All it does is load the asset and tell it to grab its own GUID
yeah
Identifiable has the actual logic to grab the GUID from the asset database
You can inherit from it to create a class
By itself, it isn't meaningful, and you can't instantiate it
That's the more annoying part. For some kinds of objects, I keep them all in a Resources folder and use Resources.LoadAll to fetch them all
for others, I'll find them all through a more elaborate means
e.g. I have a tree of "settings" objects
public class DeleteOnClick : MonoBehaviour
{
void OnMouseDown()
{
Transform parent = transform.parent;
Destroy(gameObject);
if (parent != null && parent.childCount == 1)
{
Destroy(parent.gameObject);
}
}
}
I used this for my block destroying system script but when I break the block it leaves an invisible hitbox leftover, why
I walk that tree to find all of my settings and put them in a big dictionary
In your case, I presume you already have a list of prefabs you can use somewhere
Just look through that (maybe build a Dictionary out of it)
well, perhaps the parent has another parent that has a collider on it!
look in the Hierarchy while the game is running
yeah I was intending to make a dictionary if you didn't have a more sophisticated idea
I would like it to be a static dictionary so other scripts can read it, but if I do that I can't see it in the inspector
oh wait my idea doesn't even make sense
You canโt serialize a dictionary in general
But you can certainly construct one as the game starts
Each prefab will contain its ID
Make a dictionary that maps those IDs to the prefabs
so serialize an array of prefabs somewhere, make the game read the GUIDs and assign them to a static dictionary?
Yes.
is that something I can do outside of a gameobject?
Only parent it has is the chunk but that does not have a collider
oops I sent that too soon before your message
You can use the RuntimeInitializeOnLoad attribute to run code as the game starts
Youโd still need to serialize the list though
You can put it on an asset that gets loaded from a Resources folder
So it'd look a bit like this
public class PrefabCatalog : ScriptableObject {
public List<Whatever> prefabs;
}
public static class GameData {
public static Dictionary<Guid, Whatever> prefabMap;
[RuntimeInitializeOnLoadMethod]
static void Setup() {
prefabMap = new();
PrefabCatalog catalog = Resources.Load<PrefabCatalog>("Prefabs");
foreach (var item in catalog.prefabs) {
prefabMap[item.Guid] = item;
}
}
}
fetch the catalog from Resources, then put all of the prefabs into the dictionary
note that this does mean that all of the prefabs get loaded as the game starts
You might instead use Addressables to load the prefabs on-demand instead of immediately, but that's probably not relevant to you right now
(that'd be more important if each one brought in lots of heavy assets)
a Resources folder is a great way to "bootstrap" the game
it can be the one time you don't use a serialized reference
wait are the PrefabCatalog and GameData classes in the same .cs file?
Doesnโt really matter
You just canโt put two unity object definitions in the same file
So two monobehaviours, two scriptableobjects, etc
Unity references the script assetโs GUID, hence that rule
Otherwise, you can do whatever you want
I was confused how the Load function would know how to get the PrefabCatalog asset but I guess it automatically knows to just get the PrefabCatalog part
Look up Resources.Load
It fetches an asset from a Resources folder by name
Got it
I think I've got enough information to start integration now
Looks like TMP took the Resources folder name already
yeah
oh I needed to read that a few times to fully understand why one needed a longer path
I made a class for this
a powerful website for storing and sharing text and code snippets. completely free and open source.
I've got a bunch of "catalog" assets in Assets/Resources/SingletonSO/
@heady iris so I made the public list in the ScriptableObject class but I can't see the list in the inspector
sorry if I'm bothering you a lot if you want I could try to search for information on the web
You need to create an instance of this scriptable object
This is the script asset.
Throw a [CreateAssetMenu] attribute on it and youโll be able to create an asset
Make sure to throw it into a Resources folder
yep
Ok I put this before the class but nothing's showing up
I'm not sure how to instance it
without putting it in a scene at least
That attribute allows you to create instances of the asset.
just like creating a Material, for example
Oh that makes sense
why is OnWillCreateAsset() greyed out and yellow? It should be blue
probably
It's not being called
I also can't see anything under AssetModificationProcessor
Ping reply please when responding
also happy new year
it will not suggest options that are not possible to write in the current context. try doing that inside a method
Do you know anything about the other thing?
The other thing being what you already answered yourself?
This
Why isnโt it being called
have you actually done anything to confirm it isn't being called? keep in mind that Console.WriteLine does not write to the unity console
It's a unity message called via reflection, so VS has no idea it's called automatically (unless that's something their Unity plugin knows about)
I'm not sure if VS supports the jetbrains annotations but if the Rider plugin didn't know about it would decorate it with [UsedImplicitly]
It doesnโt? That would explain it
Print wasnโt showing up so I had to use alternative
Probably shouldโve used debug.log
print is defined by MonoBehaviour
I would avoid it, as it's just an inferior version of Debug.Log
a holdover presumably added to placate people coming from certain other languages in the early days
is there a way to make it so that variables also show references the same way functions do in vs?
wrap it in a property ;p
if you right click it I think you can grab references to it, no?
I wanna present a game idea to someone
how do i do that ๐
Happy New Year to @everyone ! ๐ซ๐ค May you stay healthy and be happy afresh... ๐
dont know about vs but in vs code both functions and variables show the number of references
VS shows references hints only for methods and properties, you can open "Show all references" from rmb menu or with shortcut for class fields
ok I switched it to debug.Log() and still nothing happens
oh wait I didn't properly understand what it was supposed to do
my mistake
This code is supposed to convert world positions to grid positions:
float percentX = (worldPosition.x / gridWorldSize.x) + offsetX;
float percentY = (worldPosition.y / gridWorldSize.y) + offsetY;
percentX = Mathf.Clamp01(percentX);
percentY = Mathf.Clamp01(percentY);
int x = Mathf.RoundToInt((gridSizeX) * percentX);
int y = Mathf.RoundToInt((gridSizeY) * percentY);
My problem is that for the y , where the object which i convert the position of goes, the y goes in the opposite direction. Would someone know why is that? (both my offsets are 0.5f )
if you have a Grid, there's already a function to do that
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GridLayout.WorldToCell.html
speaking of this, I've tried to implement my own version of this for my Grid system.
public (int x, int y) NormaliseVector2ToGrid(Vector2 pos)
{
int x = pos.x.RoundToInt(); //(int)Mathf.Round(value);
int y = pos.y.RoundToInt();
x = Math.Clamp(x, 0, Width - 1);
y = Math.Clamp(y, 0, Height - 1);
Debug.Log($"GridPos {x} {y}");
return (x, y);
}```It does actually return the correct value, like here the mouse position is shown as the green gizmo, and it prints `GridPos 4 7`
(int)Mathf.Round(value);
isn't there a function for this
yeah, probably
https://github.com/isadorasophia/murder/blob/4be0892024fb4d498349e22776010e7795376e5e/src/Murder/Utilities/Calculator.cs#L574 ive used a handful of things from this
but point is, my implemenation seems far too simple for it to have worked correctly
although, could it be that becuase I have my grid originating from {0,0} which is the bottom left point, that it actually makes the process of converting from vec2 to my grids [x,y], a bit simpler?
probably
ill see if I can enlarge the margin, so the origin is still at (0,0) but it has some additional cells in each direction
https://hastebin.skyra.pw/gicobocida.pgsql im trying to make it so if the person exceeds the volume of 11f it chases you for 5seconds and then goes back to wandering. But it isnt working properly
You may want to describe what currently happens
so when i make noise and exceed the volume it chases me but after 5 seconds when its done it doesnt wander it just stands there
Log the value in update
Maybe both if and else if aren't true (the else if has an additional condition)
What are the sound and wander values when it misbehaves?
@heady iris I got the GUID assignment working, and now my prefabs are getting their own GUIDs, but when I instantiate the prefab or even try to edit it the GUID shows up as empty
This suggests that the GUID isn't actually being saved correctly
How are you assigning the ID?
show me that code
is that System.Guid you're using?
Yes
Unity can't serialize that.
oh
It looks like you wrote a custom editor to display it in the inspector?
yeah
You can certainly store a value in that field, but it will only exist for the lifetime of that exact C# object
the data isn't making it into a prefab or scene asset
That's why you have to create your own Guid type.
that looks like this
Separator doesn't seem to do anything though
doesn't matter that much
so should I be using Unity.GUID?
UnityEditor.GUID doesn't exist in the built game
https://bronsonzgeb.com/index.php/2021/09/11/the-scriptable-object-asset-registry-pattern/ shows how you'd create your own GUID type
it looks like it is roughly just a copy of the UnityEditor.GUID type though
oh ok
a powerful website for storing and sharing text and code snippets. completely free and open source.
I did make one important change
I added an implicit operator so that you can convert a System.Guid into my own type
(it literally just turns the old one into a string and then parses that. gross)
This is useful if you want to do _guid = System.Guid.NewGuid();
also, the odds of a GUID collision are so catastrophically low that I wouldn't even worry about it
One more important thing -- I'm not quite sure how the asset modification postprocessor will play with prefabs
It does look like it executed when you created a new prefab
yeah it did
it also tries to execute when I make a scene
but the logic weeds through that
it seems to work well with talking to the prefab
I'll have to experiment with that
this custom guid thing definitely adds a lot of complexity than I've already added
sort of; it just defines a new data type that holds four integers
what's the difference from a struct and a class?
conceptually: structs hold data, classes hold behavior
there are of course many exceptions and many ways to use them, and there are quite a few technical differences as well, stemming from that conceptual difference
Except for Mathf which is a struct for some reason ๐
Anyway yeah and the important difference is that structs are copied when you pass them around (value type) and classes are passed by reference (reference type)
a non-static struct, go figure
var math = new Mathf()
Mathf (or the math functions object, in general) doesn't really hold data nor behavior
it's an exception to rules in every language ive seen lmao
it's more of a namespace than anything
A struct defines a value type -- you directly hold the value.
A class defines a reference type -- you just hold a reference to the object, which exists somewhere else
so a List<HugeStructType> holds HugeStructType directly, whilst List<SomeClassType> just holds object references
I probably should've been using structs for these then
yeah those should probably be structs
seems like I don't get many errors for switching the class out for struct other than I'm not allowed to assign defaults I guess because it needs to be a constructor
Structs can't have field initializers tho which is a bit annoying
Oh you literally just said that oops
oh there's an error
I don't think you should use structs there
I would generally not recommend to switch things to structs unless you understand what they are for and what the consequences are.
I don't really get the difference still, it's the same data just stored in different places
this is a good starting point
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
oh that would've been useful to appear in my google search
do you really need those default empty arrays though
Do you understand the part about struct being passed by value and class being passed by reference?
no
Like a vector2 is data like a struct, it's two numbers and a type of value
but a GameObject is a class, it has references to an object...?
For example with Vector3 which is a struct, if you do cs var pos = transform.position; pos.x = 123;
This would not change your transform.position because you are modifying a copy of it
You'd need to assign it back
oh boy time to bust out the diagrams
that makes sense
structs make more sense here then
It's not really about what data it contains, it's about how the class/struct itself is passed around
A struct can have references to classes
yeah
Although my structs often just have primitive types inside it
but a variable with a class type is a reference because it's a class, right?
If the variable is a class then yeah
ok so this is happening, not sure what get hash code is
when you pass ref around, ie passing it to methods, setting in assignments, you're passing around, well, the reference
anytime you assign into that reference, the changes propagate to other references to the same object
when you pass value around, you're passing its values around like you would a primitive (which are also value types), so any changes you make don't propagate automatically
saveData can probably be a class
Equals and GetHashCode are methods used to define abstract equality/identity
if 2 objects compare equal with Equals/GetHashCode, then they're interchangable
!= should have ||, or just negate == to reduce repetition
oh yeah that doesn't even make sense the way I did it
that's like a nand
wait no not that
whatever it is it doesn't make sense
A nand B = not (A and B)
what you have there is nor
A nor B = not (A or B)
by de morgan:
not (A or B) = (not A) and (not B)
so what you have there says, neither array can match up for the structures to be unequal
but logically, if only 1 doesn't match up, that still makes them unequal
so you need nand, which by de morgan is equal to (not A) or (not B)
the expanded form might make it more obvious: they're unequal if one or the other is unequal
Not sure what your goal is, but your comparison of spriteShapes will return false in cases where they are two different arrays but containing the same elements, because arrays are reference types and compared by reference. Similarly for objects.
they're not actually spriteshapes or objects
I just called them that for some reason
should've been spriteShapeDatas
the startnum only increases when i make a osund over 1.1f how can i make it so it continuisl8y adds if i make a sound over 1.1f once
In what case do you need to compare two SaveDatas?
oh
to make sure I'm not saving duplicate undo data (yes each undo data is a whole save data but I can worry about that later)
would you ever have re-referenced arrays though
not sure what you mean
Does each new savedata get its own arrays or are you reusing them between savedatas?
both are reference types
how didn't i think about this, my grid originates from upper left corner, so i just gotta do grid.size.y - y if im correct
now it makes sense
so the only time they'll compare equal is when you duplicate the same save data value around
even if the contents of the arrays are the same, you'll have different arrays
I guess I need to do a comparison function then
about arrays vs lists; think about if the size will change dynamically
also sidenote; do you even need multiple savedatas floating around at the same time?
I wouldnt pay attention to my Grids code, its a custom implementation as I'm not using the one Unity provides
yeah, I've got one for every undo and redo state, and to hold the level in ram before switching to the testing state
im not using the one unity provides either
i wrote mine
ah
and mine is set to be from the upper left corener
confirmed my suspicions that the method was calculating the wrong value. Got my grid to extend its origin point down past the actual worlds {0,0,0}, so it just clamps that position to 0
perhaps you're using world coords without converting to local coords first
its because the vector2 clamps the position like this x = Math.Clamp(x, 0, Width - 1);
so the cursor is at {-1, -1} which is below 0, so it returns 0
public (int x, int y) NormaliseVector2ToGrid(Vector2 pos)
{
int x = pos.x.RoundToInt();
int y = pos.y.RoundToInt();
x += GridPadding.Left.RoundToInt();
y += GridPadding.Down.RoundToInt();
x = Math.Clamp(x, 0, Width - 1);
y = Math.Clamp(y, 0, Height - 1);
Debug.Log($"GridPos {x} {y}");
return (x, y);
}```this appears to fix it
im confused about what exactly the context is
the red sphere is the world origin, right?
the idea is, the red circle in the middle represents the perimeter of my terrain. Theres a rectangle that surrounds the circle which is that big black square. The grid that gets created fills the region of that square. Unless I add padding, it means the grid will only ever be as large as the perimeters bounds
so I add some padding to make the grid a little larger than the bounds
but as the perimeter originates at {0,0,0}, when I convert a vector2 at the cursors position, I need to take the padding into account so it knows that {-3f, -3f} is actually [0,0]
TestDummy > ModuleContainer > Orientation > EngineSlot > Thruster
These transforms have varying rotations. I ultimately need to get Thruster transforms rotation via code, so that I can align something to that rotation in the world space, independant of it's hierarchy.
float rotation = _thrusterTransform.rotation.eulerAngles.z;
This doesn't seem to account for the absolute parent rotation.
As I rotate the parent in the unity editor, the debug log just prints out a static unchanging rotation. Although adjusting the rotation of thruster transform itself will send out a new rotation value.
this just sounds like a convoluted way of saying, it's local vs world coords
perhaps, I havent really been thinking of my grid in terms of world/local coordinates
its mostly just a data representation to store information, the tiles dont actually exist as actual world objects
[0, 0] on your grid is at [-3, -3] in the world
only when I give the left and down padding 3 units
[0, 0] on your grid is at [-leftPad, -downPad] in the world
GridPadding = new Padding() { Top = 5f, Right = 5f, Down = 0f, Left = 0f };
transform.rotation is world-relative, is that what you're trying to get? im kinda confused what you're trying to get from your message
As I rotate the parent in the unity editor, the debug log just prints out a static unchanging rotation.
make sure you're rotating about the right axis
for(int x = 0; x < mapWidth; x++){
for(int y = 0; y < mapHeight; y++) {
int index = _tilemap.GetIndex(x, y);
int xpad = x - Grid.GridPadding.Left.RoundToInt();
int ypad = y - Grid.GridPadding.Down.RoundToInt();
Centroids[x, y] = new Point(xpad, ypad, _tilemap.Map[index].Zone);
}
}```I do later generate points at the center of my tiles, as those center points will be used by my marching cubes system, becuase that needs to know where those tiles actually exist in the world
nice that after several iterations of designing the system, that its finally coming together
How can I make joints unsplittable? I dont want those weapons to pierce between limbs but I cant make them triggers because weapons should collide with each other for things like block.
also I dont know why weapons dont collide?Because they are too thin?Rigidbodies are set to continious.
You'd need to show joint settings, the code you are using and the collider and layer settings of the weapons etc.
do you need ones for the characters too?
Perhaps
Why is it kinematic? Is it a child of another rigidbody?
all weapons use that weapon 1 prefab
it gets instantiated under the slot gameobject and arm has a rigidbody
I'm pretty unfamiliar with how parenting rigidbodies works in 2D physics, but I guess that answers the question why your weapons arent colliding
With each other
Could maybe either get rid of the weapon's rigidbody and just use its collider if you keep it as a child of the arm
yeah I actually dont need it
Or make the weapon's rigidbody attached with a joint to the arm
I removed the rigidbody now it doesnt pierce through too.
If you get rid of the rigidbody and still need to detect collisions (OnCollisionEnter2D) for the weapon separately, you can check which of your own colliders were hit from the Collision2D parameter
Not sure if you use oncollisionenter but i'd assume you want to detect hits
yes I will
The point is that you need to check whether it hits the arm or the weapon
Since they use the same rigidbody, the collision message will be sent to the arm
I think you have helped me before so thank you again 
Np ๐
Also FYI you might want to look at physics2d settings if you run into instability issues of the joints
It looks stable so far tho, especially if the piercing was fixed
this doesn't seem like a code question. and as i've pointed out to you, you can ask questions about that asset in the discord server the asset developers made #๐ปโunity-talk message
I am currently starting a project in which I seperate client and server code in the editor via folders. What would be a generally accepted way to name classes according to which side they serve? E.g. the NetworkController will be needed on both sides. Would I call the NetworkController class on the server side "NetworkControllerServer" and simply "NetworkControllerClient" on the client side?
Server Controller and Client Controller? 
hi guys
how do i check if a point is inside a triangle prims like so
One simple way is construct a Plane for each of the 5 faces of the triangular prism, and then make sure the point is on the correct side of all 5 planes:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Plane.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Plane.GetSide.html
something like this is fairly standard accepted practice, sure.
In that particular instance, yes. But there will be more scripts than these two ^^ I am just wondering if there are any naming conventions for that? I called my DungeonGenerator "DungeonGeneratorServer" and "DungeonGeneratorClient" now.
wow didnt know that exists
thanks
all try it out
Good to know, thanks!
The plane class also has a really convenient raycast method too, for instance it makes things very simple if all you want is to find where the mouse is clicking on the ground
No annoying collider/rigidbody needed!
when im using unity remote it can see my touch points but when im using an apk it doesnt
Potentially important Specifications:
- visual scripting
- set screen ratio
Showing code might help, but note that Unity remote is still just running the game in the editor.
yeah
are you using input system
when you say "see my touch points" what are you trying to say?
you press on the screen, but it's as though no pointer is detected in the editor?
ok so it works fine when im using unity remote
but when i build it to an apk and instlal it on the phone locally it doesnt worjkm
Again you'd really have to show your code and explain which part isn't working
yeah sorry im trying to get it to load
well becouse my code is a mess so im making another project to show it clearer
thats kinda the main part
check the logs for any errors (with android logcat, using a development build)
i have no idea what that means
specificaly the development build part
and android log chat
Development build is just a checkbox in the build settings
uhm, does anyone know what conditions need to happen for this to get stuck in the loop forever?
GameObject go = new(name);
T mono = go.AddComponent<T>() ?? go.GetComponent<T>();
while (mono is null)
{
mono = go.AddComponent<T>() ?? go.GetComponent<T>();
Logger.Fatal("kurvo raboti we");
}
because it happens 
AddComponent will return null when it's not possible to add the component to the object.
For example you used a type T that wasn't a component type or you tried to do something like AddComponent<Transform>(), or you tried to do something like AddComponent<BoxCollider2D>() when there's already a 3D Rigidbody on the object.
What's the point of this loop anyway?
Seems like it would always be infinite if it enters at all.
it was to make sure im not crazy
Another thing is you should not be using is and ?? with Unity component types
they don't work properly especially when things get destroyed.
Also shouldn't you be doing GetComponent first then AddComponent if it's not there?
e.g.
if (!go.TryGetComponent(out T comp)) {
comp = go.AddComponent<T>();
}```
my situation is quite unique, im patching a game server and im pretty much working without the unity editor, instead i have patched the server to just load my own code that i start creating monos on top of
and this is part of my hotloading, and im using AddComponent first because i am destroying the object when a module is reloaded
so it should not even exist in the first place
What's the specific case in which this is actually failing
What component are you trying to add
its when i have the following mono attached after a hotreload:
internal class PlayerAuthorizationManager : MonoBehaviour
{
...
}
im not sure how this could make AddComponent to return null
and i just checked to make sure the GameObject is created, and it is
when you say... hot reload
what do you mean by that? Compiling new code while the game is running?
yea basically its doing assembly,load on a new dll that contains my logic
I'm not sure that's... really possible in Unity?
Can the game engine handle that?
It probably does some kind of precaching of all the MonoBehaviour classes up front, that might not have happened with your loaded assemblies
and so maybe it can't AddComponent such a component properly?
ok i built it as a development build, what now
its kinda complex to explain, but basically i have a game server that is an unity app and when i want to inject my own code dynamically i am using a proxy assembly lets call it loader that will load and "unload" assemblies whenever i update them and will hook up and de-hook event handlers from the other modules
the core part of unity is staying the same
now you run it with logcat attached and look for errors
Yeah I understood all that part but do your assemblies contain MonoBehaviours?
yes
So... does that actually work?
what is log chat ๐ญ
there is no such thing as "log chat"
oh logcat?
LogCat is the package I linked you to earlier.
riiiiight
sorry i was confused
so i goota add that (done) and then do i re build the apk
i think it works because you cant really unload assemblies and they are just sitting in the background, and when i "hotload" i kill the old gameobject and create a new one with the new mono from the new version of the assembly
only if you didn't build it as a development build
no i did
then no you don't need to rebuild
just connect logcat to your android device and run the game
And watch the logs in the logcat window
how do i do that ๐ญ
All explained in the link I sent you above.
erm ok im looking a it now
i have no idea what any of it means but i can see when i tap it says this 2025/01/02 16:49:33.259 13832 13849 Info Unity Handle cmd APP_CMD_TOUCH_EVENT(20)
basically you want to filter it to your app only, and just look for any errors.
You can also see Debug.Log stuff this way.
well there doesnt seem to be any errors
iys just the 2025/01/02 16:49:33.259 13832 13849 Info Unity Handle cmd APP_CMD_TOUCH_EVENT(20)
So what's actually not working
drag what around
The square
Front the original video I sent
But also I made my own debunking interface thing and it's just not registering my touch
Hi Guys I started using unity 2022 LTS like 6 months ago in some projects .
But now I'm thinking about making another project an fps game with survival and fighting elements.
I just want to know should I use Unity 6 or it's a bad idea.
keep in mind that I already used it and It's good. but I want someone who used it more than me to give me advice ,Thanks
If you want to target WebGL it is worthwhile using 6 otherwise I would stick to 2022
For now the only thing that I don't like is importing assets in unity 6 changes them a little bit and I sometimes lose some colors ,any idea how I should fix it ?
that sounds like a texture compression issue so you might want to play with that
What's the default and preferred way to change position?
I want to write something like this: GameObject.transform.position.y += 1.
Which doesn't work, of course.
The first thing that comes to mind is something like this:
var Position = GameObject.transform.position;
Position.y += 1;
GameObject.transform.position = Position;
A little bit verbose for changing a float.
I can probably write extension methods like:
void Change(this Vector3 Position, float X, float Y, float Z = 0) {
var NewPosition = GameObject.transform.position;
Position.x += X;
Position.y += Y;
Position.z += Z;
GameObject.transform.position = NewPosition;
}
void ChangeX(this Vector3 Position, float X) {
var NewPosition = GameObject.transform.position;
Position.x += X;
GameObject.transform.position = NewPosition;
}
void ChangeY(this Vector3 Position, float Y) {
var NewPosition = GameObject.transform.position;
Position.y += Y;
GameObject.transform.position = NewPosition;
}
void ChangeZ(this Vector3 Position, float Z) {
var NewPosition = GameObject.transform.position;
Position.z += Z;
GameObject.transform.position = NewPosition;
}
Any better solutions, guys?
You can also do transform.position += Vector3.up;
I use the extension way as well
Hello,
From a monobehavior, as a field, is it possible to reference a graphView Node input port ( List<GameObject> ) , thanks ?
you do not need to copy the position again from the gameobject
Yeah none of those extensions should be referencing any GameObjects
You mean for just the += 1 version? Yeah that was an example, I want to change it by more than 1
no, that is fine, I meant your extension methods
You don't need a reference to the GameObject at all in such an extension
I use one in a form like:
transform.position = transform.position.WithY(5):``` for example
Just an extension on Vector3
Yep, yep, I just wrote it more as of pseudocode. So it should be more like this:
void Change(this ref Vector3 Position, float X, float Y, float Z = 0) {
var NewPosition = Position;
Position.x += X;
Position.y += Y;
Position.z += Z;
Position = NewPosition;
}
remember when you do transform.position you are ALREADY making a copy
Or this might be enough
Oh
Yeah you can avoid the second copy
Imagine if we had record struct, we could've had position = position with { y = 5 }; for free.
imagine if Unity devs were not so hung up on using properties we wouldn't have the problem in the first place
Do you guys recommend any fps character tutorial ?
I'm planning to use NetcodeForGameObjects andI only used mirror before
Thanks guys
Added this now, too:
public static class TransformExtensionMethods {
public static void TranslateX(this Transform Transform, float X) {
Transform.position += new Vector3(X, 0, 0);
}
public static void TranslateY(this Transform Transform, float Y) {
Transform.position += new Vector3(0, Y, 0);
}
public static void TranslateZ(this Transform Transform, float Z) {
Transform.position += new Vector3(0, 0, Z);
}
}
This is useless code
why would you spam create Vector3
yeah this is pretty much 1:1 with what you'd get with Translate
no, you have completely misunderstood the situation
you just end up coupling your code to some โconvenience libraryโ nobody needs.
it does not improve readability
- transform.TranslateX(x);
+ transform.Translate(x, 0, 0);
(or)
+ transform.Translate(Vector3.right * x);
create Vector3.zero, cache it, keep manipulating it, if you want to apply changes on that vector3 to position just write it back to transform.position
Caching a value type doesn't really improve anything
This is so unnecessary
But I don't need to retype the the 0's and type Vector3.right * x, which goes very well with C# moto of "not making the programmer type more than they have to".
this makes it harder to do non-orthogonal translates
- transform.TranslateX(x);
- transform.TranslateZ(z);
+ transform.Translate(x, 0, z);
- transform.TranslateX(direction.x);
- transform.TranslateZ(direction.z);
+ transform.Translate(direction);
I'll use Translate when it makes sense: when it's less verbose
the X in the translate method conveys the same information as Vector3.right
not making the programmer type more than they have to
i think you're misinterpreting this as literally typing less.
if we followed that we'd have single-letter variables and methods
transform.Translate(x, y, z); is less verbose than:
transform.TranslateX(x);
transform.TranslateY(y);
transform.TranslateZ(z);
Of course. That's not the situation for what I wrote the extension methods for. I wrote it for where I have to translate on just 1 axis.
"more than they have to" means you don't have to go out of your way to say something indirectly
this is kinda the opposite direction of what you should go for; generalizable code
you've made code more specific, so any change in the behavior would involve changing what methods to use, instead of just changing values
Who cares if it's local to a project imo
i mean, i kinda care when it might be posted here in the future without context
It's drier than repeating transform.Translate(x, 0, 0); and transform.Translate(Vector3.right * x);. Less code, less verbose, drier.
Also don't forget the TranslateXY, TranslateXZ, TranslateYZ and TranslateXYZ methods if you're going to be utterly specific
what about translating about the xz plane
If you needed those then you just use Translate
Also don't forget overloads with Space relativeTo as a parameter
Also Transform relativeTo
On second though, maybe it's not such a good idea after all
now you're kinda in a middle ground where neither of the methods are as "dry" as you might like, so now you have 3 more excess methods
Why is that? It is the same type of movement he wanted to use, just without spam the heap. There is always Translate method to use if he need relative movment
structs dont' spam the heap
It's the stack not the heap
nice, didnt know its struct
FYI if you were to cache the value type then copying by value is doing to give the exact same result as new()'ing it
If it were a class, it would be different
I very much might add overloads for the relative to and use them, yeah.
https://youtu.be/SVRiktFlWxI?t=5960
Rabobank Livestream 2019 with Uncle Bob | A session about clean coding
The program:
09.00 Uncle Bob - Part 1
11.00 - Break
11.20 - Uncle Bob - Part 2
12.30 - Lunch
13.30 - Breakout sessions (NO LIVE STREAM)
15.30 - Uncle Bob - Part 3 - Including Livestream.
#werkenbijRabobank #RabobankIT #unclebob
Here's the Unity's Translate method:
public void Translate(Vector3 translation, Transform relativeTo)
{
if ((bool) (Object) relativeTo)
this.position += relativeTo.TransformDirection(translation);
else
this.position += translation;
}
It is worse than:
public void Translate(Vector3 translation)
{
this.position += translation;
}
public void Translate(Vector3 translation, Transform relativeTo)
{
this.position += relativeTo.TransformDirection(translation);
}
Because it's really just 2 different methods with 2 different implementations.
The relativeTo is a boolean in this case, too.
Is this supposed to be a video where it's explained why it might be better?
Yes
Having to pass unnecessary arguments into functions is annoying and unnecessary
Also error-prone
And harder to understand
you need to stop drinking uncle bob cool aid
this stuff (ideas of clean, dry, solid etc) is extremely outdated/incomplete and in many cases tangential or irrelevant to gamedev.
it's a unified implementation
it ensures the logic is in a single place and that other overloads just point to the implementation
(bool) (Object) completely unrelated but i have never once seen 2 typecasts for a single variable
these principles do not express absolutes that can be maximised, they all have a cost and removing some parameter from a .Translate() call is such an unimportant thing to care about in the grander problem space of finishing and maintaining a project its almost ridiculous.
if anything, the overriding argument for NOT extending an API is to maintain standardisation.
It's poorly decompiled code