#archived-code-general
1 messages · Page 443 of 1
kinematic rbs don't check collision yeah
if there is no in-built way to check for collision while rotating, kinematic or not, then I think I can just make it work with character controllers
cause that's the main problem for me
do the 2 methods you mentioned not work for dynamic rbs?
whta do you mean?
if you mean
does a dynamic rb check for collision while rotating
answer is no, which I just learned
I thought only non kinematic behaved like that
so in fact, I can keep using my char controller as I have no disadvantages
afaik it should...? odd
do you have interpolation on and collision continuous
I ditched the rb long ago so I don't remember what I had
Chatgpt said that neither kinematic nor dynamic rigidbodies have collidion checks while rotating for what it's worth
I checked at least for a kinematic rb and it was true
But I don't want a dynamic rb as I don't want to be pushed around by forces
don't trust chatgpt for anything lol
just don't use forces?
I just said kinematic didn't collide with moverotation, I tried
@unkempt meadow i checked multiple other reputable sources online
dynamic rbs do have collision when moved with MovePosition or MoveRotation
seems like it's just that those 2 methods force the rigidbody to move regardless of those collisions, kinda expecting other stuff to move instead
you could either use forces or set the velocity to have it also obey the collisions
yes, it's not supposed to. but dynamic does
but you said not to use forces? Isn't that just a kinematic rb?
no
"not using forces" is just.. not using forces
don't use AddForce, disable gravity, disable damping, freeze rotation, whatever
I thought you could just disable gravity with a dynamic rb
you can
ooooooh
that's what i'm telling you to do
so if I use a dynaamic rb and NOT move by addforce/velocity/etc and instead use moveposition
and moverotation
"disable gravity" would just be setting the gravity scale to 0 for example
it will work?
they will collide and you can check for that, but afaict it won't obey the collisions, it'll just move through
no, there's a 3rd option
yes?
you could either use forces or set the velocity to have it also obey the collisions
these are the 2 methods that let the rb respect collision
you said you don't want the former, have you tried the latter
set velocity?
not sure if I did
eh more like have you considered that
since that doesn't seem to be on your mind lol
and does set velocity not use forces?
it just directly sets the velocity
so no bouncing and jiterring around?
i mean having everything work correctly relies on.. well, everything, so i can't guarantee you did everything else correctly lol
but it's not gonna cause issues in itself
and I would need to add torque for my rotations? that sounds like a force-y thing lol
there's an angularVelocity member too
aha
I will look into it
if set velocity and angular velocity respects collision but doesn't forcefully bounce my character around, it solves my problems
btw I wouldn't use gravity, I assume that won't have an effect
gpt says this:
❌ Rigidbody.angularVelocity (and torque-based rotation) does not respect collisions during rotation.
Let's check that
just stop using it tbh
it causes far more harm than good
yeah it lies but it can be useful
the problem is I can't ind anything on the entire internet
on rotation and collision
probably cause it's not a normal use case
if you can't find anything on the entire internet how is chat gpt gonna help 😛
true? But also, why does it confidently say shit then?
because it's built to tell you a good answer to your question, not a correct one
sometimes a good answer can be made by being right
so is it right? No one knows 😄
I think I even tested it and it didn't work but I can't remember
my point was that if there isn't an answer for you without chatgpt chatgpt can't be right
because it just leeches off the same resources you have access to
I understand what you are saying
but google is shit
sometimes I found correct answers while not finding them by googling
I treat chatgpt as a faster and SOMETIMES better google
when I'm looking for something niche and specific, I will always check google first
i found plenty lol
no it's very much worse lol
is it even faster lol
it is sometimes. And it's excellent for debugging, you have to admit that
it absolutely is not 😂
sometimes when you make stupid errors like GetKeyDown instead of GetKey, it immediately identifies them
so what exactly did you find?
those should be the first places you check to debug anyways
if you're looking for "does angularVelocity respect collisions", i mean, those 2 things are unrelated
angularVelocity doesn't care about collisions, it tells the rb to move in a certain way, but it probably doesn't force the rb to, just like velocity
so the rb respects collision as a result
That link said to use add torque and I do remember trying that and I think it uses forces and spins you around
It didn't say anything about angular velocity specifically
forces make the movement shitty
spins it around
jitters it around
bounces it
I tried forces and it was terrible
ok.. sounds like you didn't tune them and you blame forces as a whole?
I mean possibly, but in my use case it needs to be really precise and butter smooth
forces are just philosophically not the right fit for that
were you also using moveposition at the same time as forces?
wdym?
forces can be precise with a little math
if you're opposed to forces, have you tried velocity+angularVelocity yet lol
no, I was thinking about how to make what I want do do with the controller I already have and using for everything cause I'm lazy
but I'll just have to try that
do you guys know if it would be okay to distribute an asset but requires multiple DLLS from microsoft.. anyone know if its okay to distribute ?
Should I somehow package them into 1 assembly?
eg .. is there a more graceful way?
anyone know why ui buttons don't work in playmode on one computer but work fine on another? it works fine in a build and in the simulator, but in normal playmode they don't work. other click actions work that aren't ui related, and the project is exactly the same on both computers, including packages.
There is some way i think to ref more .net assemblies using a file but I dont know if its supported this way anymore https://docs.unity3d.com/2020.1/Documentation/Manual/dotnetProfileAssemblies.html
I'm confused a bit here.. how does unity resolve those dependencies ? btw I'm trying to keep it as .Net Standard 2.1.. What I do is basically a blank Console app then I "publish" the app and grab the DLLS manually.. It all works fine but There are over 12 DLLs now, was wondering it was easier / better to make 1 DLL or something with all those.. I actually only needed 1 package but these are all the dependencies it needs
It is to tell unity to reference additional .net assemblies but the ver we get doesnt include system.text.json I think anyway 🤔
feels like this lib is just incompatible, can you update it to use unity vectors instead and say newtonsoft json?
Oh I have no idea..I'm using SignalR.. everything works as it should though.. Its literally 1 client DLL that has all these dependencies, I just wanted to make an asset so that someone can make a small app, or example like a chat app, using this DLL rather than having all the DLLs like I did. Or thats why i was wondering if I can just distribiute it with all these DLLs
that probably depends on the license for mono/.net
ohhh..isn't .NET open source? so is should be okay commercially?
hmm here it has MIT license for this specific package
https://www.nuget.org/packages/Microsoft.AspNetCore.SignalR.Client
Client for ASP.NET Core SignalR
This package was built from the source code at https://github.com/dotnet/aspnetcore/tree/d5dc8a13cc618b9cbdc1e5744b4806c594d49553
idk if that covers all the DLLs dependencies, I guess it does?
well no, the normal user installs the deps and agrees to those terms
best go read up to see if its allowed instead of guessingg
One message removed from a suspended account.
either way its the wrong channel #archived-networking
One message removed from a suspended account.
One message removed from a suspended account.
This error is killing me:
ArgumentException: Incompatible Delegate Types. First is System.Action`2[[Unit, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[UnitEventArgs, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]] second is System.Action`2[[Unit, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[DamageEventArgs, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]].
System.Delegate.Combine (System.Delegate a, System.Delegate b) (at <b89873cb176e44a995a4781c7487d410>:0)
Unit.add_AfterDamageTaken (System.Action`2[T1,T2] value) (at <9a738af1d4b64ce2a2e238818613bf7f>:0)
The line that triggers the error:
this.Unit.AfterDamageTaken += Unit_AfterDamageTaken;
The event:
public event Action<Unit, DamageEventArgs> AfterDamageTaken;
The method:
private void Unit_AfterDamageTaken(Unit unit, DamageEventArgs args)
It only happens sometimes after the game runs for a bit, I spawn a unit like once a second and it happens every 10 seconds. DamageEventArgs inherits from UnitEventArgs.
Do you have a delegate that uses Unit, UnitEventArgs
Yes I have a couple
Then you must be trying to combine the two
Look at whatever other things are being added to that delegate and make sure you're not merging two different types into the one delegate
Though I would have thought it would be a compiler error, so perhaps if you're overusing inheritance just to avoid writing the same fields for each args type, separating the two might make that become clear
ah damn I think I found it
On a side note, is there a way to solve this:
public interface IDeactivate
{
public event Action<IDeactivate> OnDeactivated;
}
public class Unit : IDeactivate
{
//I have to use this:
public event Action<IDeactivate> OnDeactivated;
//I would prefer this only
//so subscribers don't have to cast
public event Action<Unit> OnUnitDeactivated;
public void Deactivate()
{
OnDeactivated?.Invoke(this);
OnUnitDeactivated?.Invoke(this);
}
}```
Impossible to say without understanding the usages. I tend to try to use generics to avoid boxing because I'm always using structs. But if you're not storing and accessing your data in a way that supports that (like ECS) then it's a bit fraught
Ah didn't consider that I can use generics for interfaces, I think that might work for me
this was the cause, no idea why it's letting me do this in the first place:
You can do this:
public class Unit : IDeactivate
{
event Action<IDeactivate> IDeactivate.OnDeactivated
{
add => OnUnitDeactivated += value;
remove => OnUnitDeactivated -= value;
}
public event Action<Unit> OnUnitDeactivated;
public void Deactivate()
{
OnUnitDeactivated?.Invoke(this);
}
}
Since Action is a generic type that supports contravariance, an Action<IDeactivate> can be assigned to a Action<Unit>.
I keep it in mind in case generics don't work for my case
Hey I'm making a wallrun system that you can start from any direction so I need to detect a wall 360 degrees around the player. Currently I do this with 4 raycasts going: forwards, backwards, left, right. but I was wondering if there was a better way if doing this?
if it works
Are you sure you need it to be in 4 directions and not just the player movement/view direction?
If you're using rb then just doing a sphere and getting point of collision works too
you mean a spherecast?
I thought of doing that but I still want you to be able to start the wall run when already moving parallel to the wall
overlapsphere rather, but yeah that's an idea too
spherecast is good if you need the surface normal and other hitInfo
overlapsphere might work. sphere casts are a bit of a pain cause they won't return true when they already overlap with an object when it is cast.
true
hmmm yeah actually if you want the hitinfo point I guess cast is what you want
overlap gives you the collider but not the point
does overlap even work on stuff that doesn't have an rb?
but cast has some issues of not working if it originates inside of the colldiers
good to know
rb would allow you to use OnCollision methods vs just querying
but yeah currently I just got this (the green lines) it works well enough. I just thought I'd ask here in case someone know a neat trick for doing the same thing
I think that's fine honestly unless you need more surface area
they are just thin compared to sphere and such but you still only get 1 hit point anyway
yeah I use a sphere cast for that exact reason for my ground check
overlap actually a pretty bad idea now that I think about it as the pivot of the wall could be far away
usually I would do a raycast with it to confirm but better to just get the hitinfo
sameee. I do that for my AI initially to find the player and then rays for checking walls
If your game has any complex geometry like holes or bumps in the walls/irregular shapes, I'd use spherecast instead
You dont want the cast to fit into places where your character cant fit
That's not an issue but it's good to keep in mind
Is there a minimum URP build size? What id like to understand is if I strip everything away how small in mb could I get a Unity build .exe that supports only rendering a 3D scene (no physics, extra modules of any kind)
You can't really strip the core modules, like physics, so something around 20-50mb. It depends on the platform and wether it's a mono or il2cpp build too
How about for windows? Il2cpp
I'd assume it's somewhere in that range. You should test and see for yourself.
You can look at the build report to see what exactly makes up the build size.
True. Just needed a gut check, if you said 200mb then would point me in a different direction
anyone know why whenever I use null propagation, I get a message saying "unity objects should not use null propagation" when I hover over the object? it seems to work just fine as a replacement for a null check
Because unlike the == operator, null propagation won't detect when a Unity object is destroyed.
sometimes that's ok, sometimes it's not. You should know the difference intimately if you plan to ignore it.
oh gotcha. so if it's destroyed then it will still register as not null in any other conditional?
yes destroyedObject == null will be true, but destroyedObject is null will be false
really struggling here. Iv got some transform and im trying to lerp the object between them, but they are children under a parent object that moves. If i dont set parent the transform dont follow the parent while in motion. Whats the best way to handle this?
For context, its a chair that where you sit in it moves between 2 transforms then rotates. and the root that its on can be rotated in any direction.
Spacecraft chair. Having to even parent them confuses the heck outta me, because your think that being a transform as a child would just follow that transform like a good doggy.
Im getting pretty frstrated with it
It's not quite clear what the issue is. Does a child not follow parent transform? Is that it?
Also share !code properly:
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't think i understand your problem completely but i think you are facing issue with object which is child of moving object so may be you can use Fix joint instead of making it a child (if you are using rigidbody).
private void OnCollisionEnter(Collision collision)
{
print("Hit something");
if (!isServer)
return;
if (!(LayerMask.LayerToName(collision.gameObject.layer) == paintable))
return;
CmdSplatter(collision.GetContact(0).point, collision.GetContact(0).normal);
//Destroy(gameObject);
}
it does not print out anything
hello
first time im actually debugging my game with a debugger
@jaunty surge don't ping people not in conversation with you. And if you are asking something make sure to provide context.
can you clarify? like automatically adding a closing angle brace?
that would be really annoying for trying to use < as in "less than"
there might be lsp features depending on ide (or maybe needing an extension) to have it only do that for generics 
im using vscode, it doesn't have those, and the c# lsp doesn't either, but if you're using a different ide, try searching for "auto close" or "auto closing" in settings
VS and Rider does
is it on by default?
Closing is held for contextual autocomplete.
Don't remember how it works in VS, Rider just chases you with it.
I think in VS you finish it off with Tab.
(Actually both work the same, when you enter the structure like List<> using autocomplete, you already type inside <> brackets, then finish stepping over with Tab or manually typing bracket)
I have a game in 2D currently with a menu and everything needed. I am used to making 2D games but thought I would go outside my comfort zone. I am wanting to make a 3D asset TV that, when the game starts, fades lights on a dark screen to show an old TV asset I have. Then, I want to slowly zoom in and switch it on. This will then show the menu, and the game can play on the screen from that perspective. Can anyone assist with tutorials?
don't crosspost. ask a specific question on what you need help with. there are a lot of smaller parts that make a system like this work
I have the following Problem: I have a Scriptable Object with a List typeof a Custom "Base Class" (normal C# class). Then there are several
"sub classes" that derive from this Base Class and all have different Fields. And in the List there are instances from all those different sub classes.
Now I want to rename the Subclasses but that resets all the values. How can I go around this without having to refill all those Values by hand ?
Have you tried [FormerlySerializedAs]? Not sure if it works on classes though
Yes does not work on classes unfortunately
UnityEngine.Scripting.APIUpdating.MovedFromAttribute
ok will take a look at that
ok either I used it wrong or it does not work I just have to write [MovedFrom("oldSubclassname")] right ?
You need to make sure to discard any reimport after renaming. If you've saved it after renaming, the old values are cleared.
If the namespace has changed, you also need to specify that in another parameter.
Maybe I missunderstand something but if I rename it and dont save it whats the point of it ?
You should save it afterwards yes. But if you've already saved it after renaming but before adding the MoveFrom attribute, Unity has already replaced all the values.
This is using [SerializeReference], right?
If it's the same as System.Serialzable then yes. sorry I'm not really into the whole serialization Stuff
No I added the Attribute then renamed it and then saved it
No, it's a different type of serialization. We assumed you were using it since you were talking about serializing derived types into a base type, which is only possible with SerializeReference. MovedFrom only applies to SerializeReference.
ah actually yes I do use SerializeReference I thought you mean the one for the class it self
So you were careful not to save the project after you saw the values got reset, or discarded the changes in your version control before you added the attribute?
Did the values come back if you renamed the classes back to their original names?
I actually dont use any Version Contoll I just renamed the class in VS an then the values Changed in the Inspector
No
In that case it sounds like Unity has already overwritten the values. Since you don't have version control and assuming you don't have any back up of the original values, they are lost.
The interessting thing is it only resets the value if the SO I selected so when I rename it select a SO the Values are reset but when I change it back and select the other ones they dont get reset
I did share the code properly, a block or 2 wouldn't be good enough. Thebissue is when the animation starts it moves the seat to the center mass of the spacecraft, instead of going to the assigned transform. Sometime when you exit the seat the chair is even visibly moved off the ship into the void. But the players exit point is still correct.
(You did not share the code properly)
Because Unity doesn't attempt to load or resave the SOs until they are used, such as when selected in the inspector.
Yeah I did. Discord has character limitations. So attaching the emtire.script was the proper decision...
Did you read the bot message? This is not the correct way to share code.
Users on mobile are forced to download your files in order to help you.
hm ok like i didtn lose a lot as I only changed one class so its not that I need to get the Values back but rather to find a way to rename it so that I dont lose the Values when I change the other ones
Anyways, this explanation is still unclear. Maybe a video of the issue could help.
Use Scriptbin to share your code with others quickly and easily.
I'll add a video later, but there's the code
I renamed the Name to the original and Restarted Unity and somehow now the Values are back ... but I still can't rename it without losing them again
I see that your seat visuals object is getting moved somewhere else in the hierarchy. Is that supposed to happen?
No its not. It get moved into the ships hierarchy and out of the Seatroots - but its supposed to go right back - that happens exclusivly for as google calls it motion matching
I was trying to make it so that it would follow the motion of the vehicle - so the google said to parent it to the object that's moving then back to the intended location,
but as you can see it literally disregards the set transforms locations and acts like they are over there
This vehicle moves with 6dof so...that i assume is where the complications occur
Is it possible to give a display name to elements inside an enum in Unity C# like in unreal with the property DisplayName ?
youi just want objects listed in a drop down for selection?
c# enums can't really have members
I think a Scriptable object is nore what you want
that or just display the name in some places if needed like in inspector or text components, etc...
How ?
enum values always have a "name"
it just displays the name of the enum member in the inspector
// ResourceDefinition.cs
// Defines descriptive and functional metadata about each resource type in the game.
// ============================================================================
using UnityEngine;
[CreateAssetMenu(fileName = "NewResourceDefinition", menuName = "Market/Resource Definition")]
public class ResourceDefinition : ScriptableObject
{
[Header("Basic Info")]
public ResourceType resourceType; // The enum ID (Iron, Uranium, etc.)
public string displayName; // Name shown to player (ex: "Iron (Fe)")
public string resourceCategory; // Metal, Gas, Crystal, Gemstone, etc.
public string state; // Solid, Gas, Liquid, etc.
[Header("Scientific or Tech Details")]
public string conditions; // Melting points, etc.
[TextArea]
public string notes; // Usage, lore, or technical flavor
[Header("Economy")]
public float basePrice = 100f; // Default price per unit
public float volatility = 0.15f; // How much price can randomly swing
}```
This is an example of mine
enum MyCoolEnum { Foo = 1, Bar = 2}
Its not like cpp where the string value does not "exist" in builds
Yeah but the name can't contain space hence my question of having a display name that could contain spaces
and you can leverage it like this
// File: ResourceType.cs
// Summary: Enum that defines all possible resource types in the game.
// Interacts With: MineableResource.cs, InventorySystem, Crafting
// ===========================================
public enum ResourceType
{
None,
Iron,
Copper,
Titanium,
Uranium,
Ice,
Hydrogen,
Silicon,
Gold,
Platinum,
}```
No, you can use underscores or do PascalCase or camelCase
That way you can use a enum then combine it with the Sciptable object and display it with that instead
thats MY use case, your is different certainly
unity doesn't display names directly. it splits words according to camel or pascal case
this is an enum member named StoneAnotherWord
just like how it does field names
Yeah I know that but I need spaces because it would be weird to display a name with underscore or pascal case or camel case to the user 😄
yeah but that isn't shown
Then you have a mapping to some translation or replace some char with space
(underscores don't work btw.)
im not talking about the unity inspector
I'm interesting to know how to do that please 🙂
FertileSoilSubstrate Would show up like: Fertile Soil Substrate
@fiery steeple are you talking about the inspector or shown within the game
thats what he trying to ttell you
those are pretty different contexts
you mentioned inspector before, and this just isn't an issue in the inspector
I need both
public enum MyCoolEnum { Hello_World }
MyCoolEnum a = MyCoolEnum.Hello_World;
Console.WriteLine($"{a.ToString().Replace("_", " ")}");
you could get the name via reflection and transform that, or you could also use an extension method
I don't know what that mean 😬
If all you need is 1 string per object and nothing else then go with Chris suggestion, i needed to make an entire class to display extra information
For showing a different name in the inspector, you can use the InspectorName attribute.
public enum Dimension
{
[InspectorName("2D")]
TwoD,
[InspectorName("3D")]
ThreeD
}
But this has nothing to do with displaying it in game.
Oh ok, thanks 👍
enum MyValue {
ValueOne, ValueTwo
}
static class MyValuesExtension {
public static string DisplayName(this MyValue val) {
return val switch {
MyValue.ValueOne => "Value 1",
MyValue.ValueTwo => "Value 2",
}
}
}
// usage
textComponent.text = MyValue.ValueOne.DisplayName();
void SomeMethod(MyValue val) {
textComponent.text = val.DisplayName();
}
but this doesn't affect how it's shown in the inspector, unless you want draw that yourself
Wow, I never saw this syntax before 😄
yay extension methods!
How is he able to access "DisplayName()" without using the name of the class MyValuesExtension first ? 🤔 And what's the this as parameter knowing that the type is already MyValue 🤔 ?
- because of the
thisparameter - it knows because.. i told it
It's called an extension method. You basically add a function to an existing type
this MyValue val can act like a normal parameter, MyValuesExtension.DisplayName(MyValue.ValueOne), but the this modifier means that it can also use that parameter as the this value; as in calling the method from some MyValue (and that's captured as the val parameter)
I understand nothing 🤣 Also according to the MS doc, you're using the "Before C# 14" syntax 😄
oh
it's barely got c# 9 if i remember correctly
why didn't Unity update to the last versions of C# ?
unity can't run c# directly
It uses Mono which is old and shit
it uses an existing runtime, mono, which is old
But they are making the effort to upgrade to the newer .NET CLR
unity's in the process of changing runtimes, but until then, we're stuck with old mono and thus old c#
Do you think they would change that for the next Unity version (i.e Unity 7) ?
we all hope so 🙏
Unity 2021.2 and later: Supports C# 9 features
How long it took to switch from C# 8 to C# 9 ?
That has no bearing on the update to the newest version.
Going from C# 8 to 9 didn't require changing to a new runtime, like it will to update from C# 9
so there's no average time between 2 versions that you can deduce from past version switching ?
c# 8 to c# 9 was updating mono
c# 9 to... whatever it'll be next, will be switching out from mono entirely
completely different story
then how would we use methods and fields that are part of MonoBehaviour ?
like Start() Update(), etc...
MonoBehaviour is just a name
those are unity apis
unity defines those
they aren't attached to c# versions/runtimes
It was a legit question IMO
when you said "Mono", did you mean "MonoBehaviour" ?
no, separate things
Oh ok
not an abbreviation
No, then they would have said MonoBehaviour
They mean Mono
https://www.mono-project.com/
monobehaviour is just, "one behaviour" i think
Which Unity was based off of but no longer really needs and is kind of an albatross at this point
thought they were the same and just abreviating it because the word is long and everyone is familiar with MonoBehaviour 😄
I assume MonoBehaviour comes from when Mono was new and now you could make a behaviour using Mono.
Unity used to support javascript and boo and they had to name the mono scripts something else than Behaviour to differentiate
oh so monobehaviour literally is "behaviour running on mono"?
and monoscript as well?
In the context of Unity, "Mono" specifically refers to the Mono runtime and compiler, which is used to execute and compile C# scripts within the Unity engine.
Behaviour:
The "Behaviour" part indicates that the script is designed to implement behaviors or actions that can be applied to a GameObject.
MonoBehaviour:
This class serves as the foundation for scripts that you attach to GameObjects to control their behavior in the game.
Thats how i understand it
Well, UnityScript and Boo were both different languages that both compiled to .NET dlls and ran on Mono.
SO essentially they can change Mono to what ever they want and it wont really affect your scripting
It's vestigial, they used to be literally Behaviours for Mono, even though it is no longer relevant.
Like the "Deckmaster" logo on the back of old MTG cards, it's only around because it was there at the start and can't be removed now
i mean, they are still on mono for the time being 😆
im really hoping when they make the change they dont change things too drastically.
it needs to stay user friendly - thats why i threw UDK in the trash compactor
The APIs will all stay the same. The biggest change in workflow will be related to assembly and domain reload. I believe domain reload will be disabled by default, where it's optional now. So static fields will not be reset between play mode.
thats really minor...call me crazy but that doesnt really change anything. Its literally a bool
it being user friendly doesnt get affected from this...
theres a ton of differences just from the c# versions alone
so the real difference is it just supports more C# features?
That and performance improvements in the runtime. Code in the editor and in Mono (by then, CoreCLR) builds will run faster thanks to a better JIT compiler and garbage collector.
ah yeah the GC needs massive updates
Less improvements for IL2CPP builds, but you will still have access to new language features. And as far as I know, they will try to support all runtime features in IL2CPP, as they have for Mono.
well dont forget the incremental gc exists and is configurable
How so? News to me that even exists
https://docs.unity3d.com/6000.2/Documentation/Manual/performance-incremental-garbage-collection.html#incremental-garbage-collection
If you check in project settings you can modify its parameters
If unity can replicate what S&Box is able to do (amazing hot reload) then I will be very happy
It say it run in incredmental by default though - not sure that worth touching? How would forcing a single spike be beneifical?
Yea i wouldnt mess with it but maybe for some projects it would help
good to know its there i suppose
Does UniTask handle task cancellation when the application stops? I know that was an issue with Task, and one reason I've been looking into Unity 6's new Awaitable. However, UniTask seems more feature full and appears to have more community support atm.
Hi. I'm implementing Multiplayer for a Game right now and everything is working on my local machine. I can start the game 2 times, 1 time as a Host, 1 time as a Client.
Now the problem is: When I test this with a friend and one of us hosts a session, the other one can't join. Why is that?
The Address in Unity Transport is set to 127.0.0.1, but that isn't a problem, is it?
Because that's not the Server IP, it uses Unity Cloud for the Servers
both your freidn and you are local on the same pc?
127.0.0.1 <- Is always a default local address never someone elses machine
I thought that Unity Cloud somehow takes care of this
Alright so that address IS the server address
every machine has that address - the server needs a public Ip
yeah
127.0.0.1 can never be a public Ip
I didn't know the IP in Unity Transport has to be public
I got a little confused there
What if I type in the IP Address of my Debian Server
What do I need to setup on my server to make it work there?
as long as its public address that can be connected to by externals then yes - I think that would work.
if you can ping the server with the ip from another machine and get a reply back then that should be fine
Just need to configure firewall
inbound and outbound rule for port 7777 correct?
thank you very much @valid estuary ❤️
only for the server itself
So here I just type in the servers IP
Port stays the same
and I don't need to do some weird stuff like running an instance of the game on my server
or something like that
correct?
Hey,
How to cast a parent type to a child type?
I'm trying to convert an ItemData class that contains the generic data for all items within my game.
When trying to create a child class for an item that contains more specific data about an item like a valuable item in this case.
This error is thrown at runtime InvalidCastException: Specified cast is not valid.
When the cast is removed it throws this when compiled.
error CS0266: Cannot implicitly convert type 'Game.Gameplay.Inventory.ItemData' to 'Game.Gameplay.Inventory.Items.Valuable.ValuableData'. An explicit conversion exists (are you missing a cast?)
// in parent class Item
public virtual ItemData GetItemData()
{
_itemData = new ItemData();
_itemData.itemName = itemName;
_itemData.itemRarity = itemRarity;
_itemData.itemType = itemType;
_itemData.id = persistantID.guid;
return _itemData;
}
// in a child class ValuableItem that inherits from Item
public override ItemData GetItemData()
{
// _valuableData is of type ValuableData which is a child of ItemData
_valuableData = (ValuableData)base.GetItemData(); // InvalidCastException: Specified cast is not valid.
_valuableData.itemValue = itemValue;
return _valuableData;
}
How to explicitly convert from ItemData to ValuableData?
the server IP is your PC Address if you opened ports to host the game
But I want it to be ran on my server
if you're sending it to your friend then you need to have port 7777 and send them your public IP address.. That should be in THEIR version of the game
do you have a server with a public IP then do it there
the process is exactly the same
do i need to run the game there?
yes ofcourse
its very easy just run your game like normal
do you know how to run an app via terminal? its very easy
a game with GUI?
you normally just go to the folder the bin is and type it(name of the app) in the console. Make sure proper permissions are given
but the thing is
with the current logic in the game
the host also acts as a client
so he hosts a game and then also spawns there as a player
you don't need that
I would also have to change that?
run it as Server rather than Host
okay okay I think
NetworkManager.Singleton.StartServer()
yes
it needs to be also part of the Transport, otherwise your friend tries to connect to its own IP
typically I make a TextMesh Input field to pass IP into Transport, so its a bit more modular and you dont have to reBuild the game every time you want to change IP of the executable / transport
But if I always want everything to run only on 1 "server"
I can just statically type in my public ip in the field
and that'll work?
yeah it should work if you just type it in the inspector if thats what you mean
yes
do I need to allow inbound AND outbound
for the specified port?
or is inbound alright
(firewall)
just inbound
how would this ever work?
_itemData = new ItemData();
...
return _itemData;
...
_valuableData = (ValuableData)base.GetItemData()
_itemData is clearly not of type ValuableData
There must be something im misremembering but ValuableData is a child of ItemData so an explicit conversion should be possible from ItemData to ValuableData right?
public class ItemData
{
public string id;
public string itemName;
public ItemRarity itemRarity;
public ItemType itemType;
public ItemData()
{
itemName = "";
id = null;
itemRarity = (ItemRarity)0;
itemType = (ItemType)0;
}
}
public class ValuableData : ItemData
{
public float itemValue;
public ValuableData()
{
itemValue = 0f;
}
}
oh very nice of you .
thank you 🙂
I need to start throwing some new stuff up haha been very busy lately
the object created in base.GetItemData() is a plain ItemData instance, not a ValuableData instance.
you cant cast if the object is not actually that type. it'd work in the case of it being new ValuableData() which of course you shouldnt do there either since it wouldnt make sense for any other deriving class
How to go about converting to it without hardcoding a conversion?
im not exactly sure why you need to set it up the way you've shown. just use the constructor
The data in ItemData must carry over to ValuableData
are you familiar with how inheritance works and constructors?
The new instance isn't a Valuable Data but rather an Item Data. To be able to cast to a Valuable Data, you need to create a new Valuable Data instance. Casting to the parent type would be valid. Casting to a child type from a parent instance is not valid.
https://dotnetfiddle.net/tu4cCW
you cant do what you want without declaring the logic. you'd need a constructor or method in ValuableData which copies over the ItemData
if you just use the constructor as intended, it works as is
@rigid island
do i need to configure anything in my router?
port forwarding or something like that?
yeah you have to open the port
because i tested with a friend and he can't connect when I host
did you open 7777 udp ?
nah it needs to be on your router..
thats why its generally not advisable to open port unless you really trust who you give access to your IP
your router / internet gets exposed on that port, any potential bad actor can infiltrate.. Its okay with friends, but don't do it as a public one and use your VPS
Okay I converted the code a to use constructors and it works great
okay
But surely there is a less verbose way of doing this?
public class ItemData
{
public string id;
public string itemName;
public ItemRarity itemRarity;
public ItemType itemType;
public ItemData(string aItemName, string aId, ItemRarity aItemRarity, ItemType aItemType)
{
itemName = aItemName;
id = aId;
itemRarity = aItemRarity;
itemType = aItemType;
}
}
public class ValuableData : ItemData
{
public float itemValue;
public ValuableData(string aItemName, string aId, ItemRarity aItemRarity, ItemType aItemType, float aItemValue) : base(aItemName, aId, aItemRarity, aItemType)
{
itemValue = aItemValue;
}
}
but how do I run a GUI game
on a terminal only server 😭
I still don't understand that
I connect to the server in my CMD
via ssh
not that im aware of
it works
😮
with my pc tho
I dont have it on my server yet
how is that supposed to work
Your initial get item data method seemed to be attempting to clone the item data. If you're just trying to clone the data, just implement a copy constructor.
its the same exact thing.. a server is just another computer , elsewhere lol
open the port on your VPS and do the same thing.. Make sure the IP the one from server public IP
why would you need to run anything UI related even?
Oh yes this is what I was looking for thanks!
@vapid swift if you want to strip the graphics completely you can use a Server build if you haven't done one already
https://docs.unity3d.com/6000.0/Documentation/Manual/dedicated-server-build.html
I know what a server is but
I can't open a game GUI in a terminal
why do you need the GUI ?
well yeah you have to run the game just to be able to run as Sever. Use Command Line Args
pass the server or similiar keyword to it, then you can process it to use in the NetworkManager.Singleton.StartServer()
This page walks you through how to create a command-line helper that launches your project outside the Unity Editor to make testing builds easier.
Im not sure how you plan to use ItemData/deriving classes but the copy ctor is definitely more of a backwards and worse way of doing it. What you had previously would only really be used if you were really trying to limit how ItemData's are made.
With this, you'd be creating an ItemData object, returning it so ValuableItem can create itself based on the data, then returning itself. You'd be making 2 objects everytime instead of 1 just to avoid writing the constructor properly
Yeah I just a took a longer look at it and the instance constructor way is better
When I start as a Server with one instance and connect with the other one, it can't join.
with host it works tho
Isn't Server the same as Host, just that it doesn't act as a client at the same time?
yeah it should be , well the other way around. Host is just Server + client..
yes
did you verify its actually running as server at all ?
use the bool or maybe subscribe to this event and print to console make sure ur server started at all
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.3/api/Unity.Netcode.NetworkManager.html#Unity_Netcode_NetworkManager_OnServerStarted
Does anyone know is it possible to create assembly definition reference to Assembly-CSharp?
The thing is that I have .asmdef file in one folder and I want a specific subfolder of it to be compiled into Assembly-CSharp
I dont think you can. I think cus assembly-csharp auto references everything for you.
You have to make a asm def at the project root to "replicate" it
and then ofc fix Editor folders after this as they wont work automatically anymore
meh I hoped for some fancy trick like creating empty .asmref file or something :/ Im generating assembly definition from code with some classes and auto-populate references in that asmdef if any class uses a specific type, but if referenced type is in Assembly-CSharp I need to compile that autogenerated class also into Assembly-CSharp and that creates a mess if I cant keep it in one folder
yeah I know you cant reference predefined assemblly as a dependency for .asmdef, I just really wanted somehow to bypass the logic that every subpath of a fodler with asmdef is compiled into it and make inner folder go back to default behaviour of being included in Assembly-CShsarp
Well you can make an asm def and then use asm def links to join other random folders to 1 asm def
e.g. Assets/Foo & Assets/Bar
I know but thats not the point, thanks for help tho!
yea its basically something you cant override because if assembly-csharp already references custom asm defs, they cannot ref back even if you somehow tricked unity
If Unity supported Records, then yes.
I'm puzzled. Given this serialization code:
using MemoryStream ms = new();
BinaryWriter writer = new(ms);
writer.Write(Id.ToString());
writer.Write(hasPlayed);
writer.Write(jumpScareActive);
writer.Write(playOnStart);
I would think that this should work on the other end when I deserialize:
using MemoryStream ms = new(data);
BinaryReader reader = new(ms);
Guid id = Guid.Parse(reader.ReadString());
hasPlayed = reader.ReadBoolean();
jumpScareActive = reader.ReadBoolean();
playOnStart = reader.ReadBoolean();
But once the reader is done with jumpScareActive it reached the end of stream 🤔
how big is the result of the first stream and is it as you expect?
Good question. It's one of many. I'd have to isolate it.
But it appears that there might be a solution. Someone made me aware that strings are problematic when serialized.
But I don't need to serialize the Guid as a string. I can just serialize it as a byte array.
I presume it will read a null terminated string and i wonder if string to bytes will do this
That is true yea, guid size should be consistent (its ascii always right?)
It should be, yes.
Then it would become this instead:
byte[] guidAsBytes = Id.ToByteArray();
writer.Write(guidAsBytes.Length);
writer.Write(guidAsBytes);
writer.Write(hasPlayed);
writer.Write(jumpScareActive);
writer.Write(playOnStart);
and respectively
using MemoryStream ms = new(data);
BinaryReader reader = new(ms);
int idBufferSize = reader.ReadInt32();
Guid id = new(reader.ReadBytes(idBufferSize));
hasPlayed = reader.ReadBoolean();
jumpScareActive = reader.ReadBoolean();
playOnStart = reader.ReadBoolean();
A small change, but I have to do that in a lot of places. But that's something at least.
the doc says A GUID is a 128-bit integer (16 bytes) so it should be the same size always for a guid
With the above approach I'm at least sure I always get the right size 🤞
its all shit it needs to be re written!! /s
Honestly? I had that a couple of days ago. Left a legacy codebase. Game works but performance is quite poor from where it should be. I tried to duct tape my way around it, but I just...can't. It takes more time than simply rewriting the systems that are the culprits of the frustration 🙃
So I had to touch every system and almost every file to rewrite the serialization system :U
solutions like protobuf and bebop exist to do efficient binary serialization
Anyone have any thoughts on Jason Weimann's new video on gameobject communication? https://www.youtube.com/watch?v=51sPPlT3X-4
Flash Deals - https://assetstore.unity.com/?flashdeals=true&aid=1011lkXUB
Courses - https://game.courses/
00:00 Introduction
00:24 Direct References
00:40 Property Version
01:30 OnValidate
01:46 Dynamic
02:19 FindFirstObjectgByType
03:09 Find Multiple by type
03:34 Tags
03:56 Singleton
05:37 DI
06:42 Passing Mesasages
07:07 SendMessa...
He really recommended Singleton's
As maligned as they are for general-purpose programming, singletons are actually fantastic for game development. Most people who say "singletons bad" will, when asked to elaborate, settle on "singletons bad because they're only good if a whole bunch of rare conditions and necesseties all intersect at once" and the conditions they describe are basically "video games"
1 component to control stuff is good but I have learned that its bad to rely on a static field ref too much as it can really make some things difficult later.
One of the things that makes singletons great in Unity is that there is still an actual physical object that exists with all the data, which makes a lot of the debugging nightmare of normal singletons a non-issue
When you can physically see the instance of your singleton and what its values currently are, it's hard to get snuck up on by a bug of it resetting itself without you noticing
I use what works for games. Singletons often work for what I need so I use them. It's a tool in the toolbox, not some boogeyman in the codebase 🤷♀️
Use it wrong and you get bad code.
Use it right and you make certain aspects of development a breeze.
I dont know how you are able to work with unity without singletons, it's not like you get an entry point to your scene anyway.
so that leaves you with using some find method which I despise
You can definitely setup bootstrapper scenes that allows you to control entry
And then not use it anywhere else 🤷♀️
In fact, far as I can tell, most decently made games use some kind of bootstrapping setup
Basically says, instead of understanding your problem, do what I say you should do because I found it works for me in my toy projects. Which is honestly fine since anyone who understands their problems or works on non-toy problems wouldn’t watch that video and can figure out the best solution themselves.
Okay, my "fix" didn't fix anything.
For some reason
This stream is 23 positions long
using MemoryStream ms = new();
BinaryWriter writer = new(ms);
byte[] guidAsBytes = Id.ToByteArray();
writer.Write(guidAsBytes.Length);
writer.Write(guidAsBytes);
writer.Write(hasPlayed);
writer.Write(jumpScareActive);
writer.Write(playOnStart);
When I deserialize it later:
using MemoryStream ms = new(data);
BinaryReader reader = new(ms);
int idBufferSize = reader.ReadInt32();
Guid id = new(reader.ReadBytes(idBufferSize));
hasPlayed = reader.ReadBoolean();
jumpScareActive = reader.ReadBoolean();
playOnStart = reader.ReadBoolean();
It's 22 positions long.
🙃
I can confirm that it is the right thing I'm deserializing because the ID matches.
a byte just...disappears in transit??
how is it written, file stream or somethin?
All my bytes are eventually written to disk like this
private static bool WriteToDisk(string path, byte[] data)
{
BinaryWriter writer = null;
try
{
// Create a new stream to write to the file
if (!File.Exists(path)) File.Create(path).Close();
writer = new BinaryWriter(File.OpenWrite(path), Encoding.UTF8);
// Writer raw data
writer.Write(data);
writer.Flush();
writer.Close();
}
catch (Exception ex)
{
Debug.LogException(ex);
return false;
}
finally
{
if (writer != null) writer.Close();
}
return true;
}
if you check the file with something like hxd does it have the data you expect?
I'll check
Makes little sense to use binary writer to write a byte array
Feel free to suggest.
You can get an entry point for the first scene and other startup stuffs via this btw https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
I don't remember the specifics of why I needed to do this, just that I did, but now that I look at my code again, maybe this is the problem child.
private static byte[] ReadFromDisk(string path)
{
int buffer = 4096;
List<byte[]> dirtybytes = new List<byte[]>();
using (BinaryReader b = new(File.Open(path, FileMode.Open, FileAccess.Read), Encoding.UTF8))
{
//hold position counters
int pos = 0;
int length = (int)b.BaseStream.Length;
while (pos < length)
{
//read the bytes
dirtybytes.Add(b.ReadBytes(buffer));
//increment the position
pos += buffer;
}
}
//get the complete byte array
return dirtybytes.SelectMany(x => x).ToArray();
}
I'll switch it out for ReadAllBytes instead
Depending on file size you may still want to use a stream, but the serialization step you can skip
🤨 dirtybytes.SelectMany(x => x).ToArray();
Then writeAllBytes is best
Little dirty bytes 👀
some nice pointless linq + ToArray when you know the file size from the start 🤦
I will admit, I was looking at this at a time of sleep deprevation, aka when I shoudln't.
Not the best decisions were made
That’s where performance goes to die, needless deaths
Is this kosher?
private static byte[] ReadFromDisk(string path)
{
byte[] bytes = Array.Empty<byte>();
try
{
bytes = File.ReadAllBytes(path);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
return bytes;
}
List<int> list = new();
for(int i = 0; i < 10000000; i++)
indeed
How about the version that gives the byte array at the correct size to start 😆
public static byte[] ReadAllBytes(string path);
oh im dumb
You are just reinventing methods that already exist in System.IO
you can just return null if it fails
It's a wrapper method.
I might want to change it later.
Premature abstraction is the root of all evil
Programming is the root of most of my evil
You may need an exorcism?!
Honestly, at times programming is my cursed knowledge.
It...it still doesn't...work T_T
It's one byte short
There has to be somewhere I don't do proper deserialization or something.
This appears to be the only object in the game that fails this way, so far, but why???? Q_Q
if you use File.WriteAllBytes() does it insert a 0 at the end?
does anyone know how to have it so it shows everyone's playfab ID in a photon lobby
it shows my own but it doesnt show other people's
Aight, already before it gets saved to disk, the byte has disappeared. Just figured that out.
Something happens to it before it reaches my disk :I
Using a debugger to check the whole process?
I don't agree with what he said about message passing and event bus patterns. To suggest that they are less decoupling compared to static events doesn't make sense to me. He simply boils it down to "extra CPU cycles for zero benefits" and dismisses as a pattern entirely.
He basically dismisses/recommends all patterns with very unspecific reasoning
I think the video doesn’t contribute to the education of the masses
Whatever gives you reference to your object without much fuss.. Just don't force yourself to build around a pattern because it looks cool (a rabbit hole for unnecessary complexity). Like always, be aware of the constraints (intended for singular instances as implied by the name) and some of the common pitfalls like an overly complex class, knowing which objects might be interacting with the class and misuse from others will be annoying (if applicable).
He also seems to prefer FindObjectsOfType over FindGameObjectsWithTag.
Many people don't know that unity stores a list of all tagged objects and has to only search those, as opposed to having to search all components in all objects which gets slower when your scene grows.
So find with tag + get component would be the better option here IMO (But no, I don't really use Find methods except in the prototyping phase)
Personally I don’t respect tags cuz of how hardcody they are. Ideally singletons + objects im trying to find instead finding the relevant singleton in question on initialisation feels far easier and still simple enough for prototyping
Not saying tags are great, just saying it's probably usually the better option from those two Find methods
find based code outside system init isn’t particularly indicative of a sustainable architecture
typically it shows up together with other weird solutions and can serve as honey pot which is easy to spot in reviews
That's a really fancy way of saying "code smell"
hehe
when many developers cooperate some solo-dev roses start smelling like turds
Thanks for all the responses everyone! I've been really trying to avoid singleton's, but it's a lot of extra work to learn ways around them that work well and don't create a ton of complexity.
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
That's cool thank you for responding, was just curious.
hey guys, I one issue I've had for a while but finally want to get around to fixing. I have a build automation server running in a virtual machine, but for some reason builds seem to be missing certain assets. I suspect i might need to a run a line of code in order to build the new project files after retrieving the latest git pull, but im not sure. I suspect theres a step that unity does for building asset folder that may or may not be getting skipped with how im running the build file
There should, for example, be a crate right here that i can interact with. The interaction works fine, but the mesh is completely missing from the build. There should also be a third weapon in the hotbar, but that too is missing. Inside of editor on my machine, theyre all there. I believe the build server is skipping an import step that i might need to call manually
I basically have a batch script invoking the unity editor, where i reference a build script that runs this code
public static void BuildWindowsClientAtPath(string path)
{
//Get Scenes
string[] scenes = new string[EditorBuildSettings.scenes.Length];
for (int i = 0; i < scenes.Length; i++)
{
scenes[i] = EditorBuildSettings.scenes[i].path;
}
//Initialize build options
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.scenes = scenes;
buildPlayerOptions.locationPathName = path;
buildPlayerOptions.target = BuildTarget.StandaloneWindows64;
buildPlayerOptions.subtarget = (int)StandaloneBuildSubtarget.Player;
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
if (report.summary.result == BuildResult.Succeeded)
EditorApplication.Exit(1);
else
EditorApplication.Exit(0);
}
for some odd reason, unless i manually open and then close the unity editor in the VM, it wont actually import the new assets (i believe, not 100% on it)
Do you upload the assets with metadata files?
Actually, even if you do, there still might need to be an import step.🤔
yes i upload files with their metadata to the git server
so build server is definitely retrieving those
Did you try calling asset database refresh after pulling changes?
https://docs.unity3d.com/ScriptReference/AssetDatabase.Refresh.html
hey guys, is it possible to change the cinemachine gain value with code
what this feels like, is -executeMethod arg might be causing the build to fire without importing assets first,
wait this might work
ill add this to build script before calling the build and seeing if it works
Might need to run it synchronously(one of the options) or wait for the import to complete somehow.
Should be possible. Did you look at the documentation?
yeah, I looked at it
I didn't see anything about it
unless i missed it
i saw this, this is using the old legacy gain controller no?
Not according to the sample code. You can check it in your ide real quick.
ok
I dont think i find anything
i only found
this but
i'm not sure how to acess it
access
trying the ForceUpdate option right now
chatgpt recommends i defer the build until the first Update() in unity
which would honestly probably work. The only thing is its gonna bother me not knowing how to do it properly 💀
It's a public float. So you should be able to access it directly via a reference to the class instance that contains it.
Did you try what I suggested earlier..?
i have tried ...
check your spelling
Perhaps it's compiled with that define being false. Are you using the input system in the project?
yes
And you're sure this here is within the component class?
yeah?
i think
pretty sure
It could be a nested class ot struct
it is a nested class
yeah didnt work, gonna try to defer till update now, maybe chatGPT is cooking
Ok, then you need a reference to an instance of that nested class obviously.
Chat gpt is notoriously bad with unity and especially with some niche topic like that. I wouldn't even try relying on it in this scenario. It just wasn't trained on anything like that.
What is the nested class?
you know how when you normally boot up a unity project theres that whole script compilation phase? My buildscript is running before that
I think defer might work due to it being this way
public sealed class Reader : IInputAxisReader
Are you sure your script runs before that? Unity might block during initialization, so your script wouldn't run until it's done. It's hard to say without having more context.
the starting banner never goes away if that helps
I thought it was on a cloud virtual machine or something. Do you actually have access to that server?
normally script compilation / asset import occurs once the banner is gone and the editor is loaded
yeah lmao its just a vm on an old pc
Ah, okay. In this case, indeed, the way you do it might be weird.
In the first place, it's not clear where and how you launch the editor.
I don't think there's something like that in your shared script.
i just run a batch script that executes unity.exe, pass in -executemethod arg, and run build using BuildPipeline.BuildPlayer() within that method
who want help my game idea
i think it needs to be deferred, with how the editor is behaving
!collab 👇
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I see. That might not be ideal. I'd check the tools unity provides specifically for this kind of scenarios. I.e. launching the editor in build mode.
do you have an API reference to this
i made this before unity launched cloud services
idk what they changed/opened to the public
Are you running it in batch mode?
i was at one point, but ended up removing batch mode line cause i thought itd fix the issue
few months ago
are you sure that help me make idea to a game
if you need assistance with coming up with an idea for a game, then go to #archived-game-design and actually ask a proper question. this is a code channel.
If you run it via batch mode and call the batch command to build the player, does it not work? I think this should inculde any asset importing if required.
In the simplest form -buildWindows64Player <pathname>
-batchmode didnt work, but ill try using the default build tools
for a headless windows server, how would you put in the args?
What didn't work exactly? And what default build tools are you referring to?
would it be
-standaloneBuildSubTarget 'Server' -buildTarget 'win64' -build 'path'
?
for a windows headless server
Try it.🤷♂️
There's a lot of context missing so I can't confirm or deny anything.
the build arguments section of the page you sent me
in the batch script
are those the args to pass in to get windows headless build
im about to try it still cooking this up, just wanted confirmation
It seems to be fine according to what I see in the docs.
-build wanted the -activeBuildProfile arg to be fulfilled and idk whats to be used there
im using the -buildWindows64Player instead, while passing in subtarget server and ill see how it goes
Probably a path to a build profile asset.
Docs:
Set the build profile saved at the given path as an active build profile (for example, -activeBuildProfile "Assets/Settings/Build Profiles/WindowsDemo.asset")
i see, so i make the build asset in unity and just pass it into the arg
man these server builds are taking stupidly long, i think the -buildWindows/Linux64Player is probably doing a regular player build rather than headless
yeah exactly
i mean it can always be the case where it was never even the builds to begin with 🤷♂️
confirmed, the 64player args do regular player builds, no headless
It could
If it doesn't work, I'd have a look at the logs and make sure there are no errors or warnings.
unfortunately you only get a 1 returned if theres an error in the batch script, didnt get that so I can assume the builds are successful
Nnn... Wait, these are server builds??
Where do you build the client?
Obviously the client is what should have the assets like meshes.
There should be more stuff in the editor log.
im running client and server builds
Did you at some point check whether the issue is fixed if you manually build it?
i believe that was the case, but i didnt check recently. I'll double check to make sure
You know what
I'm starting to believe it's not related to building
Forget this ever happened
Hey guys! I need an ocean in my game and I added hdrp water surface.
When i have a high repetition size the water search gives bad values and I was wondering if its possible to change the simulation (i get values from the sim in the shader)
this is a code channel...?
Yes it is. It being called #archived-code-general is a strong clue.
im not seeing how that's a code question
You may want to provide the code needing help, if it's related to code.
What function runs before start?
nothing is slated to run right before start
but Awake and OnEnable are other lifecycle messages that will be called before Start
That is what i needed, thx
okay so bascially how do i serialize a list<t> into json
{
SeqData data = new SeqData(dat);
var dirPath = projectPath + path;
var dir = System.IO.Path.GetDirectoryName(dirPath);
string jsonData = JsonConvert.SerializeObject(data);
print(jsonData);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
System.IO.File.WriteAllText(dirPath, jsonData);
}``` this function is meant to output
```[System.Serializable]
public class SeqData
{
public List<SequenceUnit> dat { get; set; }
public SeqData(List<SequenceUnit> dat_)
{
dat = dat_;
}
}``` this class, which contains a list of sequenceunit which has a whole bunch of stuff in it (yes i made sure all the variables were public)
so in thoery it should output a list of all the data in the sequenceunits in the list or thats what im trying to achieve at least
instead it outputs
{"dat":[]}
so it just does not serialize any of the objects in the list for some reason
how to i fix this and make this work
is SequenceUnit marked Serializable?
yes
public class SequenceUnit
{
public DialogueUnit dialogue { get; set; }
public bool hasDialogue { get; set; }
public List<PosRotScale> poses { get; set; } = new List<PosRotScale>();
first few lines of sequenceunit
public class PosRotScale
{
public Vector3 position { get; set; }
public Quaternion rotation { get; set; }
public Vector3 scale { get; set; }
posrotscale
public class DialogueUnit
{
public static DialogueUnit blank = new DialogueUnit("", 0, "", new Vector2());
public string Text { get; set; }
public int Voice { get; set; }
public string Metadata { get; set; }
public Vector2 screenpos { get; set; }```
dialogueunit
oh also to clarify im using newtonsoft.json rather than jsonutility
jsonutility has the same problem
Did you check the newtonsoft docs on how to serialize classes properly?
actually
At least with JsonUtility, you need to mark the properties as field serializable.
oh okay huh
donno about newtonsoft, but I wouldn't be surprised if it hase a similar limitation.
hows fieldserializable different to serializable
serializable and serialize are different attributes.
one says that the type can be serialized. The other actually tells the serializer that a field needs to be serialized.
This is all assuming JsonUtility. Don't know much about newtonsoft serializer.
should adding the [SerializeField] tag fix that?
& do i need to add it alongside [system.serializable]?
If it's a property, it needs to be [field: SerializeField]
properties are not fields
They're methods basically
with [field:...] it tells the compiler to apply the attribute to the backing field
okay neat, so i need to add it for every variable i want serialized?
neat lemme try it
oh huh
i have all of the variables in question public
ill try it anyway
if it doesnt work ill try doing it in jsonutility
okay isnt working in newtonsoft.json
in jsonutility it now outputs:
{"<dat>k__BackingField":[]}
Did you also mark the properties in SequenceUnit?
yes
Share the updated code then
public class SequenceUnit
{
[field: SerializeField]
public DialogueUnit dialogue { get; set; }
[field: SerializeField]
public bool hasDialogue { get; set; }
[field: SerializeField]
public List<PosRotScale> poses { get; set; } = new List<PosRotScale>();```
Okay. And that produces the result from earlier?
with newtonsoft.json, it outputs the same thing as before, yeah, however with jsonutility it outputs this
oh wait fuck i may be stupid
hold on
Are you sure the list is not empty?
ive just realized that yea
the list is empty...
i thought i had stuff in it but it mustve cleared somehow
probably while i was editing the code
okay well it appears to now be working
i am so sorry for wasting your time but thank you for your help
how can i apply a compile flag only on builds (but not normal editor compiles)
-# specifically disabling a warning
what i've tried:
- Project Settings > Player > Additional Compiler Arguments - also applies to editor
Assets/csc.rsp- also applies to editorAssets/msc.rsp- doesn't apply at all
My immediate thought is to write an editor script that sets the compiler arguments right before build.
is there a direct api for that? or would be through project settings?
i don't know my way around the editor api at all lol
I need help with localization.
LocalizedString titleDisplay = new LocalizedString(UIConstants.LOCALIZATION_TABLE_UI_KEY, UIConstants.LOCALIZATION_FORMAT_UPGRADE_RELIC);
titleDisplay["relicName"] = relicData.GetLocalizedName();
(titleDisplay["fromLevel"] as IntVariable).Value = fromLevel;
(titleDisplay["toLevel"] as IntVariable).Value = toLevel;
KeyNotFoundException: The given key 'fromLevel' was not present in the dictionary.
I have the right arguments
You are constructing a LocalizedString manually, so there's no IntVariable assigned. You'll need to set it yourself.
How is it usually done if not manually like this?
Serialised in the inspector
if i wanted to add to a rigidbody2D.velocity a variable of 90 degrees in either direction how would I accomplish that?
you mean angular velocity? you can modify velocity or add forces to a rigidbody
adding force via the functions is preferred unless you need to have lots of control over it
i mean something like whatever direction its going in, you add a couple of degrees to the left or right for it to rotate towards
you can add a force to push it in the direction you desire
Vector3 dir = myPos - targetPos;
dir.Normalize();
rb.AddForce(dir * multiplier);
i know, what im asking is how to calculate the new direction i desire, which would be a slightly rotated value from its original direction
if it was going straight up, 90 degrees, i would want it to at my command choose a new direction between 0 to 89 and 91 to 180
You can use a quaternion to rotate a vector by multiplying them together
im using this
{
rb.velocity = Vector2.zero;
float accuracy = Random.Range(90f, 270f);
Vector3 shootDirection = Quaternion.AngleAxis(accuracy - (accuracy / Mathf.PI), Vector3.forward) * direction;
direction = shootDirection;
rb.velocity = direction;
}```
but sometimes the speed slows to a crawl or it stops altogether
on collision
is it something to do with how velocity works?
(btw what you have as accuracy here would be more like the opposite, error or variance or delta)
oh sure
direction = (Vector2)transform.position + Random.insideUnitCircle; set at Start
{
rb = gameObject.GetComponent<Rigidbody2D>();
direction = (Vector2)transform.position + Random.insideUnitCircle;
rb.velocity = (direction - (Vector2)transform.position).normalized * speed;
}```
just to get the ball rolling so to speak
which value? shootdirection?
what direction starts as and what it ends as
how do you know it isn't just going towards the thing it just hit
what is this even for anyways lol it's so confusing
it starts away from walls
what's accuracy - (accuracy / Mathf.PI) supposed to be? you turn one of them into radians and then.. you subtract radians from degrees?
ill be honest i took this from a previous script i took and then tweaked it accordingly
why does direction have transform.position
that's not a direction, that's a position
chris please 😭
that's an issue because you treat it like a direction afterwards
in Start you treat direction like a position, so it thinks it's something like the yellow lines
in OnCollisionEnter2D you treat direction like a direction, so it thinks it's something like the green lines
the disagreement causes issues
@placid edge does that make sense
yes? i just used it to give me a random position in a circle around the object to start off with
yeah but it's a position, ie one of the yellow lines
afterwards in OnCollisionEnter I change direction to be whatever shootDirection calculates so its no longer using insideUnitCircle
velocity takes a relative position aka direction
the quaternion rotation also takes a direction/relative position, which, an absolute position is just relative to the origin. so it rotates around the origin instead of the object
oh i think i see wqhat you mean
but shootDirection relies on direction. you still have the issue. you aren't overwriting the value, you're transforming it from what it was
so i need to change the Random in direction to something else
that's not what im saying, no
Random.insideUnitCircle could be a direction relative to transform.position
by doing + transform.position to that, you make it absolute to the origin
just.. don't do the + transform.position
doing that has made the object much slower after collision
that makes sense, since your velocity's magnitude would be <= 1
(since it's inside the unit circle)
just scale that up to a speed you want
ah right, i have to re-add speed
ok no the speed is getting wild and fluctuating now
i mean.. that's what you told it to do?
oh wait the speed? yeah that shouldn't be changing, should just be velocity 
(demo)
could you show your current code?
{
rb = gameObject.GetComponent<Rigidbody2D>();
direction = Random.insideUnitCircle;
rb.velocity = (direction - (Vector2)transform.position).normalized * speed;
}
// Update is called once per frame
void FixedUpdate()
{
}
public void OnCollisionEnter2D(Collision2D collision)
{
//rb.velocity = Vector2.zero;
float variance = Random.Range(90f, 270f);
Vector3 shootDirection = Quaternion.AngleAxis(variance, Vector3.forward) * direction;
direction = shootDirection;
rb.velocity = direction * speed;
}```
oh whoops
sorry was messing with other code so had to Ctrl+Z a lot
but it was this
rb.velocity = (direction - (Vector2)transform.position).normalized * speed;
```this is still treating it as a position
also for direction do you want it to be normalized or are you relying on it also varying in magnitude?
i noticed you have a normalized on that assignment on Start but not anywhere else
frankly the main issue is that the speed isnt constant and is being affedtec by collisions
is normalized the reason?
no, but it means you don't get consistent speeds
in Start it's normalized and multiplied by speed
in OnCollisionEnter2D it's just multiplied by speed (of course also the rotation but that doesn't change the magnitude)
...should it not be affected by collisions?
the speed? no
like what are you trying to achieve here lol
just a ball that bounces around at a constant speed 😭
what's up with the collisions though?
it seems that when it collides with walls in a certain way or other balls the speed slows down or speeds up from its normal speed
oh that might be with the normalized
but that doesn't change "affected by collisions"
or maybe you just misdiagnosed the issue 
ive removed the normalized its still doing it
does it change direction?
yes
sorry of course it does
i mean, while not hitting anything, does it change direction on its own
so check if you've set up the rigidbody on the ball correctly
check linear drag and friction and stuff
wait wouldn't making it bounce somewhere in a 180° arc mean it can collide again
yyyyes? if there's something behind it when it collides
You need a physics material to make it be fully "bouncy" right?
uh you should probably have collision: continuous and interpolate: interpolate anyways
it's setting the velocity directly
@placid edge have you tried debugging the velocity (and its magnitude) that you assign to the rb?
also can you be more specific as to the incorrect behaviour you're seeing (or send a video)
theyre getting glued to walls now aaaaaaaa
but why do a random dir when a collision happens i dont understand
so it bounces away somewhere else
but what if it bounces into the same wall
instead of just getting stuck in 2 perfectly flat walls going left and right at 0 degrees forever
shouldn't it be an arc centered on the normal of the collision instead of an arc behind the velocity
yea it should either just be a reflected vector or an arc using the surface normal
no
where are you getting these conclusions lmao
im not good at understanding others
you should make the arc relative to the collision instead of relative to the incoming velocity (or both, but not just the incoming velocity)
for a believable bounce, at least
i tried using that with
rb.velocity = Vector2.Reflect(rb.velocity, hit.normal);```
but it didnt work
The collision has already happened at this point so reading from the velocity doesn't really work
Because the velocity was modified by the collision
A fix is to store your velocity in a Vector3 variable in FixedUpdate and use that variable in the collision method instead of rb.velocity
Yeah
the speed still becomes incosistent after colliding in certain situations
If you want to keep the same speed you can do that
Vector2 reflected = Vector2.Reflect(lastVelocity, hit.normal);
rb.velocity = reflected.normalized * lastVelocity.magnitude;```
The second line makes the new velocity the same length as the previous velocity
You can also use a speed float variable instead of lastVelocity.magnitude
i do have one yes
This is probably better if you want a constant speed
the behaviour seems to be working pretty good, but some collisions seem to stop it altogether, i think the issue is that there's corners it can get stuck on and it calculates multiple collisions at the same time so the velocity gets all weird? until it hits another wall or ball then it becomes normal again
im trying to capture some footage
this is with lastVelocity.magnitude which seems to slow down after wrid collisions, using * speed makes it more constant
Do they ever come to a complete stop if you use * speed?
no? though they do get stuck in corners all the same
So coming to a complete stop
yyyes
Like this guy
Idk, usually this type of bounce logic is done on way simpler geometry
yes they seem to love that corner lol
Why do you need to manually control the velocity reflection?
Could you just rely on the built in collisions but keep the speed?
i dont know man, im just trying my best
Try commenting out the OnCollisionEnter for now.
In FixedUpdate set the velocity's magnitude to the speed variable
Similiar to the second line here ^
i dont know how, am i also using Vector2.Reflect?
No, just do rb.velocity = rb.velocity.normalized * speed; in fixedupdate
ah normalize right
.normalized makes it a length of 1, then you multiply with speed to make it the speed you want
yes i did it without normalzie then thought wait that would go on forever lol
There might still be some edge cases where the ball gets stuck at zero velocity though, and normalizing a zero vector keeps it at zero
If that happens you might wanna just move it to a random direction or the last non-zero direction or something
is this the whole code? they're doing even less bouncing
Hmm show a video?
What line did you add to fixedupdate?
rb.velocity = rb.velocity.normalized * speed;
And you removed/commented out the oncollisionenter method?
yeah
🤔 Not sure then
Might wanna ask in #⚛️┃physics
Also use a physics material with high bounciness i guess
And play around with friction values
great, it causes new problems
how can this be this hard i just want to bounce things 😭
Is it possible to call a Visual Scripting custom event from c#? I found everything, but not the answer. This in the picture is the graph. This is the code:
public class UIOkDialog : UIDialog
{
[Header("OK-Dialog")]
[SerializeField] private Button okButton;
// Event triggered when the OK button is clicked
public UnityEvent onOkClicked;
private void Awake()
{
okButton.onClick.AddListener(() => _OnOkClicked().Forget());
}
public void RegisterOnOkClicked(GameObject target, string eventName)
{
onOkClicked.AddListener(() =>
{
target.GetComponent<ScriptMachine>().TriggerUnityEvent(eventName);
});
}
It's not working.
Please help 😒 I am a noob in Visual Scripting.
Try adding a log cs onOkClicked.AddListener(() => { Debug.Log("Clicked, has component: " + (GetComponent<ScriptMachine>() != null) + ", eventName: " + eventName); target.GetComponent<ScriptMachine>().TriggerUnityEvent(eventName); });
See if the log appears when you click the button
You didn't show some of the related code though
Yes, it says that the script machine component is null. But why? I am calling it from within a script machine.
And the game object of course has the script machine on it.
Oh sorry, the GetComponent in the log should be target.GetComponent
But yeah it shouldn't be null if you aren't getting a null reference exception from the TriggerUnityEvent line
Is eventName correct (onOkClicked)?
Yes: "Clicked, has component: True, eventName: onOkClicked"
Okay, well as far as C# goes that's all I can help, not familiar with visual scripting
One last thing that comes to mind is to make sure that eventName doesn't have any extra spaces at the end
Both in C# and in the graph
There's #763499475641172029
there's lots of similiarly named things here but are you expecting TriggerUnityEvent to invoke the serialized unity event field onOkClicked ? i think those are unrelated things, TriggerUnityEvent fires an event with the name "UnityEvent" in the VS event bus
And then how I do it? I just want to react in my Visual Script to the onOkClicked event in the UIOkDialog class.
Should you use TriggerEvent instead of TriggerUnityEvent?
it's not one i've used but i think the graph node that you can use for that event is just called "UnityEvent"
this one
I didn't mean that, but simon seems to be onto something
I'm looking at the docs and none of the methods have any explanations
i don't know what all these different event types are for haha, my current project uses only custom written event nodes so i've never touched these