#archived-code-advanced

1 messages ยท Page 183 of 1

plucky laurel
#

whats in the list?

#
foreach(var go in list)
  GameObject.Destroy(go);
wispy epoch
#

So i feel kinda dumb because i couldnt figure out how to implement that list idea with each game object and then manipulate them. Seemed complicated but now this explanation is making me think thats the only way. What i did was make separate functions for each of the 4 references i needed individually and set them in the singleton so i could call them. It seemed to work as i can again see the references in the editor on scene reload

plucky laurel
plucky laurel
#

code

maiden turtle
#

async Task Start() swallows exceptions? How do I make the engine await the task?

plucky laurel
#

that is insufficient to help you

orchid hinge
maiden turtle
#

I saw async void Start() and kind of giggled at that, because I know it won't work, but async Task Start() does not work either?

undone coral
orchid hinge
#

I have a problem, after instantiating a gameobject I cannot access jagged arrays for some reason. The arrays are created in the same script. It throws out a nullreference exception.
https://gdl.space/felegasuda.cs

undone coral
#

@maiden turtle use unitask, and do

void Start() {
 UniTask.Void(async () => { ... });
}

same as

void Start() {
 InnerStart().Forget()
}
async UniTaskVoid InnerStart() {
 ...
}
#

unity's default async execution context is bad

#

and the rules for how it treats Start, OnEnable, etc. when they're declare async are fuzzily defined

devout hare
orchid hinge
#

ok

orchid hinge
#

but like its fine when I try to call it on a different line in the script

orchid hinge
#

public float[][] neurons; this is in neuralNetwork

devout hare
#

ok, where do you create the array?

devout hare
#

that defines a variable

#

where do you put an array into it?

undone coral
#

not sure how that's possible. it should work fine with git

orchid hinge
devout hare
#

Not in that code you do

orchid hinge
#

?

azure hinge
#

like not clicking the GenerateDefaults button lol

undone coral
#

yeah

orchid hinge
undone coral
#

it sounds like you guys are not using git right now

azure hinge
devout hare
#

You create the sizes of the inner array (neurons[i])

#

you need to create neurons as well

orchid hinge
#

ok found the error sorry

undone coral
#

you can't use sizeof on a Vector3. users who want to manipulate raw memory, for the most part, of .net types should use the Marshal functions

final steeple
#

You should avoid Marshal when you can

#

You can sizeof a Vector3, it just requires unsafe context

#

Or you can use Unsafe.SizeOf which does the same thing

orchid hinge
final steeple
#

Marshal.SizeOf will give you the marshalled size which is different

orchid hinge
#

idk I thought it was some sort of weird error also ppl were talking there so I didnt want to annoy them

#

in code general too

final steeple
#

I'd elaborate further but I'm on mobile currently so typing it all out would be hell -- but know that this guidance comes from Microsoft developers working on .NET itself

#

Much of Marshal is essentially "legacy" as far as modern code should be concerned

plucky laurel
#

(like whole unity .net)

undone coral
#

yeah definitely.

flint sage
#

That contradicts what Zombie mentioned that it doesn't

final steeple
#

This is very close to what is done yeah

#

It doesn't use much extra storage because of how and what we encode

#

We only need a single component per pixel, not full rgb

#

Because the color is defined by the light

flint sage
#

Yeah that's the only thing I could think of

final steeple
#

Really though that's the easy part -- the hard part is actually generating those lightmaps to begin with

flint sage
#

Oh yeah

final steeple
#

You need to do a lot of "deconstruction" on the textures

flint sage
#

I don't even watn to get into that ๐Ÿ˜›

plucky laurel
#

@final steeple you are making a lightmapper?

final steeple
#

Not quite a lightmapper, just a system built on top of Unity's lightmappers

#

We can use enlighten, progressive, etc as a base

#

And we process their output into data that we use

plucky laurel
#

i see, waiting for someone to make runtime lightmapper

undone coral
#

(1) use [RuntimeInitializeOnLoad]. declare a private constructor. the rest you can fill in it. that's it.
(2) it sounds like you want to add an attribute to something. it's better to have the something strongly reference your code and invoke it every frame. otherwise, i suppose a regular list of weak references.

flint sage
plucky laurel
#

i only seen native libs

flint sage
#

I guess they might've quit after SRP

undone coral
#

@proven thorn DOTS doesn't really work, so i wouldn't recommend trying to build a game on top of it right now

final steeple
#

And if you aren't using DOTS, I have a guide on how to write a proper (imo) singleton for MonoBehaviours

plucky laurel
#

runtime lightmapper, something simple Q1/3 style, for retro shooters, imagine that

final steeple
undone coral
final steeple
#

So in theory if you wanted to do lightmapping at runtime you could run the BSP lightmapping tools externally

#

And then reload the map

undone coral
final steeple
#

Blender might be a bit heavyweight but it's a step in the right direction yeah

undone coral
#

i don't know if it supports the cinema light remapping workflows

#

for baking

final steeple
#

I imagine the biggest problem might be licensing

undone coral
#

nobody does that stuff

final steeple
#

Blender is GPL iirc

#

Though I suppose it depends on how you integrate it

regal olive
#

how to do weighted generation again? (with a ten percent chance, generate this)
and how do i do it with multiple outcomes? i know i could just generate a number between 0 and 1 and do the rest but what if i had for example:
outcome 1: 15% chance
outcome 2: 20% chance
outcome 3: 30% chance
outcome 4: 35% chance

plucky laurel
#

yeah blender as a dependency is a no no. there are libs for unwrapping, there is a foss native lightmapper, ive looked at it occasionally trying to picture if its viable

#

it all seems viable, but i would not be able to maintain any of that unless i wrote it

final steeple
#

It's certainly doable, just gotta weigh whether it's worth the effort

#

A fully featured lightmapper is a ton of work

#

Especially if you support hardware acceleration for it (which you should if you plan on doing this at runtime)

plucky laurel
#

yeah its kinda, if you do it, youd go for retro shooters for good, several titles on that tech.

#

i dont think youd need that much effort put into optimization and acceleration, as low res lightmaps would suffice

final steeple
#

We're planning on open sourcing the game we support BSP in (Dusk) under MIT so eventually more games can leverage that for modding

#

I kinda went a bit overboard lol, it supports a ton of variants of BSP

#

Source, Quake, Quake 2, Quake 3, GoldSrc, etc

#

Along with all the various variants per game

plucky laurel
#

have you seen Prodeus level editor?

final steeple
#

Yeah

plucky laurel
#

not brushes, but still, its kinda the ideal variant, integrated editing

final steeple
#

It's stored as brushes sort of

#

The map format is similar to Quake in that it's a text format set of brushes and stuff which later gets compiled into a bunch of meshes and other data

plucky laurel
#

in prodeus?

final steeple
#

Yeah

#

I looked into it a while back

plucky laurel
#

oh i mean its not really csg

final steeple
#

I don't mean the editor I mean the format it saves to

plucky laurel
#

ok

#

have you seen Poseidon asset?

final steeple
#

That I haven't

plucky laurel
#

its a first time i saw something like that, they do csg with actual meshes as brushes. Directly build levels with meshes, with all the materials etc, all csg

regal olive
#

how to do a foreach as an enum like so

enum Types {normal, medium, hard} 
foreach(var item in Types){Debug.Log(item.ToString())} 

>>>normal
>>>medium
>>>hard
flint sage
#

Enum.GetValues(typeof(Types))

regal olive
#

ty

solid elm
#

I want to call the overriden CalculateAccuracy() method of class FlickNormalScoreSystem, parent class ScoreSystem in child class FlickNormalWeaponManager of parent class WeaponManager.

FlickNormalWeaponManager.cs

public class FlickNormalWeaponManager : WeaponManager {
private FlickNormalScoreSystem flickNormalScoreSystem;

private void Awake() {
flickNormalScoreSystem = scoreSystem.gameObject.GetComponent<FlickNormalScoreSystem>();
}

private void Start() {
flickNormalScoreSystem = scoreSystem.gameObject.GetComponent<FlickNormalScoreSystem>();
}

protected override void GunShotLogic() {
flickNormalScoreSystem.CalculateAccuracy();
}
}

FlickNormalScoreSystem.cs

public class FlickNormalScoreSystem : ScoreSystem {
public override void CalculateAccuracy() {
//logic code
}
}
  • if i use the awake function it is straight giving error of null object reference.
  • if i use the start function it gives same error on flickNormalScoreSystem.CalculateAccuracy() method call.
unkempt nova
#

Parent class? Child class? Am I losing it, or are these not related at all?

fresh salmon
#

Yeah

#

The issue isn't related to inheritance

solid elm
#

its structured

undone coral
fresh salmon
#

The GetComponents didn't find so they returned null

undone coral
#

it's telling you what the error is: there's a null object reference

unkempt nova
#

If you just tried pasting, it was too big

solid elm
#

its not null i checked with null and debug log

#

it is just giving error on function call

fresh salmon
#

Post the stack trace

solid elm
unkempt nova
#

This just sounds like a race condition problem to me. Trying to load something else in another script before it had a chance to get it. Also, this should be in #๐Ÿ’ปโ”ƒcode-beginner

fresh salmon
#

Oh yeah you defo picked the wrong channel to ask in

unkempt nova
#

Ordered?

solid elm
#

script execution order

unkempt nova
#

Oh

fresh salmon
#

Post the stack trace. It's what's under the NullReferenceException error message, it points to where execution was when the error happened

solid elm
#

its only monobehaviour class giving error if i use non monobehavior class without inheritance than there is no error

undone coral
#

is there a pre-existing prometheus exporter / structured performance format for unity runtime?

solid elm
fresh salmon
#

Sample stack trace

System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.Main()

Points to Main method in my Program class, for my case. You'll have more lines like these with more information, such as line numbers

solid elm
#

NullReferenceException: Object reference not set to an instance of an object
FlickNormalWeaponManager.Awake () (at Assets/Scripts/Tasks/Flick Normal/FlickNormalWeaponManager.cs:11)
UnityEngine.GameObject:AddComponent()
GameManager:<SetupGameEnviornment>g__SetupFlickNormalTask|16_0() (at Assets/Scripts/Game Manager/GameManager.cs:88)
GameManager:SetupGameEnviornment() (at Assets/Scripts/Game Manager/GameManager.cs:76)
GameManager:Start() (at Assets/Scripts/Game Manager/GameManager.cs:46)

#

using Awake()

fresh salmon
#

Okay, so it happens on FlickNormalWeaponManager.cs line 11

#

Post what's on that line

solid elm
#

NullReferenceException: Object reference not set to an instance of an object
FlickNormalWeaponManager.GunShotLogic () (at Assets/Scripts/Tasks/Flick Normal/FlickNormalWeaponManager.cs:40)
FlickNormalWeaponManager.Update () (at Assets/Scripts/Tasks/Flick Normal/FlickNormalWeaponManager.cs:23)

#

using start()

solid elm
fresh salmon
#

Okay so scoreSystem was null

solid elm
#

its present in parent class working fine why null ? null during awake call ?

fresh salmon
#

How is it retrieved, ie. where do you assign a value to scoreSystem?

solid elm
#

Weapon manager Class parent of FlickNormalWeaponManage class

fresh salmon
#

Yeah I got that, but where do you put a value into that variable

solid elm
#

value ? you mean reference or logic for score system

fresh salmon
#

I mean where are you doing scoreSystem = something something;

#

If you're ever doing it

solid elm
#

its used in both parent and child classes

#

for calculations

fresh salmon
#

I'm not asking where it's used I'm asking where it's assigned a value

solid elm
#

bro its called referenced

#

XD

#

in the parent class

#

weapon manager

fresh salmon
#

No, it's called an assignment, when you do x = y, you assign x
And inheritance has nothing to do with whether the variables are assigned or not

#

It can still be in the parent class, unassigned

solid elm
#
scoreSystem = GameObject.FindGameObjectWithTag("ScoreSystem").GetComponent<ScoreSystem>();
#

Parent class

fresh salmon
#

Theeere we go

#

Is that in Awake?

solid elm
#

yes

fresh salmon
#

Is Awake overriden in the child class? If yes are there measures in place to run the parent's Awake, with virtual and override?

solid elm
#

no awake is not overriden should i override ?

#

in child class

fresh salmon
#

No that's good

fresh salmon
solid elm
#

if i use a non monobehavior class in FlickNormalWeaponManager, like FlickNormalScoreSystem flickNormalScoreSystem = new FlickNormalScoreSystem();

#

there are no errors

fresh salmon
#

Wait you're using new on MonoBehaviours?

#

That's not allowed

solid elm
#

no i am not

#

i just tested

fresh salmon
#

Alright

solid elm
#
scoreSystem = GameObject.FindGameObjectWithTag("ScoreSystem").GetComponent<ScoreSystem>();
        Debug.Assert(scoreSystem != null);
#

like this

fresh salmon
#

Yep

#

For good measures you would also want to check that this code is running at all, by doing a Debug.Log above those two lines

solid elm
#

its giving error on scene load

#

NullReferenceException: Object reference not set to an instance of an object
FlickNormalWeaponManager.Awake () (at Assets/Scripts/Tasks/Flick Normal/FlickNormalWeaponManager.cs:11)
UnityEngine.GameObject:AddComponent()
GameManager:<SetupGameEnviornment>g__SetupFlickNormalTask|16_0() (at Assets/Scripts/Game Manager/GameManager.cs:88)
GameManager:SetupGameEnviornment() (at Assets/Scripts/Game Manager/GameManager.cs:76)
GameManager:Start() (at Assets/Scripts/Game Manager/GameManager.cs:46)

#

is score system not referenced or what ?

fresh salmon
#

So the code on that line 11 is ran before the parent's Awake is executed

#

Or Awake isn't executed

solid elm
#

child class awake ran first ?

fresh salmon
#

You told me you didn't have Awake on the child class
First, make sure your code that finds the ScoreSystem runs

solid elm
#

parent class WeaponManager have object of score system referenced in awake, child class FlickNormalWeaponManager have object of flickNormalScoreSystem refrencing in awke via score system

#

i posted code ๐Ÿ˜ฆ

solid elm
#

๐Ÿ˜ฆ

fresh salmon
#

So both of them have Awake methods, the problem is that if you have the child class attached to an object then the child class's Awake will run, not the parent's

#

Check that this is the case by logging something in both Awakes

tough tulip
#

only the child will run unless you override a virtual method and call the virtual method from the overridden method

fresh salmon
#

Yep exactly

solid elm
#

bro child one runs first

#

๐Ÿ˜ฆ

#

that's the prob

#

so should i make override function and call it in parent's awake

fresh salmon
#

So make the parent Awake virtual, the child an override and in the child call the base implementation base.Awake();

solid elm
#

thanks ๐Ÿ™‚

#

but is awake overriden available ?

fresh salmon
#

As the base class' Awake is virtual yep

solid elm
#

thanks bro, one thing i learned i need to revise the oops principles xD

solid elm
#

f you

frozen imp
#

!warn 442885979104215042 Don't insult community members. You appropriate channels as directed.

thorn flintBOT
#

dynoSuccess STRENGTH#3425 has been warned.

frozen imp
#

*use , still asleep.

solid elm
#

bro we chilling

undone coral
#

if i have an object that could be an int, long, etc - number value type - how can i easily cast it to a double and also know it was a number type?
e.g.

if (value is asDouble double) {
  
}

will this be false for an int (because it's not a double) or true (desired, because I want to cast it to a double anyway)

#

essentially, is there a version of Convert.ToDouble(value) that does not throw exceptions

#

it just expands to if (blah is int X) if Blah is float Y...

pine tulip
#

can some one help me

fresh salmon
#

Do not cross-post.

pine tulip
#

ok

gray pulsar
undone coral
#

it's unclear if it actually does the conversion

gray pulsar
#

It does. It's as explicit cast

undone coral
#

so value as double? - is it null when value is an int? @gray pulsar

#

do you see why this is tricky

#

it's not bad to write the switch statement

#

i was just wondering if it already exists

gray pulsar
undone coral
#

is that how as works? the cast is defined for explicit casts

#

and it's not clear to me if as is an explicit cast

#

it's definitely not defined for a nullable type

frozen imp
#

Once you determine its type you would be able to cast it

#

It must be a manual process though.

The is, as, and typeof operators cannot be overloaded.

A user-defined type can't overload the () operator, but can define custom type conversions that can be performed by a cast expression. For more information, see User-defined conversion operators.```
undone coral
#
public class Program
{
    public static void Main()
    {
        object x = (int)3;
        var y = x as double?;
        Console.WriteLine(y.HasValue);
    }
}

prints False @gray pulsar

frozen imp
#

You have to (double)x it I think

undone coral
fresh salmon
#

You would get an exception in the face

#

It did for me

undone coral
undone coral
#

i suspect there must be a way to do this

#

in this example i can't tell the difference between a real NaN

frozen imp
#

I mean you should detect its type and cast it accordingly, I think?

undone coral
#

but it's easy

#

yes, that's what i'm doing in this example

#

i'm wondering if there is already a C# shorthand for this, and it sounds like there is not.

undone coral
fresh salmon
#

There isn't yet. .NET7 (preview) has generic math and the INumber interface. Set to release next November, maybe in Unity in 10 years :)

gray pulsar
fresh salmon
#

This could be disgusting but could you do something like this?

object x = // your number
if (double.TryParse(x.ToString(), out double num))
{
  Debug.Log(num);
}
undone coral
#

@fresh salmon "I rest my case"

#

"Your honor, my client was just innocently trying to parse the string representation of the victim at the wrong place at the wrong time"

#

judge: "The Jury finds you extremely guilty"

fresh salmon
#

I mean it looks like it's working

#

Just have to take care of cultures

final steeple
#

Never do string parsing without specifying culture settings

#

You should be passing CultureInfo.InvariantCulture to ensure consistent results

#

Otherwise things will break very easily once the code runs on a system with a different locale

undone coral
#

my switch statement works correctly

fresh salmon
#

That's the cleanest way you can get for now imo

undone coral
#

yeah

#

too bad

spare pond
#

How in zenject inject CinemachineVirtualCamera follow variable with specific id?

undone coral
#

does anyone have a good approach for breakpoints on exceptions in Rider?

#

ideally it only stops when code inside my Assets folder is in the call stack

#

but apparently "User code only" doesn't work at all

#

and not having that checked throws on all sorts of unity garbage

raw schooner
#

anyone know how to use TcpClient to host a local websocket a website can connect to?

#

ideally i'd like to connect to ws://localhost, but no examples i've found online work without a port

fresh salmon
#

There are also assets available as NuGet packages that do it all for you, if you want to host the server outside of Unity as a console app or Windows service for example

raw schooner
#

so, i'm having the issue that var client = server.AcceptTcpClient(); never completes

#

i'm guessing there has to be some connection already open or something like that?

fresh salmon
#

If the server is not running on the same computer check the firewall settings, otherwise check the URL+port number on both sides

raw schooner
#

no i mean, i'm doing this

using System.Net;
using System.Net.Sockets;

var server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();

var client = server.AcceptTcpClient();

Console.WriteLine("Connected.");
#

Connected. never prints

#

oh, nope, you're right

#

alright sick, thanks

#

so, i'm trying to send a simple string to the connecting website (it's a command that's supposed to execute some stuff). i know the command works, however, using the following code doesn't have any effect on the website;

using var writer = new StreamWriter(client.GetStream());
writer.Write("start");
#

what do i need to do instead?

#
using var stream = client.GetStream();
var bytes = Encoding.ASCII.GetBytes("start");
stream.Write(bytes, 0, bytes.Length);

this also doesn't appear to work

sour pond
#

Hello, I installed the inthehand.bluetooth nuget package with NuGetForUnity But i'm getting this error when pressing play

#
NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
InTheHand.Net.Sockets.BluetoothClient.PlatformInitialize () (at <b58b6f76775240448daecb704cc009f5>:0)
InTheHand.Net.Sockets.BluetoothClient..ctor () (at <b58b6f76775240448daecb704cc009f5>:0)
timber flame
#

There is a class with byte array field inside (2d or 3d does not matter). The values can change from outside the class Update(indices,newValue)
When setting some elements of the array to specific values, another method should be called as well to generate a new mesh based on the updated array.
Therefore, for some values, updating the array is enough but for specific values, in addition to updating the array, another method should be called to regenerate the mesh.
Defining a bool variable (dirty flag) and SetDirty is the right approach, right?

   _chunkObject.Update(indices,newValue);

   // call _chunkObject.GenerateMesh in the right place after all chunks are ready
// Chunk object class
public class ChunkObject{
    public void Update(Vector3Int[] indices, byte newValue){
       _chunk.Update(indices, newValue); // update the array
       // set shouldUpdateMesh based on newValue
       if(shouldUpdateMesh){
          IsDirty = true;
          UpdateMesh(); // only calculates triangles and vertices but not generate mesh
       }
    }
    public void GenerateMesh(){
      if(IsDirty){
        // generate mesh based on vertices and triangles calculated already
        IsDirty=false;
      }
    }
}
raw schooner
#

so, it would appear that my target website doesn't actually fully connect. it permanently stays on Connecting.... i'm fully sure that the issue does not lie with the website, though i can't quite figure out what's the issue...

humble onyx
honest hull
#

Is there a good way to make several atlas's(so say an albedo and a normal atlas) so that an object can have a single UV and be able to index into both atlas's if every object has 1 associated albedo texture, but only half of them have a normal texture?(I want to re-use the rects from the Albedo's PackTextures to place the normal textures on the normal atlas)

shy quest
#

Hi everyone. I am making a custom build process for Android that needs to use .aab and Split Application Binary (OBB) and other preprocesses.

My problem is that when I use my custom script the UnityStreamingAssetsPack folder is created separately and not integrated inside UnityDataAssetPack. This difference causes Google Play to reject the .aab file.

Any suggestions on how Unity compresses everything inside UnityDataAssetPack? or which method is called.

Thank you very much in advance. I attach an image of the file structure of the exported project.

regal olive
#

i have problems with my canvas scaler. it is set to scale with screensize, but if i change res (first pic) the images on the bottom left are getting displayed wrong. on original res (second pic) they are displayed right. could be an issue with my code, because the squares are getting instantiated
they have a parent, are getting instantiated like this:

curr = Instantiate(endRoom, parent: roomParent, position: new Vector3(room.x * 30 + xOffset, room.y * 30 + yOffset, 0), rotation: new Quaternion());

where xOffset is the space from the screen, room.x and room.y are just coordinates in a double nested list, 30 is the meant spacing between them.

#

^^ it seems to ignore that *30 ? i tried to set the positions manually, and when they align like they should (n * 30) it works, but they arent aligned that way, either the canvas scaler moves them or idk

#

instead of 30 (1366:768) it moves 63.6335 (16:9)

regal olive
#

i think i got it

#

OF COURSE

#

you need to use anchored position oh my god

#

how stupid am i

misty glade
#

Probably less than you think. ๐Ÿ˜‰

#

That UI reminds me of a MUD mapping tool I used a few decades ago.. zMUD

regal olive
#

nah i got this idea from dani (everyone knows dani) from this video: https://www.youtube.com/watch?v=YMWnwBpUgoI

Can I make another game in 2 days (48 hours)? Let's find out!
Download the game: https://danidev.itch.io/triangle-game
โžคDiscord - https://discord.gg/dani
โžคFacebook - https://www.facebook.com/DaniMilkman/
โžคTwitter - https://twitter.com/DaniDevYT
โžคSource code - Source code - https://github.com/DaniDevy/LudumDare45
โžคMusic by Evan King. Tracklist be...

โ–ถ Play video
undone coral
regal olive
long ivy
drifting escarp
#

Hey, i want to make my own backend and currently i search for best-practices to get data in my online game.
Basically: i use Photon Networking and dont have access or did anything to the server so i just handle all the clients.

I would need to get Data from a MongoDB and would like to also use Redis (Pub/Sub mostly for live updates). Is it a good practice to make a connection on each client to these databases or is it way better idea to make my own RESTful Service which then calls the internal functions and give back the result?
I am not sure about connecting from the client to MongoDB for example, because i feel bad that someone can decompile the game (idk how) and get the password and do their own changes in the database

flint sage
#

Never connect straight to your database from your user facing application

drifting escarp
#

Okay thx, most people i found say there is no problem but i was not sure about it ๐Ÿ˜„

#

Then i do a wrapper service in between them ๐Ÿ™‚

flint sage
#

Anything on the client side should be considered compromised

#

Any credentials your store there are compromised

#

If those credentials allow them to modify your database then that's terrible design

lucid girder
# drifting escarp Then i do a wrapper service in between them ๐Ÿ™‚

Yes. Set up a (or multiple) back-end that connects DBs and other APIs which it needs, and let the client send and recieve data to and from the back-end. That way you can also manipulate what needs to be sent. Say you fetch a huge list from a DB, but the client only needs a few entries, you do that on the back-end and only send the required data back to the client. Also remember to cache often used resources (like that huge list).

Also also, if there the client needs to have login credentials: remember to hash, encrypt, etc etc, before sending it to your back-end. And don't save it in plain text. Safety/Security is key!

drifting escarp
#

๐Ÿ‘

fresh basalt
#

Any ideas why RigidBody2D.cast doesn't hit anything? The direction is correct, tried printing it, increased the distance, nothing works
both the player and the ground have box colliders

flint sage
#

You need to use the 3d equivalent to hit box colliders

fresh basalt
#

ill change to tilemap colliders then

#

ty

raw schooner
# raw schooner so, it would appear that my target website doesn't actually fully connect. it pe...

@fresh salmon I got my tcpclient to connect and do the handshake. I can connect successfully now. However, disconnecting via the target website (there's simply a Disconnect button, which calls WebSocket.close()) doesn't appear to work.
Disconnecting sends a (what I assume to be) encoded message, but decoding it results in a message length of 0 (bytes[1] is 128). Is there another way to find out whether I'm supposed to disconnect the client?

#

Perhaps additionally, is there a better way to handle receiving messages besides checking the _tcpClient.Available property in an infinite loop?

fresh salmon
#

I think that trying to read the stream client-side when the server closed the connection results in an exception

#

Or, you could send a custom message that indicates "I'm about to end the connection!"

raw schooner
#

I tried using _tcpClient.Connected and _networkStream.CanRead, both of which remain true when I click disconnect

#

I'm not in control of the website, sadly

cedar ledge
#

does the general advise of not using null coalescing and such with Unity.Object apply to this situation?

using UnityEngine;

public class BGMusicManager : MonoBehaviour
{
    AudioClip bgMusicClip;
    AudioSource bgMusicSource;

    private void Awake()
    {
        bgMusicClip = GetComponent<AudioClip>() ?? throw new MissingReferenceException($"Missing {typeof(AudioClip).Name}");
        bgMusicSource = GetComponent<AudioSource>() ?? throw new MissingComponentException($"Missing {typeof(AudioSource).Name}");
    }

    private void Start()
    {
        bgMusicSource.clip = bgMusicClip;
        bgMusicSource.Play();
    }
}

Correct me if I'm wrong, but I feel like the funkiness around whether it's truly null or destroyed-fake-null is irrelevant during Awake(), no?

fresh salmon
#

I think that can safely be used here yeah. An alternative would be assertions:

Debug.Assert(bgMusicClip != null);

Which takes care of the semi-null shenanigans by using the overloaded operator

cedar ledge
#

interesting. would you recommend that over what I'm doing?

fresh salmon
#

It's less bulky and you have the possibility to pass a custom message as a second arg, so probably yes

raw schooner
#

typeof(AudioClip).Name?

cedar ledge
#

i changed it to nameof(bgMusicClip)

#

i was just messing around there lol

raw schooner
#

Anyway. Maybe I haven't looked at TcpClient's properties enough yet, but I'm not sure how else I can check whether the target website is attempting to close the connection

#

As long as my app is running, the connection is open (website remains on Disconnecting... when clicking the button to disconnect). Only once I close my app (i dispose of the stream, then the client, then the listener) does the disconnection finally go through (obviously, since the connection is completely terminated)

fresh salmon
raw schooner
#

This feels very expensive to do every loop iteration

wispy lion
cedar ledge
#

thank you!

fresh salmon
#

Gives a fake null if it doesn't exist? What is wrong with them lol

cedar ledge
#

can't wait for them to finish what they're working on so that they can maybe possibly in the future sometime if they feel like it move towards standard dotnet 6 and beyond

#

their system was written before fancy operators like the elvis operator ??= were added to csharp

fresh salmon
#

Yeah, pretty sure they'll eventually do that sice .NET Framework isn't receiving updates anymore

cedar ledge
#

i decided to experiment with sorcery. any idea why it doesn't throw the error? (the commented out code does throw the error)

plucky laurel
#

@cedar ledge check this

public static class Ext
{
    public static void EnsureComponent<T>(this Component owner, ref T reference) where T : Component
    {
        if (reference)
            return;

        owner.TryGetComponent(out reference);

        if(!reference)
        {
            Debug.LogException(new MissingReferenceException($"Missing {typeof(T).Name}"), owner.gameObject);
        }
    }
}

then

void Awake(){
                this.EnsureComponent(ref source);
                this.EnsureComponent(ref rigidbody);
                this.EnsureComponent(ref light);
}
cedar ledge
#

i have something like that in another project, but it's more for any serialized reference rather than components. we already have the RequireComponent() attribute for ensuring components

cedar ledge
#

ref on a reference only matters if you're assigning it to be a different reference

#

wait nevermind

#

i see how you're using out reference which is basically that

fresh salmon
cedar ledge
#

zamn

#

here i was thinking that not specifying would have it grab everything

fresh salmon
#

Got fooled once because of that yeah

cedar ledge
fresh salmon
#

Oh yep

plucky laurel
#

will exception carry stack trace if not thrown?

fresh salmon
#

Doesn't seem like it, new Exception().StackTrace returns null

cedar ledge
#

i think the throw keyword does the magic

#

actually it would have to

#

because catching an exception and rethrowing it is common practice for APIs to hide their irrelevant inner workings

#

that process "recalculates" the stack trace from that catch block

plucky laurel
#

yeah

#

makes sense guess you can wrap a call to trygetcomp into a method, throw there, try catch in the caller and log exception without rethrow

#

refering to what i wrote earlier

cedar ledge
#

should i make my professor grade this code:

var fields = typeof(BGMusicManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(f => f.GetCustomAttribute<RequiredReferenceAttribute>() != null).Select(f => (f.Name, Value: f.GetValue(this)));
foreach(var field in fields) if(field.Value == null) throw new MissingReferenceException($"Missing reference to {field.Name}");

-reflection
-linq
-tuple
-misc terrible formatting

plucky laurel
#

hold my beer

#
            string assemblypath = UnityEditorInternal.InternalEditorUtility.GetEditorAssemblyPath();
            var assembly = System.Reflection.Assembly.LoadFrom(assemblypath);
            var type = assembly.GetType("UnityEditor.SceneHierarchyWindow");
            var hierarchyfield = type.GetField("s_LastInteractedHierarchy", BindingFlags.NonPublic | BindingFlags.Static);
            var hierarchy = hierarchyfield.GetValue(type);
            var hierarchyType = hierarchy.GetType();
            var sceneviewfield = hierarchyType.GetField("m_SceneHierarchy", BindingFlags.NonPublic | BindingFlags.Instance);
            var sceneview = sceneviewfield.GetValue(hierarchy);
            var sceneviewType = sceneview.GetType();
            var treestatefield = sceneviewType.GetField("m_TreeViewState", BindingFlags.Instance | BindingFlags.NonPublic);
            var treestate = treestatefield.GetValue(sceneview);
            var expandedIdsField = treestate.GetType().GetField("m_ExpandedIDs", BindingFlags.Instance | BindingFlags.NonPublic);
            expandedIdsField.SetValue(treestate, new List<int>());
cedar ledge
#

beer at 7am? nice

#

honestly the only thing i hate about that is the m_ s_ prefix style

#

the hardcoded strings are a close second

fresh salmon
#

That, and for me the vars

raw schooner
#

Ugh, explicitly types

#

For me it's the unnecessary indentation for every line

plucky laurel
#
string assemblypath = UnityEditorInternal.InternalEditorUtility.GetEditorAssemblyPath();
            var assembly = System.Reflection.Assembly.LoadFrom(assemblypath);
            var type = assembly.GetType("UnityEditor.ProjectBrowser");
            var projectbrowserfield = type.GetField("s_LastInteractedProjectBrowser");
            var projectbrowser = projectbrowserfield.GetValue(type);
            var treestatefield = type.GetField("m_AssetTreeState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var treestate = treestatefield.GetValue(projectbrowser);
            var expandedIdsField = treestate.GetType().GetProperty("expandedIDs", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            var assetsFolder = AssetDatabase.LoadAssetAtPath("Assets", typeof(UnityEngine.Object));
            UnityEditorInternal.InternalEditorUtility.expandedProjectWindowItems = new int[1] { assetsFolder.GetInstanceID() };
            expandedIdsField.SetValue(treestate, new List<int>() { assetsFolder.GetInstanceID() }, null);
            type.InvokeMember("OnProjectChanged", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, projectbrowser, null);
cedar ledge
#

it's because it's copied from a method

plucky laurel
#

this took a while to crack

fresh salmon
#

Type implicitly if the type is clearly visible on the right side of the assignment, otherwise explicitly

raw schooner
#

Those don't happen to be the actual Unity internal fields right

plucky laurel
#

they are

raw schooner
#

Actually nevermind, not even possible i think

#

From the C++ source?

#

Surely not

plucky laurel
#

no, managed

cedar ledge
#

what's it called where the type is inferred by the variable's name

plucky laurel
#

in generics?

raw schooner
#

Implicit?

fresh salmon
#

Hungarian notation? nValue

cedar ledge
#

that's it

raw schooner
#

Oh, no

plucky laurel
#

ah you mean self describing code or something like that

#

aah gotcha

#

f_health, s_name

cedar ledge
#

vars are acceptable imo. i would prefer explicit types and no hungarian notation, but sometimes when you're game programming, you have things like AudioSource, AudioClip, AudioChannel, etc. where it's both difficult and pointless to name things not based on their type

plucky laurel
#

Single_health, Boolean_isAlive

cedar ledge
#

so if you're going to name things around their type anyway might as well var it up

fresh salmon
#

Yeah, just don't do

var x = SomeObscureMethodThatDoesSomething();
cedar ledge
#

i only do that when it's extremely inconsequential what the type of x is

plucky laurel
#

ive seen some machine learning code f, d, di, dx, u, ih ...

cedar ledge
#

graphics code

#

like shaders

#

UGH

plucky laurel
#

its dominant when the main thing is algorithm

cedar ledge
#

not only is IDE support utter garbage, but the variable name conventions do NOT help

plucky laurel
#

guess its easily inferred from the context if you know what youre doing

cedar ledge
#

if

plucky laurel
#

well if you work with ml algos, guess its a must you know how math is denoted

cedar ledge
#

speaking of math

#

any lurkers here ever studied Type Theory?

plucky laurel
#

like, how to type?

#

yeah i know how to type

cedar ledge
#

no it's like Set Theory or Category Theory. It's a foundational system of logic kind of thing

#

but Type Theory is a lot friendlier to programmer brains from what i can tell

#

Haskell and other functional programming concepts basically stem straight from it

plucky laurel
#

not me, never was interested

fresh salmon
#

Me neither, but Lisp has representation like these especially for conditions if ((< x 2) ... )

#

I find it really weird lol

cedar ledge
#

I don't think I changed anything significant here but now it's not throwing an error for any null fields

var fields = typeof(BGMusicManager)
    .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
    .Where(f => f.GetCustomAttribute<RequiredReferenceAttribute>() != null)
    .Select(f => (f.Name, f.GetValue(this)));
foreach(var (Name, Value) in fields)
    if(Value == null) throw new MissingReferenceException($"Missing reference to {Name}");
plucky laurel
#

maybe cast Value to Unity.Object?

#

not sure

cedar ledge
#

wow that actually did the trick

#

+1 rep

fresh salmon
#

And to top it off convert that to an extension method so you can do this.EnsureReferencesSet() in Awake

plucky laurel
#

also - cache reflection results per type in a dictionary

#

linq to for loops

#

the field getter to delegate

#

yeah basically a map of lists of delegates

cedar ledge
#

ive never done the caching thing, is it just storing the result of the reflection into a variable? just run that in OnValidate()?

#

why convert linq to for loops?

plucky laurel
#

no you lazily cache it

#

if its not in a static dictionary - do reflection, create a list of getter delegates

#

put in a dict, retreive on repeating calls

#

because linq is slower and allocates

cedar ledge
#

you do this inside the type itself, or in the static extension class?

plucky laurel
#

some global cached data store static class

cedar ledge
#

so the dictionary would be <Type, FieldInfo> or such?

plucky laurel
#

no <Type, Func<object,object>> i think

fresh salmon
# plucky laurel no you lazily cache it

Yeah lol made that error when I worked on some DB to type mapper, was painfully slow because I was calling Reflection for each row
Caching the stuff sped it up 10 times lmao

cedar ledge
#

if you're only storing a dictionary of type and a func what are you caching?

fresh salmon
#

The GetFields().Where()

#

This is expensive

plucky laurel
cedar ledge
#

that returns type IEnumerable<FieldInfo> not a Func<object, object>

plucky laurel
#

only problem that i didnt solve with this approach yet is that ... relfection data is not garbage collected

#

so every type you ever retreive is there to stay

plucky laurel
#

you can convert field.GetValue into a delegate

fresh salmon
cedar ledge
#

oh i see

plucky laurel
#

i have some code for that nearby

regal olive
cedar ledge
#

so you have a type and some field getters. last thing im confused about is how a 1D dictionary can store that. I feel like that would require Dictionary<Type, List<Func<>>>

plucky laurel
#

its for a setter but the approach is the same for getter

var method = (Action<object, object>)dynSetter.CreateDelegate(typeof(Action<object, object>))
#

Delegate.CreateDelegate basically

plucky laurel
#

you can wrap the info into your class with a del, name, whatever else info you need, attribute

cedar ledge
#

is there a way to simply do what ive already got, but put the awake code in the definition of the attribute?

plucky laurel
#

you mean use the attribute as the global static?

#

yeah makes sense even

cedar ledge
#
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class RequiredReferenceAttribute : Attribute
{
    private void Awake()
    {
        var fields = typeof(BGMusicManager)
            .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
            .Where(f => f.GetCustomAttribute<RequiredReferenceAttribute>() != null)
            .Select(f => (f.Name, f.GetValue(this) as UnityEngine.Object));
        foreach(var (Name, Value) in fields)
            if(Value == null)
                throw new MissingReferenceException($"Missing reference to {Name}");
    }
}
#

obviously that awake wont run

#

but you get my point

plucky laurel
#

well kinda, but at the same time, its dirty

#

attributes are traditionally just storing data

cedar ledge
#

so where do you typically make them do magic?

plucky laurel
#

static utility class

#
public static class RequiredReferenceCache{
...
}
cedar ledge
#

but i need awake, so i just stick that in a monolithic monobehavior that gets all fields from all types?

tribal pivot
#

Sure you dont need a (static) constructor?

plucky laurel
#

like that extension method from above

#

you can also run it in the editor on project change

#

omitting runtime completely

#

for even better results move it to a dll

#

it will then work even if the project fails to compile, so you wont miss anything because of it

#

now im thinking if project change detects any actual field changes, guess this route will have bunch of edge cases

sage radish
cedar ledge
#

no

#

don't worry about it, it's just for fun

#

i need to focus on getting this assignment done due tomorrow anyway

#

i'll delve more into fun generics reflection stuff later

#

this does the trick for now:

#
public static class Validator
{
    public static void Validate(this MonoBehaviour mb)
    {
        var fields = mb.GetType()
            .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
            .Where(f => f.GetCustomAttribute<RequiredReferenceAttribute>() != null)
            .Select(f => (f.Name, f.GetValue(mb) as UnityEngine.Object));
        foreach(var (Name, Value) in fields)
            if(Value == null)
                throw new MissingReferenceException($"Missing reference to {Name}");
    }
}

public class RequiredReferenceAttribute : Attribute
{ }
private void Awake()
{
    this.Validate();
}
#

๐Ÿ‘Œ

tribal pivot
#

private void Awake()
{
this.Validate();
}
Maybe you can make some editor script that, after you enter play mode, scans all components for this?

cedar ledge
#

an editor script that calls Validate() on each component in the scene?

#

what's the thing i need to search for to learn how to make a script that runs in edit mode AND runs without being in the scene?

hollow garden
#

or yano just cs public abstract class InsertName : MonoBehaviour { protected virtual void Awake() { this.Validate(); } } and then ```cs
public class Script : InsertName {

}

#

altho that feels weird

cedar ledge
#

yeah but i dont want everything to inherit like that lol

#

it gets more and more wonky the more weird features like that you want

plucky laurel
#

if you are mixing runtime here, you will get runtime overhead from the components that are interested themselves

#

if you are doing clean editor time, you will have to scan every prefab, every component in the project, which is slow, but its not runtime

tribal pivot
plucky laurel
#

detecting project change works in many cases, but im not sure how to deal with edits to components then

cedar ledge
#

that caused some funkiness

#

the yellow bits are leftover playmode tint lol

#

they arent going away

#

k that worked perfectly

#

feel free to add performance improvements but im gonna leave it at that for now

tribal pivot
#

Id personally not throw a missing ref exception. Its saying "Missing reference to abc, good luck finding it lol!"
I'd do a LogError, pass in the object that broke it in the context parameter. That way you know exactly what is missing, and where

cedar ledge
#

fair enough. i guess once you move the error away from the class its a pretty good idea to use that debug.logerror functionality to direct the programmer to the right place

hollow garden
#

could probably use TypeCache instead of reflection there

cedar ledge
#

im not familliar

hollow garden
cedar ledge
#
public static void Validate(this MonoBehaviour mb)
{
    var fields = TypeCache.GetFieldsWithAttribute(typeof(RequiredReferenceAttribute))
        .Select(f => (f.Name, f.GetValue(mb) as UnityEngine.Object));
    foreach(var (Name, Value) in fields)
        if(Value == null) Debug.LogError($"Missing reference to {Name}", mb);
}

works the same, nice

hollow garden
#

nice

cedar ledge
#

kinda cool that unity provides a way to get all fields from all cached types with the attribute just like that

hollow garden
#

yeah it's really useful in editor code

plucky laurel
#

oh yeah TypeCache never used, that one bypasses the gc issue, but for editor only sadly

flint sage
#

Wouldn't that also fail if you have a non UnityEngine.Object typed field with that attribute?

#

Which should be ignored rather than throw an error

cedar ledge
#

is Unity.Object the only thing that is a drag and drop reference in the editor?

plucky laurel
#

yeah afaik

flint sage
#

Yes

cedar ledge
#

so the attribute should have an error when put on something else

plucky laurel
#

you can copy paste other things, like SerializeReference refs, or anything with Odin

#

i dont know if it works in base unity, try right clicking some property in editor

cedar ledge
#

how do i filter so that i only select where the field is from a monobehavior

plucky laurel
#

declaring type afaik

fresh salmon
#

With something like that yeah

cedar ledge
#

there it is

fresh salmon
#

x.DeclaringType.IsAssignableTo(typeof(MonoBehaviour))?

plucky laurel
#

if(declaring.IsSubclassOf(typeof(MonoBehaviour)))

cedar ledge
#

i had .Where(f => f.DeclaringType == mb.GetType()) but it didnt filter it

plucky laurel
#

this is not how you use it

#
var fields = TypeCache.GetFieldsWithAttribute(typeof(RequiredReferenceAttribute))
#

this probably returns you all fields in the whole assembly

#

what does it return btw?

cedar ledge
#

yeah i only need the fields of the class im currently looping over

#

fieldinfocollection

plucky laurel
#

and whats an element of it?

#

i assume its some unity type

cedar ledge
#

FieldInfo

#

from Reflection

plucky laurel
#

weird

#

you should probably prefilter them by type, or do it somehow else

#

with current approach you are iterating all fields in the project and testing each, every time

cedar ledge
fresh salmon
#

I don't remember which one to use here, but the logic said "can the declaring type be assigned to a variable of type MB?" in my head

plucky laurel
#

yes its IsAssignableFrom

fresh salmon
#

And it seemed alright to me

#

Both exist

cedar ledge
#

i didnt see To

fresh salmon
#

Ah, To is .NET5 and above

#

That's why

plucky laurel
#

so on the left should be the type you want to cast to, and on the right what you want to cast

cedar ledge
#

should i just change it back to not using TypeCache? seems wasteful to loop over all fields of everything for each gameobject in the scene

plucky laurel
#

is that the only api you can use in it?

cedar ledge
#

which api

#

this bugger pops up in every project i make in any version of unity

#

๐Ÿ˜ 

plucky laurel
#

never goes away

cedar ledge
#

so it's not just me

plucky laurel
#

its gonna be year 2077 and its still be there, my guess

cedar ledge
#

.Where(f => f.FieldType.IsSubclassOf(typeof(UnityEngine.Object)))

#

i put it back to reflections and added that

#

it doesnt throw an error for my vector3 so it works

plucky laurel
#

This method also returns false if c and the current Type are equal.

#

keep in mind

cedar ledge
#

ugh

#

is there a better method or do i just add an or condition

plucky laurel
#

i think the only "pure" UnityEngine.Object is a "folder"

cedar ledge
#

thats wack

plucky laurel
#

youre probably safe

cedar ledge
#

i got it

#

just had to swap the object to the left

#

k i've officially overengineered my class-final-project-in-24-hours game

cedar ledge
#

doing a similar thing for AutoComponent

foreach(var f in fields)
{
    f.SetValue(mb, mb.GetComponent<>());
}
#

what should I put in the <> ?

tribal pivot
#

The type you want to get. But with generics, you need to know beforehand. You could use the non-generic variant if you dont

cedar ledge
#

f.SetValue(mb, mb.GetComponent<f.FieldType>());
complains that f is a variable but being used like a type

#

wait

#

i didn't even know there was a non generic version

#

f.SetValue(mb, mb.GetComponent(f.FieldType)); works

tribal pivot
cedar ledge
#

yeah i just wanted to know how to work around it and that worked perfectly

#

I'm doing f.SetValue(mb, mb.GetComponent(f.FieldType)); and it successfully finds the component but then it still has an NRE when i use it in Start() of the script

#

i think that the start is running first let me investigate that

#

does start run before playModeStateChanged?

austere jewel
#

Start is called before, pretty sure

cedar ledge
#

because im getting the debug log after the NRE from start

#

the debug log is called from playmodestatechange

#

NRE is from start

tribal pivot
#

And you're doing all this just so you dont have to drag it in?

cedar ledge
#

it's academic

tribal pivot
#

Yeah clearly

cedar ledge
#

๐Ÿ™‚

tribal pivot
#

๐Ÿ˜›

cedar ledge
#

๐Ÿ˜—

#

PostProcessSceneAttribute

granite viper
cedar ledge
#

i changed the intialize on load functionality to post process scene and everything works

#

if you ever wanted [AutoComponent] for automatically assigning your component references and [RequiredReference] for validating serialized fields when the scene plays (prevent forgetting to set them) here you go

#

i hope this isnt against the rules, i just dont want to flood the channel with even more of the same code

tribal pivot
#

Awesome, thanks for sharing!

cedar ledge
#

here's the usage just for quick reference

wicked pine
#

if i am currently drawing sprites in code in a horizontal line (in a for loop) for my player health (hearts / empty and full). I want to draw these along a bezier line. Is there a easy way to align sprites along a line in a UI? should I just forgo the drawing horizontally and just take a XY for each sprite? and manually draw them? Its for a UI and it goes along a curved background so I was thinking of either somehow drawing a line and aligning them all along the line? I do own ALINE 3rd party tool just in case that has any relevance, TLDR can i draw sprites along a curved line or should I make 10 points for 10 hearts and just manually asign them to the list of 10 points

#

in a UI canvas

proven hatch
#

Hey all, I've got a quick design question I've been going back and forth on in my head:
What is the best way to write maintainable C# MonoBehaviours?

It seems to me that we have the choice to either create larger, highly cohesive classes (Player) that become a massive burden to change and maintain due to size and complexity OR we create smaller classes (PlayerMovement, PlayerAttacking, PlayerInventory, PlayerHealth, etc) and split the functionality out making the classes easier to maintain but increasing the likelihood of bugs due to all the additional references that need to be wired up (either with requirecomponent or drag+drop in editor)

Any thoughts?

tribal pivot
#

Unity mostly works with components, and imo that works well.

#

I do avoid RequireComponent for the runtime overhead.
If you destroy a component it will search if there is no RequireComponent on it.

proven hatch
#

How do you handle the complexity of wiring up references?

#

seems like we open up all sorts of avenues for bugs

tribal pivot
#

How i do it is to have one central PlayerController, everyone links to that. And in turn, PlayerController also serializes a reference to the other components.

You could also only link from one to the other, making the dependencies very clear

proven hatch
tribal pivot
#

That guy above just made some RequireComponent, and AutoComponent.

We have something similar called GetComponent, which automatically grabs a reference when you open the inspector.

tribal pivot
proven hatch
#

Is this a component or a game object? (prefab, for example)

tribal pivot
#

Im sorry but the difference between a gameobject and a component is very big

#

A GameObject is a collection of components. Its a tag, a name, a bunch of components.

#

A projectile is a gameobject, with the components ProjectileMovement, ProjectileCollision, ParticleSystem.

proven hatch
#

Is "Head" not a "component" of a "Body"?

tribal pivot
#

No, it is a GameObject within a body, with a Transform component.

proven hatch
#

so you do not compose a Head with a Neck and so on to form your body?

wicked pine
#

and your brain is a gameObject nested inside your head ๐Ÿ˜„

tribal pivot
wicked pine
#

filled with all sorts of inactive unused deprecated components ๐Ÿ˜ฆ

proven hatch
#

...if it is composed then it is a component of the whole

#

you see what I'm getting at?

#

how do you know whether something should be a MonoBehaviour (component) or a GameObject (component)

tribal pivot
#

No, i think you're asking what the difference between a component and a gameobject is in code-advanced.

tribal pivot
proven hatch
#

obviously I wouldn't need to ask in discord for the answer in terms of code, the documentation is available

wicked pine
#

if you goto a store and ask the guy to help you pick out windows and then realize you were calling a door a window, you realize that terms matter

tribal pivot
cedar ledge
#

is there a way to fix the fact that visual studio thinks that a private serialized field is never assigned to, and suggests it should be readonly?

#

i dont think that somehow adding the relevant suppressmessage attribute to everything with the serializefield attribute in an editor script is the "right way"

#

mostly i dont want to clog up my code with a million pragma warning disables, and i do find that suggestion helpful sometimes

#

this was my first idea (AddAttribute is not a thing)

public static class SerializedSuppresor
{
    public static void Suppress(this MonoBehaviour mb)
    {
        var fields = mb.GetType()
            .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
            .Where(f => f.GetCustomAttribute<SerializeField>() != null);
        foreach(var field in fields)
            field.AddAttribute(new System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("IDE0044", "IDE0044"));
    }
    [InitializeOnLoadMethod]
    private static void SuppressEverything()
    {
        foreach(var mb in UnityEngine.Object.FindObjectsOfType<MonoBehaviour>())
            mb.Suppress();
    }
}
tribal pivot
#

Configure your ide to ignore the warnings?

cedar ledge
#

how do i configure it to only ignore it when the field has the serializefield attribute?

tribal pivot
#

I dont think thats possible out of the box

cedar ledge
#

darn

final steeple
#

They should be built-in if you install the Unity tools for VS

cedar ledge
#

i have it installed

#

hmmm

final steeple
cedar ledge
cedar ledge
#

is the best way to install this using the way you were showing me a while ago, or do i just do it from vs2022

final steeple
#

The easiest way would be to just install the VS extension yeah

#

You could embed the analyzers in the project but it's significantly more work

cedar ledge
#

it says that the analyzer should be included already

#

i did the vs code installation anyway and no dice

silk trench
#

I'm trying to use Rigidbody.AddExplosionForce(...) for rocket launchers in my game, and each player is a capsule collider. One problem that I've noticed, however, is that if the explosion is on the player but below its center, the player, they aren't launched into the air, but just pushed backwards.

#

Which makes sense if you think about it

#

But that's not the style that I'm going for

#

Is there a way to add explosion force based on the center of the player?

cedar ledge
#

for each hit, apply the force in the direction of (centerOfMass - explosionOrigin)

olive lion
#

Hello, I have a script Player that has an array of Tile gameObjects in specific positions.

As seen here, the blue board is the player and the gameObjects are those visible tiles.

I want to create a backup of those tiles which would basically be a duplicate array of the player's hand, by using deep cloning.

I wanted to ask if that's the appropriate action to take for an option to "Undo" the player's move if I can do something else.

quartz stratus
olive lion
#

I'm not sure I follow, what kind of an ID system?
I wanted at first to create an array of references themselves to the gameObjects so I can use them later on but I can't seem to think of a proper idea.

timber flame
#

There are some chunks and each contains voxels.
Is it standard to use IJob for each chunk and inside, utilize IJobParallelFor to calculate some math/calculation for each voxel?
Then after all chunks are ready (JobHandle.CompleteAll), render meshes.

foggy canyon
#

specialAttackCoolDownTimer -= Time.deltaTime; seems to be taking double the amount of time I think it should. I'm setting it to 6f but its taking 12 seconds to get to 0 in my update function

long ivy
#

what is Time.timeScale set to?

foggy canyon
brittle pumice
#

@plucky laurel so if I programmatically copy a static class/ file into my project I want to immediately execute one of the functions

#

There has to be some sorry Of attribute in unity that allows me to do this

#

I found [unityEditor.callback.didReloadScrip]

#

But that only trigger on second import

jovial totem
#

ok so. I need to make an A* Algorithm. But my node graph is a bit nonstandard, so I can't conceptualize it in my head.
My nodes have a position that they are in, and also a world, which is a completely separate space, and nodes can connect between worlds (like portals). However, the worlds' physical space do not line up; a node at (2,2) in world "Overworld" may connect to (0,0) in world "Dungeon". so how on earth do I do Heuristics for A*?

#

or do I need to do a separate pathfinding algorithm entirelty

dense tusk
dense tusk
#

In that case I'd take a theoretical view at how A* works. As you probably know, all it does is assign each spot on a grid a value depending on the destination (and other modifiers a dev might put in IE maybe a tile is a "quicksand" tile or something that might increase it's movement cost in A star), and then uses those values to find the fastest path to the destination.

While this is great for a single map, it gets far more complicated when stitching bits and pieces together (although it's of course doable).

Perhaps in this instance, you could simply use standard A star to path to the appropriate "portal" node and then repath after it enters a new "world"

#

though you might want to keep a pool of data for each world that includes where each portal leads etc. So you could theoretically have an entity path from World A to world Y by stringing together various paths to portals based on qualifying factors

jovial totem
#

Yeah Iโ€™m slowly coming to the conclusion that Iโ€™m going to have to do separate path finding for each world

#

Well. Since each world is a physical space, whenever the algorithm enters a portal it could adjust the coordinates of the new world to match like putting a pin through paper

#

This does not need to have unit accuracy

regal olive
#

I'd love it if someone could perhaps help me with Animation Events? I'm trying to figure out how to use the Object reference parameter with some custom object types (in my case, hitbox parameters, for instance). How do I use AnimationEvent objects, the docs are about as clear as muddy water lol

#

Some code for ref.

humble onyx
undone coral
#

is this your code?

undone coral
regal olive
# undone coral have you looked at ultimate fighting toolkit?

Yes, this is my code. I've implemented a "custom scripting" system using Scriptable Objects, and I want to translate them to Animation events created via code (clip.AddEvent(x). I'm using the AE's for timing purposes, as I can't seem to recreate perfect frame timing with my custom system alone.

worldly gorge
#

I posted this in code-beginner, I don't think this question belongs in there.

Using a compute shader, I call GetData() immediately after Dispatch(), is this good design? Or should I be calling Dispatch() as soon as possible and GetData() as late as possible similar to Unity's Job system?

olive lion
unkempt nova
#

So I'm making a spell that needs to make ice spikes in a radius around a target position. I'm using a Vogel spiral to pack them. GetSpiralPositions returns a list of positions corresponding to the positions in a spiral. I'm trying to "normalize" these positions, so that they all fit within a given radius by simply finding the magnitude of these positions, and then multiplying them all by a constant value calculated by the ratio of the radius to the maximum of these magnitudes.

Method:

public List<Vector2> GetSpiralPositions(int positions, float radius) {
        float theta = 0;
        float maxLength = 0;
        var returnValue = new List<Vector2>();

        // Algorithm adapted from http://www.smokycogs.com/blog/drawing-spirals-in-c-sharp/
        while (theta <= positions * 360) {
            theta += 137.5f;
            var currentRadius = Mathf.Sqrt(theta);
            var currentPosition = new Vector2(Mathf.Cos(theta / 180 * Mathf.PI), Mathf.Sin(theta / 180 * Mathf.PI)) * currentRadius;
            float length = currentPosition.magnitude;
            if (length > maxLength) {
                maxLength = length;
            }
            returnValue.Add(currentPosition);
        }
        Debug.LogFormat("MaxLength: {0}", maxLength);
        
        // Go through each return value and "renormalize" the values, so they fit in the radius.
        float normalizedMaxLength = 0;
        for (int i = 0; i < returnValue.Count; i++) {
            returnValue[i] *= radius / maxLength;
            float length = returnValue[i].magnitude;
            if (length > normalizedMaxLength) {
                normalizedMaxLength = length;
            }
        }
        Debug.LogFormat("NormalizedMaxLength: {0}", normalizedMaxLength);
        return returnValue;
    }

Full script: https://www.toptal.com/developers/hastebin/ulasegupuy.csharp
I am testing this by spawning a sphere with the same radius at the same position. I expect that all of the positions given by GetSpiralPositions to be inside of this larger sphere, but I'm getting them outside of it. Not sure why, any ideas? I'm calculating the max renormalized length and logging it, it's 5
Here's a pic of what I'm seeing, small spheres are in positions yielded by GetSpiralPositions

#

Pattern is correct though, just something weird with my "renormalization"

#

Also, I'm aware I have a currentRadius already and don't need to calculate length again, just wanted to be double sure. Trying to just use it yields the same result

glacial wedge
#

to reduce compile time each time I save one script in a big project I have to create .asmdef file or something to make unity compile only scripts in the folder where the script changes?

unkempt nova
#

Infallible Code did a video on them too, but they're still black magic to me

glacial wedge
#

I'm struggling with the options

#

what it means?

#

Which are the "predefined Assemblies"? It's the default "AssemblyCSharp" or what else?

thick birch
#

Is there a way to make a list into a property that checks if the element we are trying to get even exists or is within the array length?

#

The list is with a custom class also, if that matters cs private List<SlideDigit> digitsList = new(6);

scenic marlin
#

so im working on voxel game and i have no idea what to do now because this is nuts my max object size i was planing in bytes is large
(16ย 777ย 216 voxels) * (8 bytes) with gives me 128 MB per object
with is not good for streaming it in anyway (network,gpu,hard drive) and files will be large yes i can split it but problem stays the same
so i was thinking about using a bits instead of bytes

min bits i can store is 8 per byte
so lets say
"[0]0000000"
fist bit is a voxel state 0 full 1 empty with leave me with 7 bits to use
so i need to fit color data
with dynamic color is out i need to use palette any idea how to encode it

final size for object i can get is 16 mb

novel plinth
thick birch
novel plinth
#

do you think? ๐Ÿ˜ƒ

thick birch
#

what im doing is split the datetime time into separate digits and for each element of that class and do cs digitsList[0].SlideVertical(targetDigit, transitionTime);

#

i know of another way that involves formatting it into a string and just doing a for loop, but it feels like that one would have too much GC

final steeple
sick robin
#
    {
        if (!photonView.isMine)
        return;
        PhotonView target = collision.gameObject.GetComponent<PhotonView>();
        if(target != null && (!target.isMine || target.isSceneView))
        {
            if(target.tag == "Player")
            {
                target.RPC("ReduceHealth", PhotonTargets.AllBuffered, BulletDamage);
                Instantiate(bloodSplat, transform.position, Quaternion.identity);
            }

            this.GetComponent<PhotonView>().RPC("DestroyObject", PhotonTargets.AllBuffered);
        }
    } ```
#

Hello, i am trying to instantiate the bloodsplat particles when the player gets hit, however it only appears on the client side, it doesnt show up on the other clients side.

#

how can i make it so it appears on both sides

livid kraken
#

PhotonNetwork has a Instantiate implementation that will spawn object over the nerwork

#

Otherwise you got to call a rpc or raise your own netwotk event

brazen dragon
#

I've been working on an inventory system and I made my items scriptable objects. I then made a item database that has a list of items that I populated with my item assets. Then, when I want a certain item I'm doing an instantiate inside the item database on one of these items to get a copy.

I don't know if this is a good way to do it. Does it sound OK?

sly grove
#

Sounds fine

thick birch
#

Whats the problem for it assigning the previous duplicate element instead of the next one?

private void OnValidate()
    {
        SlideDigit[] allSlideDigit;

        allSlideDigit = GetComponentsInChildren<SlideDigit>();

        for (int i = 0; i < allSlideDigit.Length; i++)
        {
            if (!digitsList.Contains(allSlideDigit[i]))//if we dont have a class in the list
            {
                for (int j = 0; j < digitsList.Count; j++)
                {
                    if (digitsList[j] == null)//assing it to the free element
                    {
                        digitsList[j] = allSlideDigit[i];
                        break;
                    }
                }
            }
        }
    }
wooden cedar
#

I don't really understand your question or what you are trying to do

thick birch
wooden cedar
thick birch
#

foreach is also slower, plus its doing literally the sam ething in the end; i just went the for route

thick birch
#

it goes through the GetComponentsInChildren list, if one of the components it goes through isnt in the actual class's list, go through the class's list and if it finds an empty (null) element, assign it there

wooden cedar
# thick birch how is it unneeded?

The only thing you care about is if digitList[index] is null, so a huge chunk of your time spent in the for and if statements looping through elements is wasting time.

thick birch
#

๐Ÿค”

wooden cedar
#

You say it's faster, I say it's backwards. As 95% of the time it'll ignore the element at the last if null statement

#

Anyway you seem intent to do it the way you are so I won't nitpick and let you work through it how your comfortable

thick birch
#

i was just wondering why its not assigning the right element if its just one added element instead of the whole list

#

(like in the video)

wooden cedar
# thick birch i was just wondering why its not assigning the right element if its just one add...
    
private void OnValidate()
{
    // only gather null list item entries
    foreach (var listItem in digitsList.Where(x=>x==null) {

        // find missing children
        var firstMissingItem = allSlideDigit.FirstOrDefault(x=>!digitsList.Contains(x));

        // assign it if we found one
        if (firstMissingItem!=null)
            listItem = firstMissingItem;

    }
}

That's how I would tackle that. I havent tested the code, and you can separate it from LinQ if you want.

wooden cedar
thick birch
#

@wooden cedar these dont work as my code though; its assigning it differently

#

theres a reason why i have two for loops

#

theres an array, and a list

#

they are different

wooden cedar
#

I know

thick birch
#

the list can have less elements than the array

wooden cedar
#

I know

thick birch
#

๐Ÿค”

#

let me try the non-linq one

wooden cedar
#

You are going through a list, looking for empties, and assigning the first item missing from an array of children

thick birch
#

yup

#

wait no

#

looking through an array, checking if the element in the array is in the list , and if its not , assign it

wooden cedar
#

Well what you are actually doing is going through a list of children, checking if they are missing from the list, then checking if the list has any empties, and then assigning it to the list.

#

Which is backwards. Because if the list, which changes rarely, has no empties - the rest doesnt matter.

#

Hense, why I inverted it

thick birch
#

gotcha

wooden cedar
#

As it is, you are marching through all the children regardless of if the list even has an empty

thick birch
#

well your non-linq code has the same problem

#

unless i go from 0 elements to the chosen amount, it will just keep duplicating the last one

wooden cedar
#

I cant, eye ball wise, see why your original code was doing that either, i kind of hoped it was just a j vs i for loop issue. Sorry my friend

thick birch
#

weird

orchid hinge
#

This function is supposed to save my neural network and then later read the values from it and use them, idk why but it does not work https://gdl.space/ekayomivar.cs pls help

#

U dont need to understand neural networks

sly grove
#

Can you elaborate on "doesn't work"?

#

Are you getting errors?

#

Is the wrong thing writing to the file?

#

Is the wrong thing reading from the file?

#

Provide some details

sand mural
#

hey, I have a snippet that works until my character is rotated:

            Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );

            if( plane.Raycast( ray, out float distance ) )
            {
                Vector3 worldPoint = ray.GetPoint( distance );
                direction = ( (worldPoint - GunTip.position)  ).normalized;
                Direction = direction;
            }```
#

my character travels on Z

#

Im trying to shoot towards my mouse

orchid hinge
undone coral
# olive lion Yes!

sick. i think the best thing to do is, the UI "stages" the player's move, and then once they end their turn, it's committed. that seems clunkier though - how often will people undo?

undone coral
olive lion
#

In case you wonder how it looks here:

proven hatch
dire berry
#

Guys, would u rather use PlayerPrefs or create a custom static class that stores your data? And why?

novel wing
dire berry
#

Ok thankyou!

sly grove
#

Make a properly structured data class and serialize it

dire berry
#

Thank you very much

wraith wedge
#

hello so i have a problem with my game at the moment

#

so when i create a room it creates it but it doesnt show a join room button

#

it was working but then i added some unity assets and it doesnt work anymore

regal olive
rocky mica
#

yeah Unity sucks for fighting games

#

timing is extremely tricky

#

and if you want to implement rollback netcode you gotta reimplement half of unity stuff due to lack of determinism

regal olive
#

It's a shame, because Unity is so damn easy to use (for the most part). So really for this I have NO choice but to use the events. I didn't want to, but custom timing stuff is virtually impossible to implement.

rocky mica
#

yup yup

#

Best bet would to get UFE

#

it's a bit of a pita to use but at least it works

quartz stratus
regal olive
#

i don't know if this is the most appropriate place to post this but i can't find anything on google and it's making me go crazy, every time i scroll the inspector it has those trail things, at first i thought it was my monitor, but then i confirmed it happens on my other monitors too, secondly i tried to record it and sure enough that's what is being processed, if anyone has any solution please help me, i feel like jumping the boat and freaking out about my graphics card won't help, but i did notice something similar happening in KSP

#

it started today, i didn't update drivers or anything

rocky mica
#

UH

#

that looks like graphic card artifacting yeah

sage radish
regal olive
#

i have an RTX 3070, and no didn't update any drivers

sage radish
#

I would try that then

rocky mica
#

praying for that card

regal olive
#

yeah it served me well, got it for cheap at the height of the chip shortage too

regal olive
#

i also noticed that they only disappear when i move the mouse

#

could it be a unity screen refresh issue?

#

yeah updating the drivers didn't help

#

ok

#

thank God

#

i reset all my nvidia control panel settings and it seems to have fixed it

#

sorry for bothering you guys, i was just really worried about my gpu

regal olive
rocky mica
#

If you arent blending

#

then animation events would work

#

if you are blending then they wont, blended animations still send events

#

you would run into weird cases where cancelling some animation states would still send events

undone coral
# proven hatch "traditions" seems like an extreme anti-pattern.. no way to utilize knowledge of...

the value of an FPS is people's familiarity with it. modern warfare and fortnite, the last two FPSes with a large portion of the audience new to the genre, are based on decade + old engines. best not to innovate in the least interesting part of an FPS, the controls and weapon behaviors. behold, with the exception of maybe Portal long ago, there hasn't been a new idea in a weapon / FPS movement since

proven hatch
undone coral
#

unity is bad for FPSes, but i hear good things about Opsive's asset

#

if you were going to make an FPS, use unreal

#

like what is there to maintain? better to not maintain that stuff at all

proven hatch
#

I was referring to a more abstract concept than something that could be tied directly to a single genre

undone coral
#

there are gotchas in the biggest genres that should be memorized

#

lots of people try to make Metroidvanias with Unity for example

#

corgi 2.5d engine doesn't recreate it faithfully, but it's close enough

#

let moremountains maintain that stuff

proven hatch
#

Ahh I think Iโ€™ve encountered what youโ€™re talking about. Iโ€™d call those โ€œpatternsโ€ or โ€œimplementationsโ€

undone coral
#

otherwise, it's a giant single class

#

because that's what metroidvania codebases looked like

#

and they did things that are only possible with god classes

proven hatch
#

Right.. kinda makes the whole โ€œgame devโ€ concept less creative and more ritualistic

undone coral
#

i agree. making a metroidvania is a ritual

#

and yet look at the success of Shovel Knight

proven hatch
#

At what price, though? Learning very specific details of very specific OOP or Unity quirks

#

Step into a new language or platform and I might as well be a junior again ๐Ÿ˜”

undone coral
#

the ceremony of cloning the basics of a game at least puts a working build in front of you

proven hatch
#

Also semi-time-gated upward mobility in the industry

#

(Great conversation btw, thanks for indulging me)

#

Link?

frigid yoke
#

question, does anybody know of a method to get mouse position even when the app is running in the background? (while tabbed out)

sly grove
frigid yoke
#

found a solution

orchid hinge
#

This function is supposed to save my neural network and then later read the values from it and use them, idk why but it does not work https://gdl.space/ekayomivar.cs pls help. I dont get any errors however I do get weird behavor that should not happen(behaves very differently than what I saved)

#

Pls tag me

granite viper
#

@orchid hinge you should probably not be saving your floats as strings and parsing them

orchid hinge
#

What's wrong about that?

granite viper
#

someone correct me if I'm wrong but I don't know if serializing floats that way is lossless

orchid hinge
#

So like I lose some of the information?

granite viper
#

potentially yeah

orchid hinge
#

Like from 0.287637 it saves 0.28764

granite viper
#

or something like that

orchid hinge
#

Oh

granite viper
#

better to save the actual bytes of the float

orchid hinge
#

That seems kinda complicated ngl

orchid hinge
granite viper
#

you're making a neural network

orchid hinge
#

Ye

granite viper
#

and you're saying that saving the bytes of a float is complicated

#

๐Ÿค”

orchid hinge
#

Ye

#

Neural network is kinda easy when u don't do backpropagation

granite viper
orchid hinge
#

U just do prev neuron * weight (with each neuron) then u add a bias and sigmoid it

granite viper
#

cool beans

granite viper
#

which code

orchid hinge
#

the answer

flint sage
#

You'll need system.buffers

orchid hinge
#

alr

orchid hinge
flint sage
#

In that one minute, you found the system.buffers dll, downloaded it, and copied it into Unity?

orchid hinge
#

?

granite viper
#

which answer

orchid hinge
#

Ill just use an yt tutorial

granite viper
#

ok

#

I guess that's easier than being specific

orchid hinge
#

@granite viper Technically I could multiply my floats by 1000 when saving and then when reading divide them by 1000

granite viper
#

sure, that might help

#

it's really not that difficult to just write the bytes tho

#

you can convert the 32 bit number into hex and then it'd be an exact (string) representation

orchid hinge
#

I save them as txt so I could instead of saving them immediatelly just pass them through a formater and then save them

orchid hinge
#

tysm for ur help

#

Its like a dumbass sollution but that kinda suits me lol

granite viper
#

glad you figured out a fix

#

hey whatever works

orchid hinge
#

ye tysm again

foggy dew
#

do you have any ideas how to rotate overlapbox depends on player x movement

#

smth like this

#
    {
        var move = movement.Move;

        if(move == Vector3.zero) return null;

        return Physics.OverlapBox(transform.position + boxPos, boxSize, Quaternion.LookRotation(move.normalized, Vector3.up), interactableLayer);
    }```
#

I've tried this but its not working quite well, it works but like its happening with delay

chrome vault
#

im keeping getting this error

#

i dont know how can i fix that

devout hare
#

edit: not advanced question, keep it in code-beginner

humble leaf
#

@chrome vault Don't crosspost

regal olive
#

Is it possible to update value of random number after occurrence of one event

#

?

plucky laurel
#

show code, pseudo code, or anything that helps understand what you mean

shadow seal
#

Dw they crossposted

regal olive
plucky laurel
#

this is not an advanced question

regal olive
#

Can u please help

regal olive
#

@plucky laurel

lime vine
#

Hey, I'm not sure my question is advanced, but I'm seeking for knowledge about implementing AI that can fly through circles.
At the most basic version of it it's clear, but what if an agent is behind the circle and should get back to the track?

twilit parrot
#

I don't know if it is advanced but I needed to use RestSharp in my project due to API problems and the function that executes the request freezes the main thread even with coroutines. What would you suggest for this situation? Should I use another thread as the value is not required immediately?

random goblet
#

How I get this string in another script file?

tribal pivot
#

Thats not coding advanced. Thats code-beginner

undone coral
#

that said you probably do not need to use restsharp. are you trying to use an openapi generated client?

twilit parrot
#

yes

undone coral
#

use unitask and the async version of the generated client

twilit parrot
#

my problem wasn't the restsharp but the how I handled the response. Basically. I wrote wav file into disk with File.WriteAllBytes and it obviously creates a thread and makes the whole Unity wait.

undone coral
#

the blocking call is going to do just that... block

#

you can use the async write calls

twilit parrot
#

not my brightest day tbh

undone coral
#

you shouldn't be creating threads

#

use unitask / async await to do this stuff expressively

twilit parrot
#

Thank you. I will correct it.

undone coral
#

you're using openapi... you're already miles above everyone else here

rocky mica
#

uh no?

#

having the same script doesnt mean they have the same exact state

#

it's as simple as having a boolean to check if it was fired or not

tribal pivot
#

Which of the two should be destroyed?

rocky mica
#

then yeah, just have a boolean check if it was fired or not

#

it's trivial

tribal pivot
rocky mica
#

"i want the one that was fired to destroy"

tribal pivot
#

You'll need to be able to differentiate this. What does it mean to be already on the floor?

Is it the one with the lowest Y, or the one with a bool isOnTheFloor?

rocky mica
#

you have some kind of other script thats firing this prefab

tribal pivot
#

Please try to include as much information as possible

random goblet
rocky mica
#

I am afraid you will need to be more specific about your issue

#

is the prefab already a poison pool when its travelling? does it become one in contact? how does that work

#

you need to be more specific, we dont read minds

#

then again, just have a bool to differentiate them

#

your boss spawns those prefabs

#

you can use the boolean or a string or whatever variable you want to store its current state

#

the way I see it, if your prefab is travelling it has one state, and if its not it has another

#

your boss should set that on instantiation

#

and the projectile should change that when becoming stationary

#

well, now you know what to do ๐Ÿ˜„

wanton pagoda
#

let me think it through a bit

#

im just tired

#

of sitting coding 11h straight

#

xD

#
private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "PoisonPool")
        {
            //destroy other
        }

this should work right?

#

even if's the same "object" its not the same instance

rocky mica
#

that will destroy both most likely lol

#

or one of them, randomly

#

again, you need a way to differentiate them

wanton pagoda
#

no!

#

its working!

#

: D

#

i was just overthinking it

#

like an idiot

rocky mica
#

unless you are using the name for differentiating

#

which is...

#

uh...

#

questionable

wanton pagoda
#

im not

#

its destroying other

#

        if (other.gameObject.name == "PoisonPool")
        {
            Destroy(other.gameObject);
        }

rocky mica
wanton pagoda
#

but i can see why we both think it should destroy both tho

#

im a bit confused

#

what's going on xD

flat rain
#

so i have a monitor model
how can i make an "OS" in it
and be able to display it

devout hare
random goblet
#

How I set texture from path when player click on button?
I tried this, but don't work:

Material FloorPaint = Resources.Load("/Prefabs/GameData/Paints/Floor/Wood/Texture", typeof(Material)) as Material;
fresh salmon
#

Using Resources.Load requires your item to be in a valid resource folder. Means you need to have a folder named "Resources" that path is in. For you, anywhere under your Assets, it'll search for a Resources/Prefabs/GameData/Paints/Floor/Wood/ folder

shadow seal
#

The docs do tell you

#

And I should hope that at this level, we are reviewing the docs

rocky mica
#

you can load pngs as valid textures from any folder in windows

#

lol

fresh salmon
#

What?

rocky mica
#

but yeah, if you wanna use real Resources

#

you should use the resource folder

rocky mica
#

you can do it haha

shadow seal
#

We're loading a Unity Texture not a PNG