#archived-code-general
1 messages ยท Page 459 of 1
Hey, I just finished my minesweeper game and would like to know if someone wants to see my project and give me feedback on it please (mainly the code) ? ๐
i know this isnt the interface channel, but why in the editor my UI looks perfectly normal but in the build it looks like the second photo
canvas settings
ui anchors
have a read, they control how rect transforms get positioned when their parent changes size
its a very common mistake and posted here all the time
better lol
change the canvas scaler mode to "Scale With Screen Size" then fix your anchors and that should be better
check a few resolutions from the presets in editor as you do this
alr fixed
ty
bump โ๏ธ
Might be a kinda donโt ask to ask thing where you might get better feedback either posting a link to a repo entirely or specific files
They want code review i think?
yes
ah, i guess that'd make sense here then
Here's my code : https://paste.mod.gg/guuzqgfnrsom/0
A tool for sharing your source code with the world!
Just random thoughts/notes. Some of these may not be preferable etc.
- Highly recommend singleton patterns that find and assign the instance in the getter of the singleton (i can send an example if needed). setting in awake is prone to failure if something tries to access it before it wakes up
- In
OnGameOverjust flip the logic homie, (if (win)rather than (if (!win)). The way you have it now just makes it harder to read which is why i assume you needed to comment them - This is very much a me thing but i hate the usage of
varbecause it just damages readability, especially outside of an IDE like how I'm reading it - Not sure what you think that RestartGame coroutine is doing, that doesn't make the scene loading async or anything. You'd need to use the async version of that function
- In
GenerateMinesLocationsi'm pretty sure you can just copy via constructor? eg.new List<Tile>(tiles) - It's fine for the scope of this project probably but would be nice if tile type was via enum rather than int for readability purposes (and maybe even a scriptableobject for bigger projects)
- Personally in
GenerateGridI'm not a fan of how much public access you have in manipulating aTile. IMO the Tile should be responsible for handling it's colour and value. At the very least if your going to have public ways of manipulating them do it via a function so you can validate the input and potentially react to it. eg. if you hadTile.UpdatePosition(int x, int y)andTile.UpdateType(int newType)Tile could update it's color in response to those being ran. - I'd need more context but those static lists (
Tile.minesLocationsandTile.flagsLocations) looks abit weird - In
StartGameyou runOnGameStartEventbeforeGenerateGrid. From my perspective if i'm listening toOnGameStartEventI'm assuming the game is ready/setup. You might want aOnBeforeGameStartEventfor whatever that is being used for?
- In
ClearGrid, For reasons it's a good habit to explicitly set references toUnityEngine.Object's to null when destroying them.
Hope some of these thoughts are helpful in anyway, I won't pretend I'm great at any of this though ๐
Thank you for the feedback ๐ ๐
- Oh that's really smart and I struggled in some projects because of that ๐ฎ Because also, doing it in the getter would keep doing that check if an Instance is already set each time I call that getter ๐ฌ
- I did
if(!win)to follow theclause guardprinciple and return before executing the rest instead of doingif+elsestatement. Isn't this way, the proper way"pros"do it ? - I totally agree, and I had them all being the
typeinstead ofvarbut the IDE added squiggly lines referring me that it's better to make those variable types bevarinstead of thetypeitself. What's usually used inproenvironement / projects ? ๐ค - Oh yeah, I forgot to remove the Coroutine part because in the beginning I had the coroutine to wait 3 sec before restarting the game so I can see where the mines were ๐ฌ
- Just tried and no I can't because
tilesis a 2D array whiletilesCopyis a 1D array (check picture) and I needed it to be 1D to go through more easily than a 2D array. - I totally agree. At first I used enums then I quit that idea for no reason ๐คฃ How would that work with Scriptable Object in this case or bigger projects ? ๐ค
- Yeah that's smart. I will modify that, thanks ๐
- Why do they look weird ? 1 is containing all the positions of the mines and the other all the positions where the player placed a flag.
- Good point ๐ Funny thing is I don't even use that event anywhere ๐คฃ Should I remove it ?
- Oh, using
Destroy(gameObject);doesn't set the reference tonullby default ? ๐ค I don't understand theUnityEngine.Objectpart ๐ค
Personally, I'd prefer not to search the hierarchy unless absolutely necessary. The failure in Awake can be completely negated if you keep the operations of the instance limited to the scope of itself only and instead access other objects in Start. For example: cs private void Awake() { rb = GetComponent<Rigidbody>();//Fine but could probably be assigned in the inspector } private void Start() { gm = GameManager.Instance;//Would always be valid if GM exists }
I get the reasoning but personally I think for singleton managers the cost is worth the reliability, especially if eg. another manager needs to reference gamemanager in their awake etc.. That's fair though
I did if(!win) to follow the cl...
Personally this function and the if/else itself is so small that it's not necessary
I totally agree, and I had them all being the type instead of var but
I cannot attest to preference in industry due to lack of experience
How would that work with Scriptable Object in this case or bigger projects ?
I'm a little bias because of my background in modding but I tend to prefer SO's over enums because enums are static and cannot be added to at runtime. Another massive benefit though is usually for something like a "content" "type" you'll usually have some correlating information (display names, icons, colors etc.) so using scriptableobjects lets you build that information in. This isn't perfect but you could use another scriptableobject to use them like an enum like
public class TileTypes : ScriptableObject
public static TileTypes Instance => /*some public facing reference eg. on a gamemanager*/
public List<TileType> AllTileTypes {get; private set;}
[SerializeField] private normalType;
public static TileType Normal => Instance.normalType;
[SerializeField] private mineType;
public static TileType Mine => Instance.mineType;
then you can use like
if (tile.TileType == TileTypes.Mine)
etc.
Oh, using Destroy(gameObject); doesn't set the reference to null by default ? ๐ค I don't understand the UnityEngine.Object part
Unity handles object destruction in their own way, You don't need to know tooo much about it but in some occasions where the engine wants to try and clear uneeded memory, a reference to a destroyed object is not the same as a reference to a null object
UnityEngine.Object is the base class for the types affected by this (anything MonoBehaviour, ScriptableObject etc.
Why do they look weird ? 1 is containing all the positions of the mines and the other all the positions where the player placed a flag.
Personally just abit odd that no one really "owns" that data nor is it directly connected to all the other data you have setup.
Tile already knows if it's a mine or not so maybe you make a helper function that iterates through the matrix and returns the mines. Or if its never going to change and you wanna be more optimized let the GameManager at the very least own the list instead and (imo) make it a list of Tiles rather than indicies because it's just better information
Same with the flags list where tiles could probably just store if they've been revealed or not
Trying to make it so left and right can't be activated if the other is activated.... so if left is โ then right can never be โ until left is โ, and vice versa
What currently happens right now is...
Left press -> Right Press = Left โ
+ Right โ (What I want)
But...
Right press -> Left Press = Left โ
+ Right โ (I don't want this)
if (leftHitAction.action.IsPressed() && _canHitBool == true && _rightButtonHold == false)
{
_leftButtonHold = true;
Debug.Log("Left Hit");
}
if (rightHitAction.action.IsPressed() && _canHitBool == true && _leftButtonHold == false)
{
_rightButtonHold = true;
Debug.Log("Right Hit");
}
if (leftHitAction.action.WasReleasedThisFrame())
{
_leftButtonHold = false;
_leftButtonRelease = true;
}
if (rightHitAction.action.WasReleasedThisFrame())
{
_rightButtonHold = false;
_rightButtonRelease = true;
}
Just to be clear (not arguing but explaining), I would not access another manager or anything that isn't on this object in Awake and would do those operations in Start. By the time Start is called, the Singleton manager would have already been properly set up.
else and else if is a thing.
else if would still prioritize the first one no?
either way though, if rightHitAction.action.IsPressed should make _rightButtonHold be true.... which means leftHitAction.action.IsPressed shouldn't activate because _rightButtonHold == true?
If both can be true, you'll have to prioritize one or the other.
Or handle the case of both being true
but it can only set it to true if the button is pressed.... and the _canHitBool is true.... and the opposite hit is false
if I hit rightHitAction first, that makes it "true" (that part works).... meaning there shouldn't be a way leftHitAction activates here
Then maybe rethink the logic. Honestly, I wouldn't have any conditions for input querying. If the button is pressed, then it's pressed. Regardless of what other buttons are pressed.
It's how you handle that input is where you can implement whatever conditions you want.
I have to do it like this because of the Client Side Prediction for Purrnet basically has it so I have to do it like that. I have to basically set a private bool in update, then have that be equal to a state variable which is then used for prediction (or something like that... still new to it myself ๐คทโโ๏ธ )
https://purrnet.gitbook.io/docs/systems-and-modules/client-side-prediction/input-handling
I have the logic working in prediction which is fine, but the problem is in the update method as of now (which is what I am showing via my code here)
You may need to show all the code... this seems legit to me. Is there something else that might affect the bool values? ๐ค
only other thing I can think of is this.... but the False part is what I have to add according to the CSP docs
protected override HittingPlayerInput GetInput()
{
var input = new HittingPlayerInput()
{
leftHit = _leftButtonHold,
rightHit = _rightButtonHold,
leftRelease = _leftButtonRelease,
rightRelease = _rightButtonRelease,
};
// Add A False Here
_leftButtonHold = false;
_rightButtonHold = false;
_leftButtonRelease = false;
_rightButtonRelease = false;
return input;
}
why does my player move like 4x faster when i fullscreen when playing in editor
;-;
I don't know when and how is this called, but it does seem to be resetting the bool to false ๐คทโโ๏ธ
So obviously the next time the other code checks the left thing they're all false and it goes inside the left if.
In absolute or relative speed? ๐
yeah im not 100% sure whats causing this.... im asking the Purrnet discord too but they're asleep lmao
but its weird this only happens for Right first then Left second.... but not Left first then Right second.... so I don't think this is a Purrnet issue
That's just how your logic is. If you have both left and right it goes into left because it's first.
my old logic I had a left method and a right method.... did it not prioritize left in that case cause it was via a method?
cause I dont recall this occurring before me trying to learn prediction logic
You weren't resetting the values before, I assume
idk, still weird though cause the left shouldn't even activate if the right bool is active.... and I did a debug log test on that... ๐ญ
if the only bug from this would be left + right at same time (same frame) was it picked left... then who cares very hard to notice.... but this is a problem lol
This part is wrong. You probably shouldn't have the = false there for stuff that's not single frame or something. But obviously when doing MP things are an order of magnitude trickier.
could be a framerate thing. if your code is running in update then it becomes dependant on the framerate
I can probably try that but it might not fix it
or maybe it did...
double checking lmao
I still dont get why that impacts it but yay? ๐
You can try anything and it may not fix it ๐คทโโ๏ธ if you have a valid quick idea or even a suspicion - you try it and then think about it with the new data
Because the bool IS false the next time you check it and left is pressed, so you go into left?
Like... you're setting the bool to true to specifically prevent that... and then you're resetting it to false in something that's probably called about every frame. ๐
You see how that's a problem, right?
ah ok
well it turns from a normal walk into a bullet so
i fixed it
just tinkered around with fixed update
Indeed, Tile knows if it's a mine or not and if it's flagged or not that's why the data is in that class, however to avoid each time looping through all the grid each time I request to know where all the mines are and where all the flags are, each time I set the Value to be a mine or I click to make the Tile a flag, I add it to those static List. When the Tile is no longer flagged, I remove it from that List.
So that way, I don't loop over every Tile in the grid everytime to get this information each time I request it ๐
I did if(!win) to follow the cl...
Personally this function and the if/else itself is so small that it's not necessary
How would you not have that if statement and make the game sill work ? ๐ค
They meant you could just do the if-else and it would read better. The main point of guard clauses / early outs is to handle the "boring" cases quickly and separately and not nest 20 levels of if-else
Has anyone used the C# dynamic type for anything? Didn't know this thing existed until now. Apparently it leads to spaghetti but I'm curious.
Avoid it as much as possible, reflection is usually used instead.
It is also NOT supported by il2cpp
Okay, people said it might be slightly more performant alternative to reflection but yeah
It exists pretty much only for COM interop. Don't use it for anything else, everything you do with a dynamic turns into reflection and kills your performance, even if it works.
lmao
That's the most cursed shit ever
No idea that those existed as well
C# has lots of useful keywords too such as stackalloc, fixed and unsafe that can be used in more "normal" ways
In most cases where it's used it can be safely replaced with object, which is the base type for all managed types.
Why is there no TryGetComponentInParent???
you'd have to ask unity devs
It's probably better not to rely on hierarchical relations like that
but yeah you could probably use a serialized reference for that
Yeah i just fixed it like this, but weird that it doesn't exist.
you can always write it yourself or do a null check
Oh right, collisions have evil situations like this
Collider.attachedRigidbody can be used to avoid this but that's still kinda hacky
What kind of modding were you doing ? ๐
Yeah I'm using this for other systems, but this is for an impactmanager (like bullet spark effects) so that would be a bad idea.
(you could also use Collision.rigidbody directly)
Yes it works! No more hard coding each hit effect into the bullet script XD
couldn't you have the wall do that
to avoid the surfacetype juggling
I had some issues with the bullet destroying itself on hit before the object it hit could even respond.
And i don't wanna attach a script to every wall.
So I just made an ImpactManager that can spawn any effect for a given SurfaceType and ImpactType.
Now in the bullet script i only need to pass the collision and bullet ImpactType to the manager and it handles the rest.
And i don't wanna attach a script to every wall.
you just did though?
or is there supposed to be a "default" effect when there's no surface info
Yes each impactType has a default effect. My game is 95% metal surfaces so i just set that effect as the default and only have to add identifiers to the other 5%
gotcha
is there are way to set an editor-only scripting define that's not on a per-file basis, e.g. MY_DEBUG_FLAG? i want to be able to compile in some debugging features when running in the editor that are generally useful, but compile them out when profiling because they're allocating and really obtrusive in narrowing down the source of real allocations.
void Update()
{
float xInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(xInput * speed, rb.velocity.y);
animator.SetFloat("Moving", xInput);
animator.SetBool("IsMoving", xInput != 0);
// only trigger jump flag when pressing Space (and grounded)
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
isGrounded = false;
animator.SetBool("Jumping", true);
// jump flip
if (xInput < 0)
{
spriteRenderer.flipX = true;
}
else if (xInput > 0)
{
spriteRenderer.flipX = false;
}
}
Debug.Log(xInput);
}
i cant make flip during jump
the code to flip isn't running when you jump
it's only running the first frame when the jump is triggered
it's not gonna run the rest of the time either
that shouldn't be in the jump block
i made left and right walking animation . if flip happens left walking animation get cursed for prevent this i tried make flip happens only during jump
why not 2 separate jump animations for left and right as well?
can anyone explain these spikes? my monitor is running at 59.95 hz, so i thought this might be what vsync looks like when not running at true 60hz. however, i was flipping the system refresh rate between a few settings and then back to 59.95, and once in a while afterwards the profiler would show a smooth 60fps.
first time i see this UI
Donโt profile the editor, profile builds. The editor is never smooth.
this is a build
It says play mode
(but it's not a standalone profiler)
are you sure that is what that means? that is a toggle between play and edit mode. if i flip it to edit mode, it profiles the editor. right now when i have the editor open, and not playing, the profiler shows nothing. i launch my dev build, and it begins profiling the dev build.
i just quit the game again before i took that screenshot, which is why it says "play mode"
so in any case, question stands (this is a profile of a build, after i have already quit the game)
Check the GPU profiler then. It's not enabled by default because it has significant overhead.
Anybody know what's causing this error in my terrain mesh generation? Google only showed decade old forum posts, which didn't have a solution.
The mesh is invalid somehow. Has no vertices, invalid scale, something like that
Hi ! I'm struggling a bit as to how to update a variable of a Behavior graph's blackboard from code :
don't mind the "GetComponent()" in update(). I was just trying to get it right..
I especially wanted to change the value of the second blackboard in the graph but I don't get it how.. 
well, what does the error say
also what's with the ? at the end
the "?" was just me expressing that I don't get it .. and the error is : "There is no argument given that corresponds to the required parameter 'newValue' of 'BlackboardVariable.SetObjectValueWithoutNotify(object)'"
so do you understand that error
I don't understand that variable altogether ? as it's only expecting 1 argument of type "object".
even it's defenition is :
public abstract void SetObjectValueWithoutNotify(object newValue);
yeah, you're supposed to give it a value
while you know.. at least I should need to specify the name of the variable and the value I want it to be
right now you're telling to set the variable, but not what to set it to
you've already gotten a specific variable though?
yeah the InputRun from the second blackboard of the graph.. I want to try to set it to true in Update()
what exactly is your question here?
how to get a variable reference, or how to set a value to that variable reference?
my question is how to set the bool variable "InputRun" that live in a behavivor agent. inside a secondary blackboard.
and are you stuck on getting the variable, or setting the value?
both..
the only thing I managed to get right seem to be the : agent = GetComponent<BehaviorGraphAgent>();
other than that I have no idea what i'm supposed to do next..
I did check that page ! ah I just found out the method is to be called from the agent itself and not it's blackboard ?! then I thought this didn't worked because the blackboard in the graph editor doesn't show that it changed. but comparing it at runtime showed otherwise !
Hey everyone,
I'm building a Player Controller using a Finite State Machine (FSM). Would it be acceptable to centralize all input-handling logic in the main State Machine script, rather than distributing it across individual state classes?
Curious about best practices here.
Hi, i am trying to use messagepack with litenetlib.
I installed necessary packages from Nuget and git.
I am building the server build with IL2CPP, when I send a packet to the server from the editor I get the error:
FormatterNotRegisteredException: Project.Scripts.Network.Packet.TestPacket is not registered in the parser:
There is no problem in my transfer from server to client.
As far as I understand, some links are broken in the build processes with IL2CPP and my estimated package to be parsed.
The doc writes something like code gen stuff but I did not understand how to do it in unity.
IDE : Rider
@errant flame why don't u use Unity Transport instead it has example of client and server in documentations : https://docs.unity3d.com/Packages/com.unity.transport@2.0/manual/client-server-simple.html
I just wonder to learn litenetlib for future experiments multiplayer etc . then i searched for serializations i saw proto buff and this message pack they are so fast against json serialization i know i can use json and go ahead but want to learn .
Also i wonder does unity transport support all devices as well as litenetlib and can i do everything that i do in litenetlib ?
Yes It is support all devices any platform
It is also UDP so they litenetlib equal to Unity3d transport
I just started these communication things litenetlib offsers a reliable unreliable UDP protocol i guess for fast data transmission is unity transport is same thing
oh got it
But actually I had some trouble when I try to use reliable protocol (chat GPT recommended me to use it for the case, I end up with unreliable protocol it worked fine for my case)
For my case i just want run a physic simulation under a unity server and sync that physic simulation fast as possiable.
I think the problem is not with neither Unity Transport or Litenetlib , main problem is serialization i guess
If i use unity transport and do same think with message pack i get again same errors until i use json normal regular serialization
I know I'm starting from a difficult point and trying to force something.
But since the simulation I want to do is a bit heavy, I don't want to lose control from the very beginning.
You can use Unity multiplayer they have higher lvl API that allowing to sync game objects or Entities if ECS
You are right, I have reviewed most of the higher level network API's , but there is a separate learning process for them.
And for some reason I could not get used to them, I could not learn them quickly :/
There are Netcode for GameObjects or for Entities and Multiplay for Matchmaker + Lobby they are not very hard to learn
but for simple game low lvl API is enough, built my own matchmaking/elo system quite quick after understand how to work with unity transport
hey guys, bit of a dumb question but do I need to do anything to reference an objective in an additive scene?
say I have a GameManager in a Systems scene that I put ontop of the game scene, can I just slot in references as usual to the manager as if it was in the same scene (in both inspector and code)?
not in the inspector, no, but you can via code
but you gotta be a little careful about maintaining the reference across scenes, if the object ever gets unloaded
hold on let me pull up my current code
my use case for this is I want to completely and temporarily suspend my main level scene (which contains everything atm) and move the player to a smaller but completely separate gameplay area, then move them back
so I was thinking I'd just use additive scenes and disable the main one, load the second one, move the player and all the gamemanager and ui stuff
my GameManager class is a static instance, it contains references to many other managers like sound, ui, mission, etc. which are all child objects
I have various other objects in the scene which reference the instance like this GameManager.Instance.AddEnemy(this);
if I move the GameManager out of the game scene and into its own additive scene can I still keepdoing this?
well you could, but you'd then have to manage the reference correctly
this will be destroyed when the scene unloads, then GameManager would have a dead reference if you don't do anything about it
that could lead to NREs afterwards
well I was hoping that I could extend this additive scene thingy so that the base scene just disables itself, the new scene loads additively on top (GameManager scene stays), then when the player's done in new scene they go back to base scene
so no object gets actually destroyed
Trying to use the unit testing package and I made a tests folder and some tests but I can't reference things in the main assembly for some reason, even though I have it referenced in the test assembly definition
oh wait i mightve found the problem
yeah no i dont understand this at all, lol.
it was my understanding if you make an assembly definition in the root folder it should automatically put all of your scripts into that definition, right?
Can you point me in the direction to find the correct api?
Any problem with using RectTransforms and LayoutGroups outside of a Canvas?
scenes don't get disabled/enabled, they're loaded/unloaded
you do end up destroying gameobjects in that process
Can I not just disable all game objects in the base scene then?
Oh I guess this means that both scenes are just constantly loaded
that seems like a lot of unnecessary work
just make stuff link up properly lol
!ban 1384186123344941157 scam
vera6372bt was banned.
can someone help me with netcode for gameobjects and server/client stuff, i think i know what im doing wrong but I do not know how to fix it
Video for see The error๐ง
what does that mean?
Im use to VS code but ive been told that its unity integration is minimul and VS is fully integrated. Im not sure what that means honestly
So with that said. What would be best to use
VS or VS code
Whichever one that makes you most productive. If you are not sure, try both and see.
i should state that i just started using unity. Ive been doing their tutorials for the last few days. But when it came to the scripting i was a little confused because unity had me download VS but in the tutorial the guy is using VS code
Ive used VS before but i personally dont like it. Its to clunky if that make sense
Sure, personally I use VS Code for a similar reason as well.
Ok cool last question. As far as functionality goes i wouldnt have to do some extention work arounds would i if i use vs code for unity ?
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
Follow the guide here.
ahhh okay sweet thats what it means by VS is fully integrated right ? This reddit post i seen said VS is better for unity im thinking that might be why.
VSCode I dislike using, as VS feels better
It's totally subjective, your mileage may vary
keep in mind that Vs is heavy and requires much more space on your local storage
You will find a lot of people online saying all sorts of things, the most common thing people say to discredit VS Code is "it's an editor not an IDE." A lot of those people also haven't used VS Code recently to know how much C# extension has improved over time. Evaluate it yourself and see what makes you productive.
IDE is a personal tool. Different chefs have their own favorites knives.
Thanks for the help! I think im gonna stick with VS code and give it a go with the extension.
i think for the most part, it is fine. when you get to the point of Debugging though, I do not think VSC can do the same thing. someone else would know better though, as i do not really use VSC anymore
VS Code has all the common debugging features stuffs you would expect, breakpoints, step into, step over, view call stack, variables, etc.
good to know, thanks. i will erase that concern from my 'database' then ๐
Is there any Generics equivalent of the ? from Java in C#? Eg, can I make a class that normally take a generic value and tell it not to care?
No, C# generics do exist at runtime unlike in Java where they are erased.
You either propagate the generic up further, or do something like class Foo<T> : Foo.
Crap... oh well
(But also - Cursor! For the previous IDE discussion. Integration is a bit annoying, but otherwise it's been awesome!)
So, I cant make a "Map<Type, Delegate<?>" to store callbacks for various types?
Non official VS Code (eg forks like Cursor, or even just VS Codium) unfortunately is not permitted to use the C# and C# Dev Kit extension, at least if you are abiding to their ToS. The major loss is not having the debugger, there is the Samsung debugger but I haven't used it to know how good it is.
You would just have to cast. Note that this is unsafe in either C# or Java, because neither type system has the capability to encode the relationship "each value's delegate type corresponds exactly to the key's type."
I know its unsafe. But I usually make my own Add which ensures anything I add accepts the type. So yes, Runtime unsafe, reflection unsafe, but otherwise pretty ok
Yeah the best you can do is exactly that, to concentrate the unsafeness into implementation and expose only the safe public API.
But otherwise it's not any different, just store Dictionary<Type, object> or something, and then cast the retrieved value to Action<T> or whatever.
The good thing about C# is that the cast will be checked at runtime and throw if it doesn't match.
You'd get a sort of class cast exception or no such method exception in java on runtime anyway. Somewhere you'll get errors if you do not properly code anyhow ๐
But the fact I can do typeof(T) in C# is a blessing โค๏ธ
I don't really write Java, but I'm under the impression that the cast wouldn't fail since generics are erased. It would only fail when you try to call it with the wrong argument type, which can happen much later on and makes tracking down the error a lot harder.
has there anyone who made jumping system by only script
bc i cant make my vertical collisions like rigidbodies
there is always a little space between collision and my player
if i put a low value as a distance the cast doesnt work
Why not use animations?
Why should i try to close that distance by other things
isnt it possible to make collisions by script
Why not use colliders
i used to make them by myself at gamemaker
And at the tutorials i've watched
he did collisions by script
You could do that... or you could click a few buttons
Are you in 2d or 3d
3d
Somewhere along the lines of adding force along whatever axis you're using as up and then multiplying by time.fixeddeltatime
You mean rigidbody force by force?
MyRigidbody.velocity
But also you should be looking at !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is there any "difference" between a const and static readonly?
static u can call class.StaticVariable you cannot call const like this it is just wroks like variable
const aren't variables (as in they cannot change/be-modified)
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const
static makes the member a part of the class and not per instance.
readonly only allows the value to be assigned once and in particular places.
hey, question !
I have a minimap in my MULTIPLAYER game.
On the host everything is generated fine, the minimap, the player markers for everyone connected and generated marker.
but for other people than the host everything is generated (playermarker, other markers) and everything is updated but the minimap is jsut invisible, its just floating markers. is this a camera issue? the camera is generated by the script aswell. the entire code is 600 lines long idk if i should paste it in here
https://pastebin.com/G9t9kpjj thats the paste. its too long for discord
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.
is there a way to 'terminate' a branch in the Behaviour package?
I want the Repeat While to only execute the node group immediately below it (the Passively Check node sets the relevant variable so it can break out of the loop) but it executes everything past that as can be seen in the image
the documentation doesn't cover the exact definition of 'branch' so I'm not 100% sure what does and doesn't qualify as one
(sorry if this is the wrong place to put this)
TMP_Text is not a string, it has a text property that is a string though. TMP_Text is the actual component
Because string is not the same type as a TextMeshPro component
wish they could make them the same type :/
That wouldn't make sense
string isn't a component
You can't put a string on a game object
A line of text in a book is not the same thing as a library building
what are you trying to do, send some code so we can suggest a soloution
the old "i forgot to put .text"
Hi, Iโm completely stuck. I have a PageController class that manages a stack of UI windows - opening them, closing them one after another, etc. Thereโs also a PauseHandler class that handles pausing: it plays the canvas fadeโin animation and pauses the game. Hereโs the problem: when I press the button to close the current window and return to the previous one, if thereโs a second window on the stack (for example, I went from the main window into the settings menu), closing that settings window also unpauses the game. Thatโs because I only allow unpausing on the main window, and shutting the current window fires both the close event and the pause event at once, so they coincide and unpause the game. With a gamepad thereโs no issue, since โBackโ is a separate button, but on keyboard both close and pause are triggered by Escape. The only workaround Iโve found is subscribing to the pause event before the close event, but that feels like a hack and has other pitfalls. Whatโs a cleaner way to solve this?
PageController: https://pastebin.com/fKRcF5QT
PauseHandler: https://pastebin.com/P9q86VYa
How to disable mouse control? I really just want it to not have input, like affecting which button is currently selected or beig hovered over or anything like that.
with the new or old input system? with the new one I'm pretty sure you can just call DisableDevice or something. with the old one you might just have to use a bool
Thanks for response. Using the new system I believe. But you got me on the right path I hadn't looked at my eventsystem which has inspector fields that let me easily disable clicking and pointing
Easy
Did I forget something?
m_OnClick.Invoke(position);gets executed, but it does not invoke the associated member function cause a "List.count" is 0,
public class Clickable : UIBehaviour, IPointerClickHandler {
[Serializable]
public class ClickedEvent : UnityEvent<Vector2> {}
// Event delegates triggered on click.
[SerializeField]
private ClickedEvent m_OnClick = new();
protected Clickable()
{}
public void OnPointerClick(PointerEventData eventData) {
if (eventData.button != PointerEventData.InputButton.Left)
return;
Press(eventData.position);
}
[Tooltip("Can the this be interacted with?")]
[SerializeField]
private bool m_Interactable = true;
public virtual bool IsInteractable()
{
return m_Interactable;
}
private void Press(Vector2 position)
{
if (!IsActive() || !IsInteractable())
return;
UISystemProfilerApi.AddMarker("Clickable.onClick", this);
m_OnClick.Invoke(position);
}
}
you dont need to do public class ClickedEvent : UnityEvent<Vector2> {} anymore you can just use the generic version directly
your question doesnt make sense though, if the event is called whats the issue here?
Ideally you will use a debugger to see what is actually happening post click event
OnDataAreaClicked is not called, despite m_OnClick being invoked. Thats my issue. Havn't had any luck tracking it with the debugger yet. Working on it
Oh well, I'll dig around more :3
If you have a breakpoint on the UnityEvent Invoke() call you can step into it and see where it goes (hopefully)
verify the subscription is still valid in inspector during play mode OR subscribe in code and ditch UnityEvent (for public event Action<Vector2> OnClick)
Oh, now it works. :3
anyone?
is there any way to run code immediately after the Start() step?
whats the usecase exactly ?
during Start(), all my actors (character, buttons, doors, boxes) call a function in the grid system to register themselves. I need the grid system to be able to run some code once all the actors in the level are registered
basically setting up the level, e.g. telling doors to update their state depending on whether the linked button has an actor on it
Could put it in update and then in that function set a Boolean to skip over it in the future
good idea
You could also have each actor tell a central manager that they are ready and when every actor has sent that you call whatever function or event
the issue is knowing how many actors are in the level to begin with
well the actors could initially tell the central manager via singleton on awake or the start of start?
I've never seen this callback in my life, and there's no documentation on it.
Is this thing safe to use?
Ya, 2018
Alright cool. What a useful method.
Doesn't even seem to execute at some strange time.
You just make a change to the transform and boom it's called.
In ProjectSettings/Player/Resolution and Presentation, what settings should I use if I want the game to always have 16:9 ratio, but be fullscreen?
Currently I'm using Exclusive Fullscreen and setting default width and height to 1920x1080, but the documentation says the default width and height are only applicable to Windowed mode? The documentation also says Exclusive Fullscreen is exlusive to windows, but when I tried on mac it worked and had the intended effect.
hey could i have somebody please help me with getting visual studio code setup so i can use it. I did what the tutorial told me to do with visual studio but say for example if i go to type "OnTriggerEnter" and press tab it does populate the script with private void OnTriggerEnter(Collider other)
Nvm good'ol youtube helped me out!
Is there a way to check if a reference is missing (specifically, if you set a reference, then delete the object without explicitly setting the reference to null in the inspector, it will display "missing") compared to if it is null? I only need this to work in the editor so if theres some editor API or reflection thats fine (although id prefer to avoid reflection) - what I could find online suggested (object)asset) != null && asset == null (where "asset" here is a UnityEngine.Object), but this still seems to log true when the reference is "missing" or null - the reason I want to do this is so I can know if an asset was deleted outside of the project after Unity recompiles and I can then look for its original path
That should work. Are you sure you did it properly? I'll go try it real quick myself, but it looks fine.
Huh... Its very possible I didnt do it properly, though I just discovered using asset == null && asset.GetHashCode() > 0 seemed to work well enough, if the reference is actually null the HashCode is 0, if its "missing" it still has a HashCode but the asset will still say null, which is interesting and I think may be useful for my case
If it's not assigned in the editor then it's still Unity Null
Yeah, what vertx said is what I forgot about. I did a similar thing with GetInstanceID() which is 0 if the object is unassigned. Seems to work ๐คทโโ๏ธ
Random note that GetInstanceID will be removed in a later version of unity and replaced with EntityID, which will have an index and version, so that hack will have to change ๐
Maybe the logic will be similar, who knows
Interesting change, huh
Eh, you can't future-proof it all ๐ If it's for your own project - it'll be mostly fine. If it's for an asset - meh. ๐ You could get .name and catch the exception and see what case you're on, but that's a lot more performance heavy and I'd not do. Also, who knows when will they decide to change .name to be something else ๐
(And of course you could do #if UNITY_VERSION_BLABLABLA to handle the different cases when need be)
Lol true, though that is interesting - atm its just for my own projects maybe at some point ill make a asset version if it all works out, good ideas as well - thanks for the insight from both of you ๐
!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.
Im having a problem, I need to install barracuda for this script
using UnityEngine;
using Unity.Barracuda;
using Unity.MLAgents;
using Unity.MLAgents.Policies;
[RequireComponent(typeof(BehaviorParameters))]
public class AssignModel : MonoBehaviour
{
public NNModel modelToAssign;
private BehaviorParameters behaviorParams;
void Start()
{
behaviorParams = GetComponent<BehaviorParameters>();
behaviorParams.Model = modelToAssign;
}
}
But if I do that it gives me 999+ compilation errors
It is really annoying. When unloading the scene, I face this error, it is about navmesh agent, "Stop" can only be called on an active agent that has been placed on a NavMesh.
I know the problem, it is because the ground is destroyed before the navmesh agents
The solution is that I disable navmesh agents before unloading the scene but it is messy and awkward
Looking for a good tutorial that will show how to use replace the Unity 3rd party starter asset character with a mixamo character
Maybe looking up how to import a Mixamo character in Unity should give you the knowledge needed to replace the starter character with your package - usually the actual mesh is a child that you can replace, then the animations are linked through the Animator which takes an Avatar (which links the bones of the mesh to the Animator so the states know how to manipulate them), the hardest part would likely be with setting up the import settings, which most tutorials should also show
Is this a good channel to ask for issues with Colliders and Raycast Hit registering in Unity2D??
if it isn't, we'll redirect you
the answer is probably yes, but we can't answer for sure until we actually see the question lol
Sorry, alright I'll ask:
I am very new to Unity2D this is my first project. I am trying to make a Balloon Tapping Game and everything is working okay except upon clicking sometimes the Shapes are not registering the click and instead it is passing through and the background is registering the mouse click. I am using RaycastHit to identify colliders to work it out but I cannot understand how to stop the Raycast passing through objects.
Show the relevant code and how the 'balloons' are set up
Also send the video in a correct format.
This is the issue where the 'Balloons' or the shapes need to be deleted upon clicking but sometimes randomly the clicks are passing through and the background is registering the click and taking the damage (see the final part where I am trying to click on the yellow square but instead of it getting deleted the health keeps dropping)
As for the code I have a Monobehaviour class that is spawning the different shapes of 'balloons':
And the individual balloon behaviours are their own different Component Codes. This is for the Triangle one that teleports:
public class PokaBehaviour : MonoBehaviour
{
public Vector2 minx, maxx;
public Vector2 miny, maxy;
// this basically makes a box
public float timegap; // teleportation time gap
float timeholder; // just a timer
Transform gameObj;
void Start()
{
gameObj = GetComponent<Transform>();
}
void Update()
{
if (timeholder <= 0) // time to teleport!
{
Vector3 newPosition = new Vector3(
Random.Range(minx.x, maxx.x),
Random.Range(miny.y, maxy.y),
gameObj.position.z
);
gameObj.position = newPosition;
timeholder = timegap;
}
else
{
timeholder -= Time.deltaTime;
}
}
}```
!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.
hey anybody knows how to make a simple map? It can be just a flat space with some blocks which i'll turn into buildings later
do I have to create a scene?
please don't crosspost
then where should I ask for anything
in a single relevant place
neither are you - it's a common courtesy to not spam
thats unnecessarily harsh
A tool for sharing your source code with the world!
This is the Spawner Code I have
And this is the individual behaviour code component
Why are the Raycasts passing through objects?
using System.Collections;
using UnityEngine;
public class Meteors : MonoBehaviour
{
public GameObject[] Asteroids;
private int currentAsteroid;
public Sprite[] brokenAsteroidone;
public bool halfGame;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
for (int i = 0; i < Asteroids.Length; i++)
{
float randomZ = Random.Range(0f, 360f);
Asteroids[i].transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, randomZ);
}
}
// Update is called once per frame
void Update()
{
}
IEnumerator ChangeSprites()
{
if (halfGame)
{
for(int i = 0;i < Asteroids.Length; i++)
{
int chosenSprite = Random.Range(0, brokenAsteroidone.Length);
Asteroids[i].GetComponent<SpriteRenderer>().sprite = brokenAsteroidone[chosenSprite];
}
}
}
}
I want to run a method outside of Update, so I tried using a coroutine, but you need to return in a coroutine. So where should I put 'return' in the "ChangeSprite" coroutine? Thanks
a coroutine is supposed to do something over time
your coroutine is doing everything all at once, so it being a coroutine is unnecessary
did you just copy the body of Update to the coroutine?
yeah
i dont really know coroutines all that much
this feels like an x/y problem
what problem are you trying to solve with making the coroutine
the goal is to have for loop change all the sprites in the list change to a list of sprites.
but in update it changes the sprites every frame, which isnt what i want
now im trying to wonder how to run a method outside of update or run a method but not every frame
my bad if its a dumb question im still not super advanced in coding
and when do you want that to happen?
when a bool is true, which in this case is "halfGame"
and you only want it to change on that specific event?
yes
so why not have that event also trigger the sprite change, rather than checking the sprite every time
instead of having the halfGame be public, make it a property or use a method that also triggers changing the sprites when halfGame is set to true
I've tested several values for foot speed, step size and step height, but it always results in this walking animation, where the legs don't move the same, and one leg gets stretched fully. Any idea for a better walking animation?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hi, I'd need some help from somebody who understands how rigidbodies work. I have made a game for my friends based on a real TV show, where you have to hit the bottom block off from a tower with a hammer without the above ones falling down. In the real show, these blocks have weight, and if the bottom one gets hit, the blocks above it dont fly upwards, or act like if they have no or little weight. They barely move. I have set their weight in Unity to a big number..but still. Any help is appreciated!
you'd probably want to also reduce friction and/or increase damping
You have gravity, mass, drag, friction, and force of the hammer hit to play with... it is not easy.
Oh okay, I'll check those out, thanks
also make sure ur moving the hammer using physic forces..
then its ur just finetuning all that was said earlier..
drag, friction (physics materials) all that stuff
Hello I'm having some trouble getting my UI to display properly. I'm trying to create the following
Outer (VerticalLayoutGroup)
|- Inner (HorizontalLayoutGroup) Should forcibly fill all of the width in outer and be max(min height, content height) tall
|- NameContainer (LayoutComponent) Should be 1/3 of the width of Inner
| |- Name (Text) Should be left aligned
|- Value Containuer (LayoutComponent) Should be 2/3 of the width of Inner
|- Value (GameObject) Should be aligned in ValueContainer and potentially cause everything to stretch to fit if needed
Currently I'm just trying to get Inner and the containers to properly display.
Outer has outer.childAlignment = TextAnchor.UpperCenter; and displays just fine if I child game objects to it correctly
However, I tried to do the following for inner (please ignore not explicitly getting components in my pseudocode)
inner.transform.SetParent(outer.transform, false)
inner.anchorMin = new Vector2(0,1)
inner.anchorMax = new Vector2(1,1)
inner.anchoredPosition = Vector2.zero
inner.childControlWidth = false;
inner.childForceExpandHeight = inner.childForceExpandWidth = inner.childControlHeight = true;
NameContainer.transform.SetParent(inner.transform, false);
NameContainer.flexibleWidth = 1;
ValueContainer.transform.SetParent(inner.transform, false);
ValueContainer.flexibleWidth = 2;
When I do that I get the attached image (the light grey is outer, the green is NameContainer, and the blue is ValueContainer and even though you can't see it both squares are sizeDelta = 100, 100)
When I inspect I see that inner has both anchormin and anchormax = new Vector(0, 1) and is anchored right.
- Why is this happening? What's causing it to override the anchors I gave it?
- How do I avoid it
I am working on an Endless Runner. For a new game I want to give the user the ability to choose a charactgr. I will have 4 Mixamo characters, 2 males and 2 females they can choose from. So I am guessing I am going to create something called like ThePlayer. I will set it up to use a default mixamo character. but if they choose a different character to use, I am guessing I am going to assign a different prefab to ThePlayer. All the animations will be the same so the only difference is the look of the character. Am I on the right track?
Your example isn't super clear but if you want to use flexable width/height correctly you should make sure preferred width/height is 0 explicitly in Layout element.
layoutgroups set their childrens' anchors
should probably ask this in #๐ฒโui-ux
thank you both i'll give that a go in just a minute. I didn't realize that i needed to be explicit on that to get it to fill
layout groups, images and text provide preferred width so you want to override it to make only flexible sizing be used
Does it work to have a static class with a UnityEvent or does that have the same problems as using a base C# event?
If the difference is only cosmetic, just have a Model gameobject which you can swap which is a child of "ThePlayer"
same problems? what problems?
If you subscribe and unsubscribe correctly there are no problems (e.g. when the monobehaviour is destroyed)
I always have problems with events.
such as?
this one
I'm trying to do the scriptableobject thing
Where you have your events be in a scriptableobject so they're decoupled
I'm not getting any errors but when the event gets invoked nothing happens and it says it has no listeners
but its still the same instance ID?
I don't understand.
remember that serialized event subscriptions are NOT the same as runtime subscriptions
Nor do I know how to debug it
How do you subscribe to the events?
Should I not be using a so if I don't care about serialization?
I don't need it to be serialized
UnityEvent can do both but otherwise just use event
I tried UnityEvent too, didn't work
e.g. public event Action MyCoolEvent;
public static void Bind(string eventID, Action action)
{
var gameEvent = Resources.Load<GameEvent>(eventID);
if (gameEvent == null)
{
Debug.LogError($"GameEvent with ID {eventID} not found.");
return;
}
gameEvent._onInvoke += action;
Debug.Log($"Action bound to '{eventID}' " +
$"({gameEvent._onInvoke?.GetInvocationList().Length ?? 0} listeners) " +
$"(ID: {gameEvent.GetInstanceID()})");
}
also, the "2 listeners" is unexpected
There shouldn't be 2 listeners
put a breakpoint to check the event before subscription. it should be null when it has no subscribers
It is null
this looks normal though so its probably user error
I think its something to do with me reloading the scene
Its managed code it cannot change in regards to a scene
unless you unsub or set the event to null elsewhere it will not be mutated by unity scene changes
So the listeners shouldn't be disappearing at all, right?
especially because its a C# event, not a UnityEvent
I dont expect the listeners to clear
Oh it could be the GameEvent instance was GC'd so each time you are "loading" a new instance...
because its just a managed class instance
you would need to load and keep it somewhere to get again later (e.g. dictionary)
So I see the GameManager initializes, it reloads the scene so it can put the game into the correct state (for the editor), then the game starts
read what i said above
Hm, you might be right
I will make a dictionary
so something like:
if(!events.TryGetValue(eventId, out var gameEvent))
{
gameEvent = Resources.Load<GameEvent>(eventID);
events.Add(eventId, gameEvent);
}
gameEvent._onInvoke += action;
yep thats exactly what i typed
But anyway this makes the use of a scriptable object pointless
could just be an Action or whatever created when first used
unless the SO has extra data required
I kind of forgot why its a SO
rando yt tutorial?
No I'm way past tutorial days
I've just never quite grasped how events work in unity
Dont think about unity, think about c#
its gonna work the same, its managed code that follows the same rules
just has some funny stuff relating to == null on unity classes for assets/game objects
I think the reason I wanted to use an SO is because I thought UnityEvent automatically removes dead references, doesn't it?
I don't remember what the SO part was for, other than holding the UnityEvent
the inspector made ones may do this because its all reflection based
otherwise code subs wont unless there are checks to specifically check the .target of the original subscriber
Hey! Thank you very much for your help :) Would it be possible to ask for the unity file you made? I am not an expert really and being able to see the code indirectly would help me out a lot. EDIT: FIXED IT, THANK YOU SO MUCH!!!!!
(perhaps your system can provide a UnityEngine.Object for lifetime checks?)
The problem with C# events is that they don't go away when you stop playing in the editor by default
so you get a memory leak
also applies in the game, too
a domain reload will happen eventually so thats not that bad
but you can use events to know when play mode ends
And during gameplay its YOUR job to unsub things that should not be subscribed anymore
well the usual fix for that is to use on OnDestroy or OnDisable
for a fully static class you can use the init on load things + events to know when playmode ends to clean the events
Ah right in a static class
anyway this is all stuff you can do but you just have to do it correctly
If you want it to be automatic and cool then it needs that functionality to be added
I'm just gonna keep it simple..
It felt stinky to just drop an event in my GameManager and be like "ok now everybody go ask the gamemanager to subscribe to this"
but honestly whatever for now
I remember why I wanted to use a SO now lol
Pain...
I wanted to be able to drag in game events into a component so I can set up what happens on an event in the inspector
<@&502884371011731486> off topic / potential scam
Hi everyone!
I got an error trying to automatically upload my .ipa to TestFlight through Post-build script (Unity Cloud Build (Build Automation)):
โFailed to generate JWT token: ErrorDomain=NSCocoaErrorDomain Code=-43
โFailed to load AuthKey file.โ
The file โAuthKey_<YOUR_API_KEY>.p8โ could not be found in:
โข /BUILD_PATH/.../private_keys
โข ~/private_keys
โข ~/.private_keys
โข ~/.appstoreconnect/private_keysโ```
In post-build.bash I tried the following two options but both don't work:
1 option:
```KEY_WITH_NEWLINES=$(echo $CONNECT_API_KEY | jq '.private_key |= sub(" (?!PRIVATE|KEY)"; "\n"; "g")' -c -j)
echo $KEY_WITH_NEWLINES > ~/.appstoreconnect/private_keys/AuthKey_${API_KEY_ID}.p8```
2 option:
```mkdir -p ~/.appstoreconnect/private_keys
echo "$CONNECT_API_KEY" | jq -r '.private_key' > ~/.appstoreconnect/private_keys/AuthKey_${API_KEY_ID}.p8```
In Unity Cloud Build (Build Automation) โ Advanced Options โ Environment Variables โ Variable value for CONNECT_API_KEY I indicate in the following format:
```{"private_key":"-----BEGIN PRIVATE KEY-----\nMIIEv...\n-----END PRIVATE KEY-----"}```
Please tell me how to fix the error? Is it wrong in my code in post-build.bash or the input format Variable value for CONNECT_API_KEY?
with unity 6.1 the editor im unable to get the editor layout as it was for facebook sdk
what has to be changed ?
it has to be something like this
same for game analytics as well
there's no login button
ongui should still work so must somehow be broken by some editor gui change
what can be done as of now?
is it because of editor?
make sure your not on the debug inspector mode and check if you have updated the sdks recently
otherwise I have no idea, there isnt an indication that ongui no longer works
why is this happening
will check
looks like you are maybe missing some packages or assembly references
I restarted my computer yesterday and this morning, Unity Hub is uninstalled.. What could have caused that? I can just reinstall it obviously but I'm confused
https://chatgpt.com/s/t_6862c71ec63c81919e7691bc24c871d4
I asked ChatGPT for general information about enemy behaviour to make it easier to create. Are there any crucial parts that ChatGPT is missing?
you should generally just not use genai for that kind of stuff
did you ever clicked the link? there was not code just information about what to do
i read your message, that doesn't change my answer
Are there any crucial parts that ChatGPT is missing?
A soul.
hello, i want to have a variable that can be used by other script but not inspector tied is :
private int money = 10;
public int GetMoney() => money;
the best solution ?
there's no best solution, there are several solutions
use a property not a method to expose it to other objects, it's basically exactly the same, but remove the () and you can treat it like a readonly variable in other objects
the typical approach would probably be public int money { get; private set; } = 10;
you could also (for example) use NonSerialized/HideInInspector on a public field
note that HideInInspector does not prevent it from being serialized, you'd want to use NonSerialized for that
ah, whoops
it seems like public int money { get; private set; } = 10 is what i'm gonna use, i don't rly like having a getter
i don't rly like having a getter
do you perhaps mean you don't like having an explicit getter method? because your auto property does have a getter, it's an implicitly generated getter method because that's what properties are
Yes i mean i don't like having 2 separate names it feels like a workaround that is very tedious with a lot of variable but idk it feels like it
That's what having an explicit backing field is and even with properties there might come a time where you would need an explicit backing field (for example if you need to add logic to your getter or setter you must use an explicit backing field)
for exemple here on my prefab i have 10 maxHp for my enemy when i change the script to 5 why is it still keeping it at 10 ? i didn't even touch it i thought it was when modified manually then the inspector become the reference
because it is serialized
what is the workaround for that ? I still want to change the hp in the scene but i want the prefab to follow the script
reset the component and it will go back to its default values
yeah ofc but it's a bit strange to do that everytime no ?
no, that's the whole point of serialization. whatever value is set in the inspector is applied when the object is created at runtime. the value in the inspector doesn't change just because you change the code because it has already been serialized.
it's a prefab ofc the script should matter more that the inspector it seems logic to me no ? Is there no shortcut to like reset every prefab or idk
but i didn't put anything in the inspector tho
" i didn't even touch it i thought it was when modified manually then the inspector become the reference"
you set the value when you first created the component with a serialized field
just because you didn't manually assign a value doesn't mean it didn't serialize the existing value
the value assigned in the script is just the default when you create a new component
it doesn't automatically change every existing instance of the component
So there is no way to force the variable to follow the script at the start of the scene but to still access it in play mode ?
you could just not serialize it
something like maxHP you probably do want to serialize though
i still want to access it in the inspector and i want it public to use in other scripts, googling this i found that i can Awake it to the good value, tedious but i guess that's ok
that would make it useless as a property then lol
why do you need to access it in the inspector if you don't plan to change it outside of play mode
everything would have the same max hp
it feels like you're trying to solve a problem that doesn't exist here tbh 
because i want to access it while in play mode ? I'm not sure i understand the question
whn they spawn yeah which is already the case but they will have the script maxhp and then i can modify one particular in play mode
i'm plrobably creating an inexisting issue
yeah you're just writing yourself into a corner with this line of thinking
but i like modifying the hp while in play mode but still want the script to work x)
hp should be separate from maxhp though
hp doesn't need to be serialized unless you need it to start at a specific point
So, I removed the code to create the procedural walking animation, and instead made it so the legs would instantly move to their new points (the points that the red curved raycasts hit, marked by the green rays) and discovered that the issue of the leg animation not being the same, with one of the legs being streched fully isn't a result of the animation code, but an inherent issue. Any help?
ok then let's say i want to have them not shown in inspector but still accessible via script what can i do ?
the thing we recommended..?
do you guys use unity cloud to store your repos?
it saves whatever you want it to save. the limit per file is 100mb I think? then there is LFS for bigger size per file.. Sure 3D meshes though I don't recommend storing big art asset files , If they are big and barely ever change I store them in a cloud service like google drive that gives more space for free/cheap
I can't modify it with another script like that no ?
I'd like to make camera animation from weapon animation I have. There's camera_bone. This code is just locking camera and rotate it full, but I'd like that it only "affect" to main camera and player can control his camera
private void HandleCameraAnimation()
{
if (_holder is ICameraHolder cameraHolder)
{
Quaternion currentBaseRotation = cameraHolder.GetBaseCameraRotation();
Quaternion animRotation = _cameraBoneTransform.rotation;
Vector3 animEuler = Quaternion.Inverse(animRotation).eulerAngles;
animEuler = new Vector3(
NormalizeAngle(animEuler.x),
NormalizeAngle(animEuler.y),
NormalizeAngle(animEuler.z)
);
Quaternion effectRotation = Quaternion.Euler(animEuler);
_playerCameraTransform.rotation = currentBaseRotation * effectRotation;
}
}
make the setter public or use a nonserialized field
I have a weird bug, I have a Sprite array added to a script that is added to a GO. it worked fine for a few weeks, it contained 4 sprites just set in the inspector (first element being null). but now when I want to add 2 new sprites to that list, the editor only remembers that the array size increased to 6, not the references to 2 new sprites.
the scene file doesn't change, so the change is not persistent. if I hit play, the newly assigned sprites disappear, (but the first 4 references are fine, it's just the last 2 become null). I can change references to the first 4 elements just fine, it's just everything after the 4th disappears and becomes null on play
I will try to debug tomorrow and try more things, but maybe someone saw this already? is this a known bug? I'm using Unity 6000.0.43f1
You may set the list size somewhere in script, or initialize the list inside script
not a known bug.
can anyone help me code a throwing baseball system with a glove that can catch it without closing your hand in vr
i dont normally code for vr but cant you just use OnCollisionEnter or OnTriggerEnter?
Why can I not make playmode tests? in either of these folders with these assembly definitions?
this is in an embedded package, which i see is supposed to work with the test runner?
Make sure the assembly has a UNITY_INCLUDE_TESTS define constraint
ok I added that but still no. It has been able to see them under 'EditMode' but the 'PlayMode' is as shown.
Is my test defined correctly to be recognized?
[UnityTest]
public IEnumerator PlayerInputSource_SouthWest()
{
PressDirectionalKeys(Key.S, Key.A);
yield return WaitForSmoothDamp();
AssertDirection(-1, -1);
ReleaseDirectionalKeys(Key.S, Key.A);
}
```Inside a class that extends `InputTestFixture`
Does the test fixture have [RequiresPlayMode] on it?
it seems that attribute does not exist in the version I'm on, which is test framework 1.5.1
Not sure, I'd restart Unity if you've not tried it yet
when I create a test assembly and a test script it looks like this and is recognized inside of the embedded package:
[UnityTest]
public IEnumerator NewTestScriptWithEnumeratorPasses()
{
// Use the Assert class to test conditions.
// Use yield to skip a frame.
yield return null;
}
is it because the class my test is in extends from InputTestFixture?
I will try right now, thank you
The docs mention playmode tests so I imagine it should work fine. Your class isn't generic or abstract is it?
ah restarting Unity worked, thank you. Perhaps it is a bit unstable, I am in unity 6.2 beta.
Always a depressing time when that's the fix 
when working with unity's spline package, objects usually follow the spline as intended. but if i set a gameobj to start following the spline's path during runtime, it starts to exhibit weird behaviour. it still follows the path, but it seems to use some sort of broken interpolation method instead of the expected spline follow method. has anyone experienced this before?
i should add that this only happens if there are no pre-existing objects affected by the spline already
have you tried restarting the editor or resetting the library?
i keep getting these warnings from dynamic water physics 2 plugin, and they are super confusing to me - what bindings are they talking about? why does the thing i have on the second image not work or count as bindings?
the input section in manual in question - i honestly barely get what's going on here :/
Did you read the "installation" section of those docs?
It describes exactly the situation with the missing bindings
The docs do seem a little vague
It's not clear how it's resolving which input asset to use, nor is it clear if the input needs to be in a particular action map or something
If you check the code that's emitting those warnings it should become a little more clear
i've done that (pasted it - seemingly correctly?) but it gives the same warnings
not really tbh, it's just this stuff
i tried logging the exception that is thrown and it is
To change the input settings use: Edit -> Project Settings... -> Input Manager
but like, the inputs are there in Input Manager
show a screenshot of the input manager
i also get this while in the editor
InputActionMap with path 'UI' in asset "Assets/NWH/Common/Scripts/Input/InputSystem/SceneInputActions.inputactions" could not be found. The Input System's runtime UI integration relies on certain required input action definitions, some of which are missing. This means some runtime UI input may not work correctly. See Input System Manual - UI Support for guidance on required actions for UI integration or see how to revert to defaults. UnityEngine.UnitySynchronizationContext:ExecuteTasks () (at /home/bokken/build/output/unity/unity/Runtime/Export/Scripting/UnitySynchronizationContext.cs:110)
possibly related?
That code looks like it's trying to use the old system
Are you sure there's not different code in the plugin for the new system?
what input backend is selected in player settings?
There you go looks like it's looking for a particular action map named UI
it's just the defaults, i haven't touched anything here
okay i fixed it, i went from "Both" to just "Input System" and for safe measure removed the already disabled InputManager scripts
thanks everyone!!! 
hello everyone,
I am trying to send a command in loop to my robot, using thread in background,
void ServojSendLoop()
{
float prevTime = 0f;
double interval = servojUpdateRate; // 0.008
while (keepSending)
{
double start = servojStopwatch.Elapsed.TotalSeconds;
float[] anglesToSend = new float[6];
float currentTime;
lock (angleLock)
{
Array.Copy(targetServojAngles, anglesToSend, 6);
servojAngleLog.Add((float[])anglesToSend.Clone());
currentTime = (float)servojStopwatch.Elapsed.TotalSeconds;
servojLogTime.Add(currentTime);
}
float delta = prevTime == 0f ? 0f : currentTime - prevTime;
servojLogDelta.Add(delta);
// UnityEngine.Debug.Log($"Sent angles: [{string.Join(", ", anglesToSend)}], dt={delta:F6} s");
prevTime = currentTime;
robotManager.SendServoJCommand(anglesToSend, 0.1f, 300);
// Busy-wait until the next interval
while (servojStopwatch.Elapsed.TotalSeconds - start < interval)
{
Thread.SpinWait(10); // Yield CPU briefly
}
}
}
It stays very close to 8 ms, but sometimes it fluctuates a little by 1 or 2 ms, is there any way to get absolute 8 ms loop time??
I'd go with "no", but I'm not 100% sure. Why do you need it to be that precise?
You can use system.timer but needs a sync object to ensure the event is invoked in the correct "thread"
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net-9.0
It could be better? not fully sure tbh
even restarting the pc doesn't help
I see, thanks
there are only 3 references which look like this: icon.GetComponent<Image>().sprite = gameObject.sthIcons[4]. even commenting them out doesn't help
what helps is just creating a new public Sprite[] sthIcons2 array, it's only the old sthIcons that's bad
and it doesn't even help commenting out the array completely, recompiling so that the script doesn't have the array at all, and only then adding it with references back in the editor
unless I use a new variable name
so for now I will just rename
looks like a bug, you may try to update your project to the last Unity3d version it could be fixed there
yeah I will try that. in any case the workaround is super simple, so it's not an issue
it's just... bizarre behavior
thanks for all the help!
Question about the life cycle of Scriptable Objects.
If I have created a Instance of a Scriptable Object and set it as a field on a MonoBehavior and the MonoBehavior is destroyed does that also destroy the instanced Scriptable Object?
No
oof now I have to redesign my entire game controller ๐
Well not the game controller but a sub system that uses it.
Sorry for the late reply, my robot needs this command at 8 ms, if the frequency changes it goes a bit nuts.
Thanks for reply, I tried it but it seemed less accurate than the current code i have
What kind of accuracy are you getting on desktop?
And do think about any costly operations you do that may be taking 1-2 ms
Otherwise you will want to have a queue of pre processed commands that is filled by another thread to minimise time between each cmd
i removed all the debugging and improved a lot, but the rest of the operations are costly but necessary.
preQueued is the way it is done generally with this robot, but i need it in real time.
I guess best case with that technique would be an 8ms delay
Only 1 of 2 public fields is showing up in the inspector. Idk why. All you need to know is that Registry inherits from ScriptableObject.
You are looking at the script default values, which is most likely not what you want. Put the script on something and you should see all of the parameters you expect.
It's a ScriptableObject not MonoBehaviour
Okay, then you'd need to set the variables on an instance of the SO, not the script file containing it
You probably want to use CreateAssetMenu
The weird part is why Sprite works but string doesn't...
Because it is an asset reference. And you're assigning default assets, not actually assigning values to variables on any instances
I wanna make my game available to modding, that's why i want it to work in the Inspector too. I couldn't care less about the inspector if not for that.
The inspector you are looking at is for the script file itself, not an instance of this SO.
You will need to actually create an instance of your SO to change the values on it
i see...
What you see here is akin to just doing = "SomeStringValue" on your string variable in the initializer
It changes what new instances will be created with
Since you cannot set an asset reference in code, it lets you assign one here. You can't see the string variable because you can just set that in the code
ok maybe im doing BS again becouse im new to SO's so i'm still figuring out how i could use it...
ScriptableObjects are scripts that define an asset you can create, like a prefab or a texture but just containing variables. You should be adding on a CreateAssetMenu attribute so you can actually create an instance of this SO that you can drag into a variable slot in some other component
print(PosX);
print(PosY);```
this snippet *should* get the position of the player, and set the posX and posY variable to the x and y position of the player respectively, and then print out the values of both variables.
What it instead does is set the player's position to 0, 0 and in return sets both variables to 0
What am I doing wrong here?
This snippet sets the player's position to PosX and PosY, then prints those values
I got that much, but how should I do this instead?
Or at least point me in the right direction
If you want to set PosX and PosY, you want to set those variables, instead of setting position
The thing on the left of the = is the thing that you are setting
Trying to play with properties again and I'm trying to get the property to fire off an event when another script tries to assign a value to it like so.
public int currentHP { get { return currentHP; } set { currentHP = value; onUpdate?.Invoke(Stats.CHP); } }
I already know this causes a StackOverflowException because it's effectively stuck in an infinite loop, but I don't know how to design this in a way that doesn't invoke an infinite loop
Make a variable that holds the value, then use the property to read and write to that other variable
Like so?
private int _currentHP; public int currentHP { get { return _currentHP; } set { _currentHP = value; onUpdate?.Invoke(Stats.CHP); } }
You would also want to return the variable in the getter
Ah, you edited it just as I sent
Yeah, forgot the underscore
I know that instantiating a canvas per gameobject is bad performance wise
but, if I wanted to create an hp bar above enemies
but make the hp bar a child of the enemy GO
what's the best approach?
What do you mean "a canvas per gameobject is bad performance wise"?
Is this something you profiled?
I read it somewhere
that if u have many enemies in a scene, and each enemy will have their own canvas, it will be bad performance wise
If you have enough enemies, with or without a canvas, it'll be bad performance either way.
Profile it and see if you have a performance issue. Especially before going down a rabbit hole of a harder solution because you read it from someone who read it from someone who read it....
you can always deactive the canvas object and only activate it when needed
works wonders
and unity handles a shit ton of enemies pretty well
as long you do it right
personally what eats away the performance is meshes and textures
make sure your enemy animations are baked and meshes that dont move are static
you should be fine
if its a 2D game then ignore what i said
Hi, trying to create a loading screen using a coroutine and unity Android. However the next scene doesnโt load?
Show code
Itโs literally just an IENumerator Start()
{
Yield Return new wait for seconds(3)
SceneManager.LoadScene(โMain Sceneโ);
}
Canโt take a photo, havenโt got discord on the computer ๐คฃ
Well for starters the capitalisation of the code you shared is wrong. This is why we need to see the exact code and what errors you have in the console
My best guess right now is that Main Scene is not added to the scene build list
Or itโs added but itโs not called Main Scene
Iโm on discord on my phone, using a college computer ..
Thatโs the best I can do, sadly. Iโm so confused.
And I canโt help without more concrete info
Is loading manager attached to a game object?
Yes.
Well what does the console tab say ?
Mate, itโs a college computer without discord.
you can access discord via any browser
Itโs blocked.
go to discord.com/app in an incognito or guest window or something
damn, that's unfortunate.
Yes, it is.
really should find a way to share actual screenshots or code then, it gives us a much easier time helping you
Yep, I know. If I was at my computer at home I would. However that isnโt the case, Iโve searched online for answers, forums etc and now I find myself in the Discord because I havenโt found an answer. Iโm working with what I have.
have you checked to see if the code is actually being reached? ie having a Debug.Log at the start of the method
Are you doing any timescale manipulation anywhere
If your timescale is 0 this will never finish
Yes, it logs.
ok, what about after the Wait?
Yep, it logs. It just doesnโt go to the next scene.
what if you rename the scene to not have the space?
and update the load call as well
If it gets to the log after the wait the only thing that'd be preventing a scene from loading there would be an error. Are you sure you haven't hidden errors in the console
how do I get the position of another object to be referenced in a script?
get a reference to the other object and get its transform.position
I think ive tried that but I want to use the x and y positions for PosX and PosY variables respectively
oh wait I should probably move code beginner
ok then get .x and .y
transform.position.x?
yeah
oh
is there a way to make an infinite array?
a list?
actually it doesnt need to be infinite, it just needs to automatically add things
i thought those were the same thing
so basically, I have a script that gets the position of the player every frame, and i want to make a list of all the x positions and all the y positions it has
you have to do that
you said it needs to automatically add things
you need to write code to add things to it
well yeah, but i want it to add the new position of the player to the array/list whenever it gets a new position
I can't type out all of those positions
if(oldpos != newPos)
//Add To List
unless an int vector positions will probably never match so you need to use an approximate comparison
vector3 already uses approximate
Huh you are right
public static bool operator ==(Vector3 lhs, Vector3 rhs)
{
float num = lhs.x - rhs.x;
float num2 = lhs.y - rhs.y;
float num3 = lhs.z - rhs.z;
float num4 = num * num + num2 * num2 + num3 * num3;
return num4 < 9.99999944E-11f;
}
TIL
i had a discussion about this not really being applicable sometime ago
how do you mean?
I see.. yeah its very much depends also how you're using it too.. I wouldn't rely it on it for big things, for my uses it was always okay so yeah something you'd want to keep in mind for sure
There is a problem when using skeleton root motion. I use native spine system to play animations.
Imagine, for specific animation, I wanna enable root motion and after finishing it, disable it.
The problem is when disabling the root motion and play the next animation (non root motion), the character snaps back , how can I resolve it?
To enable/disable root motion, I write the code below
_skeletonRootMotion.enabled = isActive;
I see the fields X, WorldX and Ax skeleton are not zero but by setting them to zero does not solve the problem. In the next frame, the values change to non zero again and smoothly moves to zero!
Anyone here have a good grasp on quaternions? I have to work with rotations so much but barely understand how the system works, I just know multiply something rotation by another rotation basically adds it
The general rule is: If you find yourself ever reading or writing to an individual component of a quaternion - don't.
if you want to learn how they work: https://eater.net/quaternions
Its usually enough to construct them from Euler angles and to know how to multiply them together
And if you don't know how to multiply them together, just multiply them the other way around ๐
haha yep very true
Sorry, maybe I'm dumb and I don't fully understand how inheritance works, but this:
foreach (var thingObject in ActiveThings)
{
if (thingObject.TryGetComponent(out Thing thingComponent))
{
thingObject.GetComponent<Landmark>().ChunkId = (10, 0);
Debug.Log(thingComponent.ChunkId + "ChunkId From thing");
PackYourThings(thingComponent, thingObject);
}
}
Always print 0 0 (the default for an int,int tuple) instead of the value I am assigning to Landmark, which inherits from Thing. So, if I use GetComponent (TryGetComponent) on a component that a GameObject doesn't have, but does have a component it inherits from, it returns an empty object for some reason?
Worth noting that thingObject does NOT have a Thing component assigned, ONLY Landmark. Also, ChunkId is ONLY declared in Thing, not in Landmark.
If you're trying to set the value on thingComponent, you should use that instead of another GetComponent call.
The GetComponent call is only for demonstration.
Does the object in question have multiple components of type Thing
No.
The problem is that I set the value inside of Landmark earlier, but when I do TryGetComponent, which should return Landmark, since it inherits from Thing, but instead it returns an empty Thing.
Or so it would seem.
Maybe show the inspector of one of the objects in ActiveThings
if (thingObject.TryGetComponent(out Thing thingComponent))
{
Debug.Log(thingObject.GetComponent<Landmark>().ChunkId + "ChunkId From thingObject");
Debug.Log(thingComponent.ChunkId + "ChunkId From thing");
PackYourThings(thingComponent, thingObject);
}
Here is a better example.
Correction. Yes.
Cheers!
I was inheriting Thing on another class for no reason.

Hi I was wondering does anyone have problem when rotating with player or moving it feels like it is sturreing a little bit like the objects them self.
Me using rigidbody for movemnt, yes rotation of camera point is in late update and actuall camera that is following rotation and position of that object is also in late update and rigidbody is set to interpolate
this happened to me before, but i don't remember what was the issue exactly
i would advice the following:
- comment any other code that's related to player movement/camera and test the looking around with mouse ALONE first
- listen for input in Update, apply the actual movement in late update (i think this was my issue)
should movemnt be in fixed update since it is physics
rigidbody movement? yea ideally
yes. Like movemnt is in fixedeupdate, keyboard input in update and camera rotation in late update
but it is more camera point and player that are rotating
actaull camera is not a child object
it is just following camera point
yeah usually how its done
for camera I only used Cinemachine when it was following the player instead
but yeah lateupdate I think is usually where to add cam
how are you doing the movement exactly?
hopefully not using translation lol
what do you mean by this
actual code that does the movement... specifically wondering if it's using rigidbody.position, MovePosition, AddForce or velocity, or perhaps still doing transform.position
just camera.position = camerapoint.position
camerapoint is child of player
camera itself seperate object
Thanks m8
this also seems reasonable... can you record a video of the problem?
Iam getting an error on this line
transport.SetRelayServerData(new RelayServerData(allocation, "dtls"));
It says "The type or space name 'RelayServerData' could not be found (are you missing a using directive or an assembly reference?)
https://paste.mod.gg/stzyavyogqxz/0
A tool for sharing your source code with the world!
I can't find where this error is stemming from
Are you missing a using directive?
Does your IDE suggest anything
I shouldn't be, the error occurred after i tried using the older Lobby and Relay packages with the Multiplayer one. But I deleted the older ones, reinstalled the new one, and regenerated project files, and it is still ongoing.
Hello Everyone, I have installed Unity Hub and I have installed the latest Unity Version, it is Unity 6 and some other numbers, anyway, I have created a project but when it loads a bit it crashes
What namespace does the documentation say RelayServerData is in?
Check the editor !logs . They should have a crash report
I did but nothing
Nothing what?
I don't see error codes
But I tried forcing Unity with OpenGL and it did work
from what i can find its in here, using Unity.Netcode.Transports.UTP;. Which i do have in my project.
https://docs.unity3d.com/Packages/com.unity.transport@2.0/api/Unity.Networking.Transport.Relay.RelayServerData.html
Documentation says it's in Unity.โNetworking.โTransport.โRelay
Do you know which package this would fall under?
its says unity transport
which i have, but the code is not working when i try to use Unity.Networking.Transport.Relay
iam unsure how to apply this to my code to get RelayServerData to work.
What version of the package do you have?
2.5.2
Try deleting library folder perhaps
after deleting it do i have to do anything other than run the project again?
Nope. Just run the project.
alraight iam going to give that a try then
error still persists
Then you're either missing a namespace or using assembly definitions and missing a reference.
iam 99% sure iam using the correct name space
Which is?
this "Unity.Netcode.Transports.UTP;" since "Unity.โNetworking.โTransport.โRelay" falls under it
I don't see Unity.Networking.Transport.Relay in the code you shared
I'm not sure what you mean by since "Unity.Networking.Transport.Relay" falls under it
i had gotten confused, its seems like it exists in both, the one iam trying to use is the one that's in Unity.Netcode.Transports.UTP. https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.7/api/Unity.Netcode.Transports.UTP.UnityTransport.SetRelayServerData.html
That's a totally different API though. Not the type you said you have issues with.
yeah i had gotten mixed up on what the relay i was calling was. This is the one iam trying to use (the link i sent) and the one that is not working.
i tried to follow this from unity https://docs-multiplayer.unity3d.com/netcode/current/relay/#how-do-i-pass-allocation-data-to-my-transport
With Netcode for GameObjects you can use an IP address and a port to connect a client to a host over the internet. However, using an IP address to establish a connection doesn't always work. Instead, you can use Unity Relay to initiate a connection between multiple clients and a host.
they have one small change to make it
transport.SetRelayServerData(new RelayServerData(allocation, connectionType: "dtls"));
but the issue still persist where it says namespace name RelayServerData could not be found
Well, they don't show what namespaces they use, but they likely use the one we mentioned earlier.
when i try to use the one we mentioned earlier it does not work with their code, saying
Severity Code Description Project File Line Suppression State
Error CS1729 'RelayServerData' does not contain a constructor that takes 2 arguments Assembly-CSharp J:\Unity chess\My project\Assets\Scripts\NetworkUI.cs 51 Active
and if i use the code they have for the relayserverdata i get this
Severity Code Description Project File Line Suppression State
Error CS1739 The best overload for 'RelayServerData' does not have a parameter named 'connectionType' Assembly-CSharp J:\Unity chess\My project\Assets\Scripts\NetworkUI.cs 79 Active
also earlier in that same page they are using both
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
in one of the other pages in that same section
still have not been able to get anywhere with this
i have been able to figure out that this code works, but idk how to integrate what i need onto it
public async Task<string> StartHostWithRelay(int maxConnections, string connectionType)
{
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
var allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections);
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(AllocationUtils.ToRelayServerData(allocation, connectionType));
var joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
return NetworkManager.Singleton.StartHost() ? joinCode : null;
}
and it only works because its avoiding RelayServerData
which using Unity.Netcode.Transports.UTP; should allow me to use
It seems to me like this guide is outdated and wouldn't work correctly with unity 6. If you follow around some links on how to set up the relay packages and stuff they mention that it is deprecated in unity 6.
It also feels like you have several packages installed that are not meant to be used together or have version incompatibilities.
Hi all, I just started throwing together an isometric game in Unity and made a point of using pure 2D w/ sprites rather than a 3D environment with an orthographic camera at an isometric angle. I'm currently just starting out with the basics: taking a Cartesian coordinate and converting it into an isometric coordinate and backwards.
I can spawn a grid of tiles with a given width and size ratio (so this isn't strictly isometric, as my tile sprites are a bit steeper than the expected 30 degree angle). However, when I use my inverse transformation method to figure out which tile the mouse is hovering over, I notice a strange distortion that seems to increase the further away I get from the center of the screen. I've tested this with properly isometric tiles and it still failed to work, so I believe the error doesn't come from the fact that the tiles are dimetric.
My conversion methods can be found here. https://pastebin.com/uxDJJQj1
In case it becomes relevant, the code for testing the hovered tile is here. https://pastebin.com/rEnQVD2x
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
hey guys, so i am a beginner to making games on unity and i came across some random issue that shouldnt happen?
void FixedUpdate() // Check for the current states of the player.
{
// All states being checked.
if (isJumping)
{
print("Player is jumping.");
rb.AddForce(new Vector2(0, jump_power), ForceMode2D.Impulse);
isJumping = false;
}
if (isFalling)
{
print("Falling");
}
if (isMoving)
{
rb.AddRelativeForce(new Vector2(x_input*movement_speed,0), ForceMode2D.Force);
print("Player is moving.");
}
if (isGrounded)
{
print("Player is grounded.");
}
}
And it has to do in the "isMoving" part, where if i made it using linearvelocity or addForce or addRelativeForce, the character just does not move at all even though with the same code it used to move the character with no problem. everything else like the jumping works And all the prints get printed out
i was using linear velocity at first and it stopped suddenly and switched to addforce, then while working on a way to set a limit on the force it also stopped working
now both stopped working even though i would revert to the exact same code
Original linear velocity to move:
rb.linearVelocity = new Vector2(x_input * movement_speed, rb.linearVelocity.y);
print("Player is moving.");
ok i fixed the problem somehow?
printing the "movement_speed" it is changing from 5 to 0 when i never ever changed the value
the only time it gets changed is in the unity properties itself because it is [SerializedField] float
but not once in code, now i put an integar instead of the variable it works fine, i have no idea why
You would have to share your full script (including any logging code) for us to make sense of what you're talking about here.
yeah no need i found the actual problem actually
turns out i inserted the script twice in my player
which explains why i had 2 different values for the movement speed
it works completely fine now ๐
Hi! I have a question regarding the order of operations
string result = "";
int a = 1;
int b = 2;
result += a * 2 + b```
What will be the result string? "4" or "22"?
And if it's 22, will () around the math fix it to be 4?
4 i believe. the += is in charge of turning your value into a string
easy to test though ๐
You're right ๐ Would the same apply if it said =?
i used this when do a post api call
cs UnityWebRequest.Post(uri, jsonData)
but it said this is obsolete? and recommended me to
cs using (UnityWebRequest webRequest = UnityWebRequest.PostWwwForm(uri, jsonData))
which isnt sending object as json anymore but in this thing: application/x-www-form-urlencoded
is there something else to use or i should ignore this obsolete
And how would that work if it said += a * 2 + b + "."
Is "math" always preferred over adding strings?
not sure in that specific usecase but in general the way types implicitly convert other type values is via "overloading" those signs like != and ?= so the order of execution will be handled with that in mind
eg. maybe imagine this as
result.UpdateValue(a * 2 + b);
I see. Thank you ๐
the docs doesnt say .post is obsolete i guess its just editor thign and ignore it
The parenthesis are grayed out, so I assume it doesn't matter @night harness
remember this counts for the + too (though im not actually sure which value is in charge of that here, i know it does end up as a string)
result.UpdateValue((a * 2 + b).UpdateValue(".")) (i added parenthesis because they will implicitly be there due to being on one half of the + were the other half is a different type(?))
hopefully im right on that ๐
There isn't anything special about the += operator in this case, the order of operations is determined by the operator precedence. += has lower precedence than * or + so it applies last. https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=msvc-170#precedence-and-associativity-of-c-operators
Why is there another 'apple' script in the Solution? How do I get rid of it?
Do you mean the meta file? That should be there. Meta files are generated / used by the Unity Editor internally to track references to the asset and more (https://docs.unity3d.com/6000.1/Documentation/Manual/AssetMetadata.html)
I assume they mean this part
I'd right click to view the file in the explorer
see what folder opens for apple.cs and Apple.cs
Nvm, Unity didn't update the metadata yet. I just reset it
its the c# file
I see apple and Apple
I renamed the apple file to uppercase, but the engine didn't update the project file immediately
unity and vs are weird with file modifications sometimes
ive renamed files in VS, only for unity to switch them back the moment I go back to the editor
I think its also happened when I deleted a file that then reappeared moments later
I think making new .cs files within Visual Studio also confuses unity. I get why it confuses unity, but its annoying as it can often be more convenient to make a new file in VS with a simple hotkey, than it is to go back to unity to do it there
Unity is in control of the solution/project files so when it reloads it will re generate.
Making a new cs file should work fine in visual studio, i use the "move to xx.cs" option all the time just fine.
operators have 2 properties in this regard, precedence and associativity
precedence governs the order in which different operators are applied
associativity governs the order in which the same operator, or different operators with the same precedence, are applied
+ is left-to-right associative so (a + b) + c and a + b + c are strictly equivalent
What does it mean half-size? Horizontal or vertical?
It's the height
it's half the height*
please don't crosspost
Thank you for your help! I was able to find a way to make it work, hit another wall though where using the relay system from unity i make a code but the other device, when trying to connect, says code not found. On the unity dashboard i can see the original session being made though.
hi, i have a problem, i hava a nav mesh agent that stop in front of a door when exist a wall to pass throught it, how i can solve it. If i instantiate another enemy, the new one can pass without problems
Might be better to ask in #archived-networking to be honest.
gotcha, thanks for the help!
Hi, does anyone know know good way to have like solid in air movment
I was tryinfg just to add force in direction that I want to move with forcemode.aceleration but just little bit so game does not feel to stiff(I dont want that full in air controle but just to be able to movve little bit so game is nto to stiff)
but then second jump is way to strong
Bump.
lots of ways you could do this @vapid merlin. not sure what you mean by "but then second jump is way to strong" but if you want to keep control of the player in the air you could have an "inAir" multiplyer to your speed and if you are not touching the floor you multiply it by that amount. You could check if they are in the air in multiple ways , raycast, boxcollider or sphereCast depending on how you wanted to do it.
Sounds like youโre looking for counterstrike movement, has momentum, you can very slightly change it in the air sideways
yes
I mean if I jump right for example it has very slighy change for other directions
and so on
but my method makes second jump way to big
is there no UnloadScene Synchronous that isn't deprecated?
they deprecated all the sync unload calls and slapped a note in there to say "well just use async"
Anyone here with knowledge about Handles, EditorWindow and color?
am having a problem with drawing, in the code I use the same Color for the DrawAAConvexPolygon() and DrawSolidArc(), yet they differ in color.
Handles.color = new Color(color.r, color.g, color.b, color.a * color.a);
Handles.DrawSolidArc(pointA, Vector3.forward, startDir, 180, radius);
Handles.DrawSolidArc(pointB, Vector3.forward, -startDir, 180, radius);
Handles.color = new Color(color.r, color.g, color.b, color.a);
Handles.DrawAAConvexPolygon(
new Vector3(pointA.x, pointA.y, 0) + startDir * radius,
new Vector3(pointA.x, pointA.y, 0) + startDirR * radius,
new Vector3(pointB.x, pointB.y, 0) + startDirR * radius,
new Vector3(pointB.x, pointB.y, 0) + startDir * radius
);
oh sorry, my mistake
Hi, im new here. What channel can I ask a question relating to the Unity game engine itself. Im currently having an issue where my friend can't download a build of my game because it's getting flagged as a virus. We have tried turning off safe browsing in chrome and turning off his windows security and it's still getting flagged for some reason
#๐ปโunity-talk for general questions related to topics not specifically covered by other channels
Thank you
{
if (Vector3.Distance(transform.position, player.transform.position) < fov.viewdistance)
{
Debug.Log("1");
Vector3 dirToPlayer = (player.transform.position - transform.position).normalized;
Debug.Log(Vector3.Angle(transform.up, dirToPlayer) + " < " + fov.fov / 2f);
Debug.Log(Vector3.Angle(transform.up, dirToPlayer) < (fov.fov / 2f));
if (Vector3.Angle(transform.up, dirToPlayer) < (fov.fov / 2f));
{
Debug.Log("2");
RaycastHit2D hit = Physics2D.Raycast(transform.position, dirToPlayer, fov.viewdistance);
Debug.DrawRay(transform.position, dirToPlayer * fov.viewdistance, Color.red);
if (hit.collider != null)
{
Debug.Log("3");
if (hit.collider.gameObject == player)
{
Debug.Log("I SEE YOU");
}
}
}
}
}```
So this code seems to be written correctly, but i get this wonderful debug message. it states that the equation comes out false but it goes through anyway. any tips?
pay attention to the warnings in your IDE
there is a sneaky ; behind your if statement
What is the simplest way to have a mask that only makes rendering OUTSIDE of itself possible not inside
Both the mask and the masked object are custom graphics components already - I'm looking for a component analogous to mask but called inverse mask or something
Is there a package for this?
You can invert the image and it will show the outside I think this is is the simplest way
Or you can wait until Unity Team add the invert option for mask ๐
You can also write shader with 2 texures of same size and setup to render second texture if dot of first texture is not transparent or if dot is transparent for Inversed version it is not hard
Flipped textures and custom materials aren't an option, it's a custom graphic component with a custom shadergraph canvas material on it
it doesn't even have a proper texture on it at all, it generates its own custom mesh and I'm a bit too stupid to figure out the code inside it XD
yeaaah I don't think that's happening lmao
I'm trying to figure out how to change the stencil write mask in a shadergraph shader right now
if I figure that out I think I got it
Why "Flipped textures and custom materials aren't an option " is not an option just open in Photoshop select all transparent part with magic wand and press invert selection and then fill it white color
you didn't read my whole message did you?
there's no texture to edit
it generates its own mesh
it's a custom MaskableGraphic
Didnt you need the sprite for mask?
the generated mesh is used for the mask
figuring out what the generation does and reversing it is a last resort I really dont wanna do
flip the mesh in this case if you know how to generate mesh it should not be hard to generate inverted version
point is - it's not my code. I don't know how to flip it properly
I don't want to mess around with that unless I really need to
as I said, figuring that out is a last resort
I do not understand how u masking the mesh?
Or u use it as Rawimage the only way i supose
If you really need I can write shader for you, but will you be able to set the texture of your generated mesh into custom shader material?
I'm not using rawimage. I'm using a custom component deriving from MaskableGraphic
you'd need to modify an existing shadergraph shader that does some helper stuff
Is it contain shader code?
it's a shadergraph shader
so not sure what you mean
Do you have shaderName.shader file in project? where ShaderName is not necessary much shader in material path
I do not sure shader graph generate the shader but I think it should generate the shader cg file if you have it I can try to modify but I never worked with shader graph only with cg.
There is the simple shader work like this:
Hey there, I needed to learn how to add ads to a mobile game in unity6 but the guides I find online all seem outdated. Can anyone help me with that?
You need to decide on a provider, then dig into it's documentation
Also #๐ฑโmobile
Hello, I have a question on how I can replicate the cloud shadowing just like this video. https://youtu.be/_uxV9R3JrXo?si=5NQowkQuJUrh4ev9
To me, it seems like itโs two layers of clouds that are casting shadows at a different intensity, and when they overlap each other, the intensity of the shadow gets darker. (I could be wrong)
Date of Recording: 2020-10-17
Building a cloud shadowing engine which is consistent with the pixel art aesthetic poses some unique challenges:
- A purely screenspace approach looks great, but does not behave consistently when the camera perspective changes
- A purely worldspace approach is stable to camera rotation, but looks artistically in...
if anyone has the time, can you see why in this code, my black pieces on the client side do not detect each other? For the life of me, I can't figure it out. I was just able to fix the white pieces' movements being out of whack, but the black pieces still only detect white pieces, allowing them to be moved to other black pieces' locations and eat them.
https://paste.mod.gg/zgtxxidflcif/0
A tool for sharing your source code with the world!
and some of the white pieces can still move in ways they shouldn't, like one piece can detect it can't move somewhere when there is one of its own but some of them can still do it
its very odd
#archived-networking. though you'll want to narrow down what part of this is code is relevant when moving this to that channel. thats a lot of code to go through without even knowing what part is related to detection
that truly is some code though. I dont think id recommend to be doing multiplayer at the moment either
Yeah its definitely all kinds of messed up at this point. I have been gutting it and reworking it for the past 2 days trying to get online to work. i have a working single-player built, and for some reason thought online would be easy to implement for peer-to-peer connection. I will see If i can try to pinpoint excatly where this is failing.
Why is the class called chessman ๐
If the client does not own the black pieces, possibly thereโs some functions it doesnโt have access to that detect if a space is available? Or possibly the client isnโt being updated with positions locally, and the host is. Thats a lot of code to look through buddy haha
has anyone found a way to reduce Unity's long compile time?
currently unity opens up very fast, but it takes around a minute to compile my code. it's a really long time.
I see online people saying it takes them less than a few seconds. how???
I am already working with asmdefs. and reload domain is disabled
Make sure the project is on an SSD and you're using a fast CPU with a lot of cores. That's all you can do, really 
Domain reloads always happen after compilation, no matter what, and reload all the code in your project. So the more packages you have, the longer it takes. Doesn't matter if the assembly was recompiled or not.
One additional thing you can do is to avoid using editor callbacks like OnValidate that get called a lot, and keep anything triggered in enable/awake very lightweight. This doesnโt do much initially but can become noticeable in larger projects
it is, I am on a new pc so I should be good
I also disabled domain reload, my code can handle it. It still takes a long time to recompile.
it takes an entire minute to post process il for assemnly csharp editor - sounds like il2cpp? which is wild since I use regular mono
I beleive mono has faster build times
I don't use onvalidate at all :/
Disabling domain reload only disables it when entering play mode, it's not optional after compilation.
And no, that's not IL2CPP. IL2CPP is only for builds.
so what could be taking so long? is there a way to debug compilation?
Have you restarted the editor recently? Sometimes you can have some form of (memory) leak that makes reload progressively take longer.
just restarted, still takes a while
You got a good PC?
Yea, new gen cpu, 32gb ram
I started working with live editor reload (hot reload?) for playmode and for the editor. So far so good
post process il for assemnly csharp editor sounds like an entities thing
