#archived-code-general

1 messages · Page 443 of 1

unkempt meadow
#

for rotation, I used moverotation and I thought that would check for collision while rotating but it doesn't

vestal arch
#

kinematic rbs don't check collision yeah

unkempt meadow
#

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

vestal arch
#

do the 2 methods you mentioned not work for dynamic rbs?

unkempt meadow
#

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

vestal arch
#

do you have interpolation on and collision continuous

unkempt meadow
#

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

vestal arch
#

don't trust chatgpt for anything lol

unkempt meadow
vestal arch
#

@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

vestal arch
unkempt meadow
#

but you said not to use forces? Isn't that just a kinematic rb?

vestal arch
#

no

#

"not using forces" is just.. not using forces

#

don't use AddForce, disable gravity, disable damping, freeze rotation, whatever

unkempt meadow
#

I thought you could just disable gravity with a dynamic rb

vestal arch
#

you can

unkempt meadow
#

ooooooh

vestal arch
#

that's what i'm telling you to do

unkempt meadow
#

so if I use a dynaamic rb and NOT move by addforce/velocity/etc and instead use moveposition

#

and moverotation

vestal arch
#

"disable gravity" would just be setting the gravity scale to 0 for example

unkempt meadow
#

it will work?

unkempt meadow
#

ok so now I'm confused

#

so you ARE telling me to use addforce to move

vestal arch
#

no, there's a 3rd option

unkempt meadow
#

yes?

vestal arch
#

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

unkempt meadow
#

set velocity?

vestal arch
#

yes

#

have you tried that

unkempt meadow
#

not sure if I did

vestal arch
#

eh more like have you considered that

#

since that doesn't seem to be on your mind lol

unkempt meadow
#

and does set velocity not use forces?

vestal arch
#

it just directly sets the velocity

unkempt meadow
#

so no bouncing and jiterring around?

vestal arch
#

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

unkempt meadow
#

and I would need to add torque for my rotations? that sounds like a force-y thing lol

vestal arch
unkempt meadow
#

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

vestal arch
#

it causes far more harm than good

unkempt meadow
#

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

night harness
#

if you can't find anything on the entire internet how is chat gpt gonna help 😛

unkempt meadow
night harness
#

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

unkempt meadow
#

so is it right? No one knows 😄

#

I think I even tested it and it didn't work but I can't remember

night harness
#

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

unkempt meadow
#

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

vestal arch
vestal arch
#

is it even faster lol

unkempt meadow
vestal arch
#

it absolutely is not 😂

unkempt meadow
#

sometimes when you make stupid errors like GetKeyDown instead of GetKey, it immediately identifies them

unkempt meadow
vestal arch
#

the ones i linked?

#

what are you looking for

vestal arch
#

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

unkempt meadow
#

It didn't say anything about angular velocity specifically

vestal arch
#

ok, what about it

#

(why are you opposed to forces anyways lol)

unkempt meadow
#

spins it around

#

jitters it around

#

bounces it

#

I tried forces and it was terrible

vestal arch
#

ok.. sounds like you didn't tune them and you blame forces as a whole?

unkempt meadow
#

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

vestal arch
#

were you also using moveposition at the same time as forces?

vestal arch
#

forces can be precise with a little math

unkempt meadow
#

I can't remember, but I guess I'll just have to try

#

nothing else remaining to do

vestal arch
#

if you're opposed to forces, have you tried velocity+angularVelocity yet lol

unkempt meadow
#

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

rigid island
#

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?

elder gust
#

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.

steady bobcat
rigid island
# steady bobcat There is some way i think to ref more .net assemblies using a file but I dont kn...

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

steady bobcat
#

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?

rigid island
steady bobcat
#

that probably depends on the license for mono/.net

rigid island
#

ohhh..isn't .NET open source? so is should be okay commercially?

#

idk if that covers all the DLLs dependencies, I guess it does?

steady bobcat
#

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

rigid island
#

true, better safe than sorry lol

#

I'll llook into it better.. thanks!

frigid saddle
#

One message removed from a suspended account.

rigid island
frigid saddle
#

One message removed from a suspended account.

frigid saddle
somber tapir
#

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.

quartz folio
#

Do you have a delegate that uses Unit, UnitEventArgs

somber tapir
quartz folio
#

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

somber tapir
#

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);
    }
}```
quartz folio
#

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

somber tapir
#

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:

late lion
#

Since Action is a generic type that supports contravariance, an Action<IDeactivate> can be assigned to a Action<Unit>.

somber tapir
#

I keep it in mind in case generics don't work for my case

lucid brook
#

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?

latent latch
#

if it works

cosmic rain
latent latch
#

If you're using rb then just doing a sphere and getting point of collision works too

lucid brook
latent latch
#

overlapsphere rather, but yeah that's an idea too

rigid island
#

spherecast is good if you need the surface normal and other hitInfo

lucid brook
#

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.

rigid island
#

true

latent latch
#

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

lucid brook
#

does overlap even work on stuff that doesn't have an rb?

latent latch
#

but cast has some issues of not working if it originates inside of the colldiers

rigid island
#

any physics queries only care about colliders

#

rigidbodies are irrelevant

lucid brook
#

good to know

latent latch
#

rb would allow you to use OnCollision methods vs just querying

lucid brook
#

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

rigid island
#

cant go wrong with rays

#

they are pretty cheap

latent latch
#

I think that's fine honestly unless you need more surface area

rigid island
#

they are just thin compared to sphere and such but you still only get 1 hit point anyway

lucid brook
#

yeah I use a sphere cast for that exact reason for my ground check

latent latch
#

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

rigid island
#

sameee. I do that for my AI initially to find the player and then rays for checking walls

hexed pecan
#

You dont want the cast to fit into places where your character cant fit

lucid brook
winter bramble
#

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)

cosmic rain
winter bramble
cosmic rain
#

You can look at the build report to see what exactly makes up the build size.

winter bramble
modern atlas
#

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

somber nacelle
leaden ice
#

sometimes that's ok, sometimes it's not. You should know the difference intimately if you plan to ignore it.

modern atlas
leaden ice
#

yes destroyedObject == null will be true, but destroyedObject is null will be false

valid estuary
#

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.

cosmic rain
tawny elkBOT
novel bough
maiden trellis
#
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

jaunty surge
#

hello

maiden trellis
jaunty surge
#

I was wondering if there was a way to automate this < like () and { }

#

@sleek bough

sleek bough
#

@jaunty surge don't ping people not in conversation with you. And if you are asking something make sure to provide context.

vestal arch
vestal arch
#

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 shrugsinjapanese

#

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

sleek bough
#

VS and Rider does

vestal arch
#

is it on by default?

sleek bough
#

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)

opaque crane
#

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?

ocean hollow
peak peak
#

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 ?

spice estuary
peak peak
quartz folio
peak peak
#

ok either I used it wrong or it does not work I just have to write [MovedFrom("oldSubclassname")] right ?

late lion
#

If the namespace has changed, you also need to specify that in another parameter.

peak peak
late lion
#

This is using [SerializeReference], right?

peak peak
peak peak
late lion
#

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.

peak peak
#

ah actually yes I do use SerializeReference I thought you mean the one for the class it self

late lion
#

Did the values come back if you renamed the classes back to their original names?

peak peak
#

I actually dont use any Version Contoll I just renamed the class in VS an then the values Changed in the Inspector

late lion
#

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.

peak peak
#

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

valid estuary
hexed pecan
#

(You did not share the code properly)

late lion
valid estuary
cosmic rain
#

Users on mobile are forced to download your files in order to help you.

peak peak
#

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

cosmic rain
valid estuary
#

I'll add a video later, but there's the code

peak peak
cosmic rain
valid estuary
#

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

fiery steeple
#

Is it possible to give a display name to elements inside an enum in Unity C# like in unreal with the property DisplayName ?

valid estuary
#

youi just want objects listed in a drop down for selection?

vestal arch
valid estuary
#

I think a Scriptable object is nore what you want

fiery steeple
steady bobcat
vestal arch
valid estuary
#
// 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

steady bobcat
#

enum MyCoolEnum { Foo = 1, Bar = 2}

#

Its not like cpp where the string value does not "exist" in builds

fiery steeple
valid estuary
#

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,
}```
steady bobcat
valid estuary
#

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

vestal arch
#

just like how it does field names

fiery steeple
steady bobcat
vestal arch
steady bobcat
#

im not talking about the unity inspector

fiery steeple
valid estuary
#

FertileSoilSubstrate Would show up like: Fertile Soil Substrate

vestal arch
#

@fiery steeple are you talking about the inspector or shown within the game

valid estuary
#

thats what he trying to ttell you

vestal arch
#

those are pretty different contexts

#

you mentioned inspector before, and this just isn't an issue in the inspector

steady bobcat
#
public enum MyCoolEnum { Hello_World }
    
MyCoolEnum a = MyCoolEnum.Hello_World;
Console.WriteLine($"{a.ToString().Replace("_", " ")}");
vestal arch
#

you could get the name via reflection and transform that, or you could also use an extension method

fiery steeple
valid estuary
#

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

late lion
#

But this has nothing to do with displaying it in game.

vestal arch
#
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

fiery steeple
steady bobcat
#

yay extension methods!

fiery steeple
#

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 🤔 ?

vestal arch
naive swallow
vestal arch
#

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)

fiery steeple
vestal arch
#

uh.. ok?

#

unity doesn't have c# 14

fiery steeple
#

oh

vestal arch
#

it's barely got c# 9 if i remember correctly

fiery steeple
#

why didn't Unity update to the last versions of C# ?

vestal arch
#

unity can't run c# directly

steady bobcat
#

It uses Mono which is old and shit

vestal arch
#

it uses an existing runtime, mono, which is old

steady bobcat
#

But they are making the effort to upgrade to the newer .NET CLR

vestal arch
#

unity's in the process of changing runtimes, but until then, we're stuck with old mono and thus old c#

fiery steeple
#

Do you think they would change that for the next Unity version (i.e Unity 7) ?

steady bobcat
#

we all hope so 🙏

valid estuary
#

Unity 2021.2 and later: Supports C# 9 features

fiery steeple
#

How long it took to switch from C# 8 to C# 9 ?

late lion
#

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

fiery steeple
#

so there's no average time between 2 versions that you can deduce from past version switching ?

valid estuary
#

it took them 1 year to go from 8 to 9

#

but you cant rely on that

vestal arch
#

completely different story

fiery steeple
#

like Start() Update(), etc...

vestal arch
#

...what?

#

how's that related

lean sail
vestal arch
#

those are unity apis

#

unity defines those

#

they aren't attached to c# versions/runtimes

hexed pecan
fiery steeple
vestal arch
#

no, separate things

fiery steeple
#

Oh ok

vestal arch
#

not an abbreviation

naive swallow
vestal arch
#

monobehaviour is just, "one behaviour" i think

naive swallow
#

Which Unity was based off of but no longer really needs and is kind of an albatross at this point

fiery steeple
late lion
#

I assume MonoBehaviour comes from when Mono was new and now you could make a behaviour using Mono.

hexed pecan
#

Unity used to support javascript and boo and they had to name the mono scripts something else than Behaviour to differentiate

vestal arch
#

and monoscript as well?

valid estuary
#

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.

hexed pecan
late lion
#

Well, UnityScript and Boo were both different languages that both compiled to .NET dlls and ran on Mono.

valid estuary
#

SO essentially they can change Mono to what ever they want and it wont really affect your scripting

naive swallow
vestal arch
valid estuary
#

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

late lion
#

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.

valid estuary
#

thats really minor...call me crazy but that doesnt really change anything. Its literally a bool

lean sail
#

theres a ton of differences just from the c# versions alone

valid estuary
#

so the real difference is it just supports more C# features?

late lion
#

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.

valid estuary
#

ah yeah the GC needs massive updates

late lion
#

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.

steady bobcat
#

well dont forget the incremental gc exists and is configurable

valid estuary
steady bobcat
#

If unity can replicate what S&Box is able to do (amazing hot reload) then I will be very happy

valid estuary
#

It say it run in incredmental by default though - not sure that worth touching? How would forcing a single spike be beneifical?

steady bobcat
#

Yea i wouldnt mess with it but maybe for some projects it would help

valid estuary
#

good to know its there i suppose

quick elbow
#

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.

vapid swift
#

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

valid estuary
#

both your freidn and you are local on the same pc?

vapid swift
#

right?

#

no

#

that's the point

#

I wanna make it work across devices and networks

valid estuary
#

127.0.0.1 <- Is always a default local address never someone elses machine

vapid swift
#

I thought that Unity Cloud somehow takes care of this

vapid swift
valid estuary
#

every machine has that address - the server needs a public Ip

vapid swift
#

yeah

valid estuary
#

127.0.0.1 can never be a public Ip

vapid swift
#

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?

valid estuary
#

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

vapid swift
#

Just need to configure firewall

#

inbound and outbound rule for port 7777 correct?

#

thank you very much @valid estuary ❤️

valid estuary
#

Docs say 7777 is correct

vestal arch
vapid swift
#

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?

daring cove
#

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?

rigid island
vapid swift
rigid island
#

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

rigid island
#

the process is exactly the same

vapid swift
#

do i need to run the game there?

rigid island
#

yes ofcourse

vapid swift
#

ufff

#

how

#

it's a debian server

#

linux

#

terminal only

rigid island
#

its very easy just run your game like normal

#

do you know how to run an app via terminal? its very easy

vapid swift
#

a game with GUI?

rigid island
#

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

vapid swift
#

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

rigid island
#

you don't need that

vapid swift
#

I would also have to change that?

rigid island
#

run it as Server rather than Host

vapid swift
#

okay okay I think

rigid island
#

NetworkManager.Singleton.StartServer()

vapid swift
#

I will do it with my own PC first

#

just allow UDP 7777

rigid island
#

yes

vapid swift
#

thank you

#

just type in my public ip right?

rigid island
#

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

vapid swift
#

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?

rigid island
#

yeah it should work if you just type it in the inspector if thats what you mean

vapid swift
#

yes

#

do I need to allow inbound AND outbound

#

for the specified port?

#

or is inbound alright

#

(firewall)

rigid island
#

just inbound

vapid swift
#

alright

#

thanks mate

lean sail
vapid swift
#

Subscribed to your Channel btw!

#

The videos look interesting

daring cove
# lean sail how would this ever work? ```cs _itemData = new ItemData(); ... return _itemDa...

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;
    }
}
rigid island
#

I need to start throwing some new stuff up haha been very busy lately

rigid island
lean sail
daring cove
#

How to go about converting to it without hardcoding a conversion?

lean sail
#

im not exactly sure why you need to set it up the way you've shown. just use the constructor

daring cove
lean sail
#

are you familiar with how inheritance works and constructors?

dusk apex
lean sail
#

if you just use the constructor as intended, it works as is

vapid swift
#

@rigid island

#

do i need to configure anything in my router?

#

port forwarding or something like that?

rigid island
#

yeah you have to open the port

vapid swift
#

because i tested with a friend and he can't connect when I host

rigid island
#

did you open 7777 udp ?

vapid swift
#

in my firewall yes

#

on my PC

rigid island
#

nah it needs to be on your router..

vapid swift
#

oh okay

#

XD

rigid island
#

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

daring cove
daring cove
#

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;
    }
}
vapid swift
#

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

vapid swift
#

😮

#

with my pc tho

#

I dont have it on my server yet

#

how is that supposed to work

dusk apex
rigid island
# vapid swift how is that supposed to work

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

lean sail
daring cove
rigid island
vapid swift
#

I can't open a game GUI in a terminal

rigid island
vapid swift
#

you said i should open the game

#

the game has a GUI

rigid island
#

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()

lean sail
# daring cove Oh yes this is what I was looking for thanks!

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

daring cove
vapid swift
#

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?

rigid island
vapid swift
#

yes

rigid island
dapper forge
#

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

steady bobcat
#

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

dapper forge
#

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

dapper forge
#

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

steady bobcat
#

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

dapper forge
#

I know but thats not the point, thanks for help tho!

steady bobcat
#

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

last island
#

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 🤔

steady bobcat
last island
#

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.

steady bobcat
#

That is true yea, guid size should be consistent (its ascii always right?)

last island
#

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.

steady bobcat
#

the doc says A GUID is a 128-bit integer (16 bytes) so it should be the same size always for a guid

last island
#

With the above approach I'm at least sure I always get the right size 🤞

steady bobcat
#

true, then technically it should be uint64 🤓

#

size_t ❤️

last island
#

aight

#

Time to refactor :U

steady bobcat
#

its all shit it needs to be re written!! /s

last island
#

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

steady bobcat
#

solutions like protobuf and bebop exist to do efficient binary serialization

compact spire
#

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...

▶ Play video
#

He really recommended Singleton's

naive swallow
#

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"

steady bobcat
#

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.

naive swallow
#

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

last island
#

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.

latent latch
#

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

last island
#

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

cold parrot
last island
#

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.

steady bobcat
#

yea 23 bytes seems like the correct length to me

#

4 + 16 + 1 + 1 + 1

last island
#

a byte just...disappears in transit??

steady bobcat
#

oh shit could be

#

how are you sending this?

last island
#

Straight to disk

#

And then read it later :U

steady bobcat
#

how is it written, file stream or somethin?

last island
#

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;
}
steady bobcat
#

if you check the file with something like hxd does it have the data you expect?

last island
#

I'll check

cold parrot
last island
#

Feel free to suggest.

steady bobcat
#

File.WriteAllBytes?

#

the more foolproof ways to read/write files

cold parrot
#

Binary writer is a serializer

#

you don’t need that if you have a byte array

night harness
last island
#

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

cold parrot
last island
#

The files are tiny

#

kb

steady bobcat
#

🤨 dirtybytes.SelectMany(x => x).ToArray();

cold parrot
#

Then writeAllBytes is best

last island
#

Little dirty bytes 👀

steady bobcat
#

some nice pointless linq + ToArray when you know the file size from the start 🤦

last island
#

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

cold parrot
last island
#

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;
}
steady bobcat
#
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

cold parrot
steady bobcat
#

you can just return null if it fails

last island
cold parrot
last island
#

Programming is the root of most of my evil

cold parrot
last island
#

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

steady bobcat
#

if you use File.WriteAllBytes() does it insert a 0 at the end?

prisma helm
#

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

last island
steady bobcat
late lion
cold parrot
#

He basically dismisses/recommends all patterns with very unspecific reasoning

#

I think the video doesn’t contribute to the education of the masses

dusk apex
# compact spire He really recommended Singleton's

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).

hexed pecan
#

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)

night harness
#

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

hexed pecan
#

Not saying tags are great, just saying it's probably usually the better option from those two Find methods

cold parrot
#

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

hexed pecan
cold parrot
#

when many developers cooperate some solo-dev roses start smelling like turds

compact spire
#

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.

leaden ice
#

!collab

tawny elkBOT
#

: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

fast timber
worthy hatch
#

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)

cosmic rain
#

Actually, even if you do, there still might need to be an import step.🤔

worthy hatch
#

yes i upload files with their metadata to the git server

#

so build server is definitely retrieving those

cosmic rain
lyric veldt
#

hey guys, is it possible to change the cinemachine gain value with code

worthy hatch
#

what this feels like, is -executeMethod arg might be causing the build to fire without importing assets first,

worthy hatch
#

ill add this to build script before calling the build and seeing if it works

cosmic rain
cosmic rain
lyric veldt
#

I didn't see anything about it

#

unless i missed it

lyric veldt
cosmic rain
lyric veldt
#

ok

lyric veldt
#

i only found

#

this but

#

i'm not sure how to acess it

#

access

worthy hatch
#

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 💀

cosmic rain
cosmic rain
somber nacelle
#

check your spelling

lyric veldt
cosmic rain
# lyric veldt

Perhaps it's compiled with that define being false. Are you using the input system in the project?

cosmic rain
# lyric veldt

And you're sure this here is within the component class?

lyric veldt
#

i think

#

pretty sure

cosmic rain
#

It could be a nested class

#

Double check

lyric veldt
#

I pressed the

#

edit script

#

button

cosmic rain
#

It could be a nested class ot struct

lyric veldt
worthy hatch
cosmic rain
lyric veldt
#

i do tho

#

wait do i have to compile first

#

or

#

and then

cosmic rain
cosmic rain
worthy hatch
#

I think defer might work due to it being this way

lyric veldt
cosmic rain
worthy hatch
lyric veldt
#

wait i figured it out

#

im stupid

#

nvm

#

sry

cosmic rain
worthy hatch
#

normally script compilation / asset import occurs once the banner is gone and the editor is loaded

worthy hatch
cosmic rain
#

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.

worthy hatch
#

i just run a batch script that executes unity.exe, pass in -executemethod arg, and run build using BuildPipeline.BuildPlayer() within that method

proud isle
#

who want help my game idea

worthy hatch
#

i think it needs to be deferred, with how the editor is behaving

somber nacelle
tawny elkBOT
#

: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

cosmic rain
worthy hatch
#

i made this before unity launched cloud services

#

idk what they changed/opened to the public

cosmic rain
worthy hatch
#

i was at one point, but ended up removing batch mode line cause i thought itd fix the issue

#

few months ago

proud isle
somber nacelle
#

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.

cosmic rain
#

In the simplest form -buildWindows64Player <pathname>

worthy hatch
#

for a headless windows server, how would you put in the args?

cosmic rain
worthy hatch
#

would it be

-standaloneBuildSubTarget 'Server' -buildTarget 'win64' -build 'path'

?

#

for a windows headless server

cosmic rain
worthy hatch
#

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

cosmic rain
#

It seems to be fine according to what I see in the docs.

worthy hatch
#

-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

cosmic rain
#

Docs:

Set the build profile saved at the given path as an active build profile (for example, -activeBuildProfile "Assets/Settings/Build Profiles/WindowsDemo.asset")
worthy hatch
#

i see, so i make the build asset in unity and just pass it into the arg

cosmic rain
#

Seems so.

#

The windows64player probably uses a default win64 profile

worthy hatch
#

man these server builds are taking stupidly long, i think the -buildWindows/Linux64Player is probably doing a regular player build rather than headless

worthy hatch
#

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

cosmic rain
#

It could

#

If it doesn't work, I'd have a look at the logs and make sure there are no errors or warnings.

worthy hatch
#

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

cosmic rain
#

Nnn... Wait, these are server builds??

#

Where do you build the client?

#

Obviously the client is what should have the assets like meshes.

cosmic rain
worthy hatch
#

im running client and server builds

oblique spoke
#

Did you at some point check whether the issue is fixed if you manually build it?

worthy hatch
#

i believe that was the case, but i didnt check recently. I'll double check to make sure

worthy hatch
#

You know what

#

I'm starting to believe it's not related to building

#

Forget this ever happened

sullen trail
#

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)

sullen trail
vestal arch
#

im not seeing how that's a code question

dusk apex
#

You may want to provide the code needing help, if it's related to code.

mossy shard
#

What function runs before start?

vestal arch
#

nothing is slated to run right before start

#

but Awake and OnEnable are other lifecycle messages that will be called before Start

hazy oxide
#

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

vestal arch
#

is SequenceUnit marked Serializable?

hazy oxide
#

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

cosmic rain
#

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.

hazy oxide
#

oh okay huh

cosmic rain
#

donno about newtonsoft, but I wouldn't be surprised if it hase a similar limitation.

hazy oxide
#

hows fieldserializable different to serializable

cosmic rain
#

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.

hazy oxide
#

should adding the [SerializeField] tag fix that?

#

& do i need to add it alongside [system.serializable]?

cosmic rain
#

properties are not fields

#

They're methods basically

#

with [field:...] it tells the compiler to apply the attribute to the backing field

hazy oxide
#

okay neat, so i need to add it for every variable i want serialized?

cosmic rain
#

Yes.

#

If it was a field, public should make it serialized by default

hazy oxide
#

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":[]}

cosmic rain
#

Did you also mark the properties in SequenceUnit?

hazy oxide
#

yes

cosmic rain
hazy oxide
#
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>();```
cosmic rain
hazy oxide
#

oh wait fuck i may be stupid

#

hold on

cosmic rain
#

Are you sure the list is not empty?

hazy oxide
#

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

vestal arch
#

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 editor
  • Assets/msc.rsp - doesn't apply at all
chilly surge
#

My immediate thought is to write an editor script that sets the compiler arguments right before build.

vestal arch
#

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

wild nebula
#

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

quartz folio
wild nebula
quartz folio
#

Serialised in the inspector

placid edge
#

if i wanted to add to a rigidbody2D.velocity a variable of 90 degrees in either direction how would I accomplish that?

steady bobcat
#

adding force via the functions is preferred unless you need to have lots of control over it

placid edge
#

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

steady bobcat
#

you can add a force to push it in the direction you desire

Vector3 dir = myPos - targetPos;
dir.Normalize();
rb.AddForce(dir * multiplier);
placid edge
#

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

steady bobcat
#

You can use a quaternion to rotate a vector by multiplying them together

vestal arch
#

or you could do a little math, not too hard for 2d

placid edge
#

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?

vestal arch
#

(btw what you have as accuracy here would be more like the opposite, error or variance or delta)

placid edge
#

oh sure

vestal arch
#

what's direction?

#

and have you tried logging the value out to debug?

placid edge
#

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

placid edge
vestal arch
#

what direction starts as and what it ends as

vestal arch
#

what is this even for anyways lol it's so confusing

placid edge
vestal arch
#

what's accuracy - (accuracy / Mathf.PI) supposed to be? you turn one of them into radians and then.. you subtract radians from degrees?

placid edge
#

ill be honest i took this from a previous script i took and then tweaked it accordingly

vestal arch
#

that's not a direction, that's a position

placid edge
#

chris please 😭

vestal arch
#

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

placid edge
#

yes? i just used it to give me a random position in a circle around the object to start off with

vestal arch
#

yeah but it's a position, ie one of the yellow lines

placid edge
#

afterwards in OnCollisionEnter I change direction to be whatever shootDirection calculates so its no longer using insideUnitCircle

vestal arch
#

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

placid edge
#

oh i think i see wqhat you mean

vestal arch
placid edge
#

so i need to change the Random in direction to something else

vestal arch
#

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

placid edge
#

doing that has made the object much slower after collision

vestal arch
#

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

placid edge
#

ah right, i have to re-add speed

#

ok no the speed is getting wild and fluctuating now

vestal arch
#

i mean.. that's what you told it to do?

#

oh wait the speed? yeah that shouldn't be changing, should just be velocity thonk

vestal arch
placid edge
#
    {
        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

vestal arch
#
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

placid edge
#

frankly the main issue is that the speed isnt constant and is being affedtec by collisions

#

is normalized the reason?

vestal arch
#

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)

vestal arch
placid edge
#

the speed? no

vestal arch
#

like what are you trying to achieve here lol

placid edge
#

just a ball that bounces around at a constant speed 😭

vestal arch
#

what's up with the collisions though?

placid edge
#

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

vestal arch
#

oh that might be with the normalized

#

but that doesn't change "affected by collisions"

#

or maybe you just misdiagnosed the issue shrugsinjapanese

placid edge
#

ive removed the normalized its still doing it

vestal arch
#

does it change direction?

placid edge
#

yes

vestal arch
#

sorry of course it does

#

i mean, while not hitting anything, does it change direction on its own

placid edge
#

no

#

it goes in a straight line until it collides

vestal arch
#

so check if you've set up the rigidbody on the ball correctly

#

check linear drag and friction and stuff

placid edge
#

ive tried Continous as well its the same thing

vestal arch
#

wait wouldn't making it bounce somewhere in a 180° arc mean it can collide again

placid edge
#

yyyyes? if there's something behind it when it collides

vestal arch
#

no i mean with the same object

#

anyways that's besides the point

steady bobcat
#

You need a physics material to make it be fully "bouncy" right?

vestal arch
#

uh you should probably have collision: continuous and interpolate: interpolate anyways

vestal arch
#

@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)

placid edge
steady bobcat
#

but why do a random dir when a collision happens i dont understand

placid edge
#

so it bounces away somewhere else

steady bobcat
#

but what if it bounces into the same wall

placid edge
#

instead of just getting stuck in 2 perfectly flat walls going left and right at 0 degrees forever

vestal arch
#

thonk shouldn't it be an arc centered on the normal of the collision instead of an arc behind the velocity

steady bobcat
#

yea it should either just be a reflected vector or an arc using the surface normal

placid edge
#

you're saying i sohuld make the arc smaller?

#

wait

vestal arch
#

where are you getting these conclusions lmao

placid edge
#

im not good at understanding others

vestal arch
#

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

placid edge
#

i tried using that with

        rb.velocity = Vector2.Reflect(rb.velocity, hit.normal);```
#

but it didnt work

hexed pecan
#

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

placid edge
#

ill try that

#

replacing rb.velocity in the code above?

hexed pecan
#

Yeah

placid edge
#

the speed still becomes incosistent after colliding in certain situations

hexed pecan
#

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

placid edge
#

i do have one yes

hexed pecan
placid edge
#

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

hexed pecan
#

Do they ever come to a complete stop if you use * speed?

placid edge
#

no? though they do get stuck in corners all the same

hexed pecan
#

So coming to a complete stop

placid edge
#

yyyes

hexed pecan
#

Like this guy

#

Idk, usually this type of bounce logic is done on way simpler geometry

placid edge
#

yes they seem to love that corner lol

hexed pecan
#

Why do you need to manually control the velocity reflection?

#

Could you just rely on the built in collisions but keep the speed?

placid edge
#

i dont know man, im just trying my best

hexed pecan
#

Try commenting out the OnCollisionEnter for now.
In FixedUpdate set the velocity's magnitude to the speed variable

hexed pecan
placid edge
#

i dont know how, am i also using Vector2.Reflect?

hexed pecan
#

No, just do rb.velocity = rb.velocity.normalized * speed; in fixedupdate

placid edge
#

ah normalize right

hexed pecan
#

.normalized makes it a length of 1, then you multiply with speed to make it the speed you want

placid edge
#

yes i did it without normalzie then thought wait that would go on forever lol

hexed pecan
#

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

placid edge
#

is this the whole code? they're doing even less bouncing

hexed pecan
#

Hmm show a video?

placid edge
hexed pecan
#

What line did you add to fixedupdate?

placid edge
#

rb.velocity = rb.velocity.normalized * speed;

hexed pecan
#

And you removed/commented out the oncollisionenter method?

placid edge
#

yeah

hexed pecan
#

🤔 Not sure then

#

Also use a physics material with high bounciness i guess

#

And play around with friction values

placid edge
#

great, it causes new problems

#

how can this be this hard i just want to bounce things 😭

ivory fjord
#

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.

hexed pecan
#

See if the log appears when you click the button

#

You didn't show some of the related code though

ivory fjord
#

And the game object of course has the script machine on it.

hexed pecan
#

But yeah it shouldn't be null if you aren't getting a null reference exception from the TriggerUnityEvent line

#

Is eventName correct (onOkClicked)?

ivory fjord
hexed pecan
#

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

thick terrace
#

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

ivory fjord
hexed pecan
#

Should you use TriggerEvent instead of TriggerUnityEvent?

ivory fjord
#

CustomEvent.Trigger(target, eventName);?

#

I'll try this.

thick terrace
#

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

hexed pecan
#

I'm looking at the docs and none of the methods have any explanations

thick terrace
#

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