#archived-code-advanced

1 messages ยท Page 98 of 1

frail umbra
#

It really depends on how you want to animate it

tired wyvern
#

it's a factory game written fully with structs & jobs so it goes fast.

I'm rendering all belts with rendermeshinstanced no matter what. as for buildings, either I use graphics.rendermesh to render the factory buildings too (ideally with a way to animate) or i make some system that spawns gameobjects purely to render the buildings, nothing else.

#

not sure what path to take because i don't know what my options are for animation with renderMesh

regal lava
#

seems complicated

#

I'd probably just scroll a texture over them haha

tired wyvern
#

texture scroll is good for belts, not sure how i could use it for buildings. *or what i could use it for rather

hardy jacinth
#

is this a 3d game?

tired wyvern
#

yes

hardy jacinth
#

hmm, I would look into skinned meshes first, and only after reading about them more trying to look into other things.

stoic otter
#

Does someone have experience to disable warnings with a csc.rsp its about the warning UNT0011 can i disable this somewhere?

thin mesa
#

why are you creating an instance of a scriptable object by calling its constructor manually?

stoic otter
#

because im caching a backup

#

thats why

frank moat
#

Hi, would anyone happen to know how to set the "rendering layer mask" when using Graphics.DrawMesh?
It's trivial to set it on a UnityEngine.Renderer, but I don't understand how to do it when rendering things manually.

I've looked around online but I've found no obvious way to do it.
Any help is appreciated!

vernal onyx
#

Is programming a functional inventory system that complicated or am I that stupid?

#

i programmed everything its just that when I drop an item which is at index 0, the item at index 1 goes back to index 0

hardy jacinth
#

inventory systems like that usually have numbered inventory slots

#

example: minecraft

sly grove
#

If you have a fixed number of slots in your inventory it would be better to use an array

#

(this also isn't exactly an advanced code topic)

somber tendon
#

A list still could work, just give it an ID that indicate it as empty

sly grove
#

I guess but it's super awkward

#

You would have to manually populate it with empty elements to begin with

regal lava
#

well, depends how complicated you make it, but once you start mixing types it becomes logic heavy

#

then comes the ui :)

vernal onyx
vernal onyx
vernal onyx
#

thanks people, I almost felt like I am so dumb

regal lava
#

and passing between these container types. It can be quite overwhelming

vernal onyx
frank moat
sly grove
hardy jacinth
frank moat
#

render layers deal with lighting and shadows

sly grove
frank moat
#

Is there some way to play nice with the rendering system then?

#

The end goal is just to render a lot of meshes without needing to have the overhead of a gameobject, mesh renderer and so on for each one.

sly grove
frank moat
#

that does seem promising... i'm currently looking into it...

frank moat
hardy jacinth
#

When using unity.properties package https://docs.unity3d.com/Packages/com.unity.properties@2.1/manual/index.html

  • can I reuse Property/IProperty and cache it?
  • can I simply get a property value if I know the property type and it's path, but the object (i.e. TContainer?) defining this property is only refrenced using it's based type Base? (i.e. can something like PropertyContainer.GetValue<Base, int>(someComponent, propertyPath) work?)
  • when I use [Unity.Properties.GeneratePropertyBagAttribute], is there any generated companion with generated paths to properties?
autumn elbow
#

Does anybody know why IDragHandler would not work?

sly grove
autumn elbow
#

Well I have a project I haven't worked on for a couple weeks, and before I stopped working on it my inventory system I had was working normally. Now that I have reopened the project recently, the inventory system has decided that nothing should work including dragging an item.

#

This is not the finished code for items but what I have so far:

sly grove
#

Also !code

thorn flintBOT
autumn elbow
#

How can I know if the script is running in the first place then?

sly grove
#

Basic/standard debugging techniques apply as always.

hardy jacinth
#

does unity.Properties package work with SerializedProperty ?

autumn elbow
sly grove
#

is OnDrag running?

autumn elbow
#

what I mean is the overall file that im having issues with is in scene.

#

and how would I know if OnDrag is working if I cant get it to work?

sly grove
autumn elbow
#

yes

sly grove
#

basic debugging techniques

#

Then it's working

#

So what exactly is NOT working?

autumn elbow
#

dragging an item

sly grove
#

in what way is it not working?

autumn elbow
#

it doesnt react to my mouse clicks whats so ever.

sly grove
#

But you just said OnDrag runs

#

so it does react

#

Are OnBeginDrag, OnDrag, and OnEndDrag all being called/running when you expect they should?

autumn elbow
#

well the way i got the script to debug.log is i quickly put in a start method inside

sly grove
#

So you still haven't actually checked if OnDrag is running

autumn elbow
#

ya, so how would i check that>

sly grove
#

We don't care about Start

autumn elbow
#

i know

sly grove
autumn elbow
#

Well my item just doesnt react to any mouse click so im just entirely lost

sly grove
#

I don't understand the confusion here

#

Check if the code is running

#

with basic debugging techniques

#

if it's NOT

#

then we learned something

#

but you have to first make that effort

autumn elbow
#

Well ive been trying

sly grove
#

I've explained the first thing you should try

#

come back when you've tried it

autumn elbow
#

i have debug.log's in each of my interfaces

sly grove
#

what do you mean "in the interfaces"?

#

You mean in the methods?

sly grove
autumn elbow
#

like ibegindrag, idraghandler

sly grove
#

those are interfaces

#

you can't add logs inside the interface

#

you can add logs inside your methods.

autumn elbow
#

i know i mean the methods

sly grove
autumn elbow
#

and none of them seem to work

sly grove
#

so they're not running

autumn elbow
#

yup

sly grove
#

So don't tell me they are like you did before ๐Ÿคฆ

#

Do you have an event system in the scene?

autumn elbow
#

no

#

let me add that and get back to you

sly grove
#

You need that

#

or it won't work

autumn elbow
#

Wow... I must have somehow accidentally deleted that lol. Thanks ๐Ÿ˜‚

#

sorry for making you lose brain cells๐Ÿ˜ข

misty glade
#

I'm looking for a super cheap / free option to collect some simple telemetry for my app (a puzzle game with hundreds of levels). I basically just one a single API endpoint that unity can call to log information. Ideally this API endpoint can write/append the data in the call to something like a google sheet.

Faster/simpler/cheaper is better. I do have azure infrastructure but I'd rather not spin up a web service and database for this single data point of telemetry. Azure databases are kinda stupidly expensive.

Any ideas?

#

Maybe google firebase..?

#

(Or has anyone used the new unity cloud stuff? is this the same as the old unity gaming services?)

hardy jacinth
#

super cheap / free -> look into oracle always free tier... buuuut... not sure if they have preemptive containers. Probably very inappropriate if you try to use it for actual prod, but good enough on prototype stage or something... Just be aware of their preemptive containers

#

beside that Firebase, maybe self-hosted supabase

#

I dunno, I'm also interested in answers to that question ๐Ÿ‘

misty glade
#

I'm gonna try out the new (old?) unity services analytics.. seems pretty shiny and quick and easy to setup.. I'm just sorta cringing at the pricing (since it's a low-LTV mobile product so high MAUs = really expensive costs)

#

But since we haven't launched yet.. we'll swap it out later if it isn't what we're thinking

languid remnant
#

Does anyone know how to make a simple AABB collision box around a rotated collider?

rigid widget
#

I've got a struct called Segment, formed by two Vector3 variables. To make things simpler, imagine I want to calculate the length of this Segment variable. I have two options of doing this, either like this

public struct Segment
    {
        public Vector3 Start;
        public Vector3 End;
        public Segment(Vector3 start, Vector3 end)
                {
                    Start = start;
                    End = end;
                    Direction = (End - start).normalized;
                    Length = Vector3.Distance(start, end);
                }

or like this

public struct Segment
    {
        public Vector3 Start;
        public Vector3 End;
        public Segment(Vector3 start, Vector3 end)
        {
            Start = start;
            End = end;

        }

        public Vector3 Direction()
        {
            return (End - Start).normalized;
        }

        public float Length()
        {
            return Vector3.Distance(Start, End);
        }
    }```

Which of both would you recommend me to use? As far as I know the former would store the data forever while the latter would calculate it on the fly. For such a simple struct I'm unsure of which would be best
misty glade
#

the first use case will be correct if you're accessing it more than once or twice over the lifetime of the struct; the second use case will be correct if you're creating/deleting these en masse and only using direction/length once or twice - ie, what is your constraint, CPU or memory

#

also I'd change Direction() and Length() in the second to properties (methods should be verbs, and property-ish methods should just be properties):

public struct Segment
{
  public Vector3 Direction => (End - Start).normalized;
}
rigid widget
#

Right, I always forget about lambda expressions

misty glade
#

exact same thing, tbh, but then it's easier to remember externally ("is it .Direction or .Direction()?")... whereas if you really want to remember that you're doing an expensive calculation, you could name it GetCalculatedDirection() or something.. a bit more verbose but then clear in the name of the method that it's doing some shit

shut hedge
#

Does anyone know how the assembly is called which I need to reference to use Unity.VFX?

#

Or more generally, if it says assembly is missing: How do I find out what I have to reference?

wooden moat
#
Stream stream = new MemoryStream(file.bytes);
        BinaryReader br = new BinaryReader(stream);
        
        int dataVal = br.ReadByte();
        BitArray bitArray = new BitArray(dataVal);

        Debug.Log(bitArray.Length);

        for (int i = 0; i < bitArray.Length; i++)
        {
            Debug.Log(bitArray[i]);
        }

Hi, im trying to use bitarray to make an array of bits of a byte, but for some reason instead of working how i expected it to (an array of bools of length 8) it makes an array the size of the binary number, with every value being false

#

IE hex of FF would make an array of length 255 with every value being false

long ivy
#

did you look at the documentation? it's working as intended based on your description

wooden moat
#

the documentation doesn't have everything as false surely every value being false is kinda pointless idk

#

how would i achieve what i want then?

long ivy
wooden moat
#

is the byte being read from readbyte not what's assigned to bitarray?

long ivy
#

we're back at the documentation now. No

wooden moat
#

i wanna make a bitarray with the values of the byte read from readbyte

long ivy
wooden moat
#

this is still getting bytes though how do i convert that to an array of bools

long ivy
#

how were you going to do it with the BitArray? How are you packing the data in the first place? You could just convert a bit at a time

wooden moat
#

like i wanna read the first 8 bits and get an array of [1, 0, 1, 0, 1, 0, 1, 0]

wooden moat
long ivy
#

so create a bool array of length 8, and check each bit

untold moth
mild cairn
#

I have a question, I know you can't have multiple inheritance.
I have two asset packagaes: MoreMountains TopDown Engine and Databrain
How to have a class that inherit from Dataobject (Databrain) and InventoryItem (TopDown Engine) at the same time?

regal lava
#
public MyClass : Monobehaviour
{
  public DataObject DataObject;
  public InventoryItem InventoryItem:
}```
mild cairn
#

Sorry I forgot to mention both are from Scriptable objects

regal lava
#

Similar idea, just make a class of ScriptableObject

mild cairn
#

So,
If I inherit from DataObject (I can view that scriptable object in Databrain editor window)
If I inherit from InventoryItem (I can use the whole inventory engine with that scriptable object item)

If I do it like your suggestion, I can't see the object in the Databrain editor window and I have to still have the InventoryItem scriptable object item created

I was thinking how to merge both so that I can handle the InventoryItem in the Databrain editor window

regal lava
#

not sure what these packages are, but if this Databrain is some standalone asset that works on other assets, I wouldn't expect you to have to actually restruct the package data

mild cairn
#

I was thinking of going in the asset package and doing this:
public InventoryItem : DataObject
But I can't because the asset packages are like isolated? You can only build on them through inheritance

mighty marsh
#

So I have a silly: I am currently using the Unity Rendering Pipeline. I am currently first rendering a "mask" which is saved to stencil. This mask is just a rendering layer so everything on it is part of the mask. I want to add some blur to this effect to soft out rough edges. Is there any way to apply a blur to one layer? I am working in 2D

#

Example Object that renders the mask

#

Render passes(in order)

regal lava
#

Shaders and post processing / camera deals more with that

#

stencils for pixel replacement and rendering order specifics (also used for discarding pixels)

plush pasture
#

Hello, I have a small programming question: we are given a shape(polygon made of squares) like in the picture, the goal is to find its corners like highlighted in red. the squares are described by a list of int tuples that desribe its location in the grid. what's the best way to get the coordinates of the corner points in red?

shy nebula
#

check if each point has at least 2 adjacent black faces and at least one white face. also check if the black faces are not on the same axis if it is just 2 black faces that are touching, because otherwise it'll consider a straight line of blocks to have corners.

shut surge
#

Hey all, anyone know a way that I could disable ENABLE_UNITY_COLLECTIONS_CHECKS in the editor?

tiny pewter
#

simplified convex hull walk (take the idea is rotate the line anti clockwise) should work, dfs and find a random outermost cell and generate the coordinate of one corner, then try to always walk in one direction, if fails, rotate the direction by 90deg anti clockwise

shy nebula
#

like a ~~9x9 ~~3x3 where number 5 is a white square and everything else is black

#

sorry i meant 3x3 lol

tiny pewter
#

i understand, the algorithm is the same (for each current corner point detect the next corner point by checking if there is a cell blocking it), but now the problem become how to detect the "hole" inside

shy nebula
#

yes im not sure how that would be implemented inside of a convex hull algorithm

#

maybe another algorithm just for this issue in particular ๐Ÿคทโ€โ™‚๏ธ

tiny pewter
#

not convex hull, i just take some idea from it

#

time taken should be O(2* number of tile)

#

not "walking" on the tile but walking on the corners of them

shy nebula
plush pasture
#

damn I would never have thought about that thanks @tiny pewter

tiny pewter
#

btw the "next corner" calculated depends on the direction you walk

#

or simply coordinate+ direction*tile length

shy nebula
plush pasture
tiny pewter
#

detect "holes" is some way harder, i only come up with a solution done in O(size of AABB of the shape), ie floodfill

obsidian glade
#

think it should work in all cases

shy nebula
obsidian glade
#

just noticed the pattern, but it's quite similar to how marching squares/cubes works as well

somber swift
kindred tusk
#

Does anyone know how to hook into the generation of the csproj file to modify it?

upbeat path
kindred tusk
#

To change options that unity doesn't support

#

I don't think it really matters for the question. Basically unity will regenerate the file and I want to hook in and modify each time.

upbeat path
shy nebula
kindred tusk
#

Sorry your idea isn't beautiful

#

Beauty is in the eye of the beholder

shy nebula
#

I'm not afraid to admit you're right ๐Ÿ˜…

kindred tusk
#

Hahaha

#

I'm joking

#

I actually read through the responses to see why it was so beautiful and was laughing that it was just your immediate answer

#

But phrased slightly differently

#

Oh well, at least you know you were right

shy nebula
#

Mine involved a few extra brute force checks but the other one simplified it perfectly

kindred tusk
shy nebula
kindred tusk
#

I'm not sure if watchers would survive a domain reload anyway

upbeat path
kindred tusk
#

There is a callback from unity

#

But I thought maybe someone would know if there was a more specific API

upbeat path
#

but what has that to do with changing the csproj file?

kindred tusk
upbeat path
#

no

kindred tusk
#

No what?

#

It's also generated when you click the option in the external tools panel

#

But that's pretty rare

upbeat path
#

csproj is not regenerated on compile, it is regenerated before compile, you need to hook into the space between the regerate and the compile, the api you linked will not do that

kindred tusk
#

I can use csc.rsp for unity compiler

#

It just doesn't respect it enough to add it to the csproj

#

And ide doesn't respect csc.rsp

upbeat path
kindred tusk
#

I don't know what batch build is sorry. I just want to have the same settings in the IDE as I have in unity via csc.rsp.

#

Specifically I want warnings as errors and nullable refs

#

Very easy to enable in the unity compiler, but asmdef itself doesn't expose any options for them

#

So the options don't get baked into the csproj

scenic forge
#

There's a callback for csproj

kindred tusk
#

Meaning that we get completely different handling between IDE and unity

kindred tusk
scenic forge
#

OnGeneratedCSProject.

kindred tusk
#

How did I not find this before

#

Thanks

scenic forge
#

In that callback you can just use typical file IO and do whatever.

kindred tusk
#

Yeah perfect

#

It's just an XML file so it should be relatively easy to modify I think

scenic forge
#

Instead of csc.rsp, have you tried using additional compiler arguments instead? I can't remember if the IDE integration packages have special handling for those, worth a quick try.

kindred tusk
#

Not something I was aware was an option tbh

#

I thought csc.rsp was compiler options for mono

#

Actually I found so little info about what it even is from googling

scenic forge
#

I came in the conversation late and it's too far for me to scroll up on mobile, what compiler option are you changing?

kindred tusk
#

I want to set warnings to errors and enable nullable refs. I am able to do this for unity via csc.rsp but I don't have parity in our IDEs because unity generates them.

#

Actually there is a way to create a special file called directory.Build.props that augments the csproj, but annoyingly it applies to all csproj in the folder, which is every single csproj

#

So I'm hoping to just modify ours each time they generate

#

Honestly I think that callback is the answer

#

I might write a program that parses the csc.rsp and converts them into csproj options

scenic forge
#

Worth looking into additional compiler arguments regardless, it's somewhere in project settings, and if IDE integration packages know how it works then that saves you the trouble with having to deal with modifying csproj.

kindred tusk
#

Really appreciate it

scenic forge
#

I'm not by my computer atm, but my project also uses nullable reference type and I remember removing all the csproj modifications a while ago, so there's probably a way to do it. I'll check how my project is set up later.

kindred tusk
#

I need to sleep, but thank you.

misty glade
#

@kindred tusk if you're still awake - I had the exact same question a couple days ago and there's an undocumented event unity fires after generating the csproj that you can hook into and manually add/rewrite what you need to into the files

#

lemme see if i can find the event name for you to google up

elfin salmon
paper grotto
#

I have a private Vector3 with a [SerializeField] attribute named m_Size in a private class. This class inherits from MonoBehavior and is a component on a GameObject. How can I utilize FindProperty() to modify the variable m_Size? It is possible, right?

kindred tusk
stuck plinth
paper grotto
stuck plinth
#

which object are you calling FindProperty on?

paper grotto
#

The full line is: new SerializedObject(gameObject).FindProperty("m_Size")

stuck plinth
#

aha, do it on the component, like new SerializedObject(gameObject.GetComponent<YourComponent>())

paper grotto
#

I would, but the component is a private class. I can't reference the class at all.

stuck plinth
#

you should still be able to use the overload of GetComponent that takes a string type name then

#

is it your own script that you can't access from an editor assembly? you could always make it internal instead and use InternalsVisibleToAttribute

paper grotto
#

That worked, thank you! I wan't aware of passing in a string to GetComponent. Also, the component is ProBuilderShape, from Unity's ProBuilder plugin, so I wasn't able to modify the class.

stuck plinth
#

string typing it is then ๐Ÿฅฒ

scenic forge
kindred tusk
scenic forge
#

You can override each directory with their own Directory.Build.props.

kindred tusk
#

in Unity

scenic forge
#

Ah.

kindred tusk
#

This is what I tried:

<Project>
  <PropertyGroup Condition=" '$(MSBuildProjectName)' == 'Game.Runtime' ">
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>True</TreatWarningsAsErrors>
  </PropertyGroup>
</Project>
#

but for whatever reason it's not respected, so I gave up

#

But yeah, essentially enabling nullable on all your upm packages wreacks havoc on the project

#

like it's okay, but jump to next error can have some unwanted consequences in VSCode

scenic forge
#

Well you can always fallback to doing the csproj modifications in callback.

kindred tusk
#

Yep, that's what I'm going to try

#

this is my plan...

#

wait for them to be generated, search for each asmdef

#

then find the relative csc.rsp

scenic forge
#

I feel like surely you can get conditions to work with Directory.Build.props though.

kindred tusk
#

then convert each of those optinos into options

kindred tusk
#

Because I can only have one directory.build.props Actually you can have multiple blocks, it could be the right move if I can get it working.

#

I did try for a few hours

#

I was asking on C# discord and, predictably, they were like 'why don't you just modify the csproj" at which point I had to reveal that I was a unity dev.

#

They don't like when you do that!

scenic forge
#

Yeah I moved away from modifying csproj because it's just kind of fragile, if modification breaks it's silent because obviously you don't check Unity's csproj files into source control so you have no idea, and the breakage can manifest in weird ways and waste your time making you think it's something else.

kindred tusk
#

Or if it exposed an API for modifying it safely

#

oh well, bitching never solved anything

scenic forge
#

It'd be nice if Unity was consistent with rest of the .NET world in general yes, hopefully the Core migration would help with some of the pains even if not this specific one.

kindred tusk
#

I haven't been keeping tabs on things. Hopefully we get the latest version of C# soon. I want those memory utilities for span.

scenic forge
#

Not sure when, but it's something that's been actively worked on for a while so I'm hopeful.

kindred tusk
#

Well thanks for following that up @scenic forge!

#

I might try messing with directory.props some more

austere jewel
#

It's sadly not soon, but it's coming fast.

kindred tusk
austere jewel
#

If we're lucky there'll be a preview within the year ๐Ÿ˜„

kindred tusk
#

but I'm glad there's a nice future for my skillset

kindred tusk
#

All our asmdefs start with Game

scenic forge
#

If you have people using Rider in your team, might want to check with them to make sure things are also working there. I've heard there were bugs with Rider's support for Directory.Build.props but they might already be fixed, but good to check regardless.

kindred tusk
#

I used this as our csc.rsp

-warnaserror+
-nullable+
#

it's respecting warnings as errors but not respecting nullable

#

strangely this is working in another project, I must be doing something wrong

kindred tusk
#

Okay, got it all working. This is great :-)

robust nexus
#

So is there a "method to the madness" of creating a new object in async (not coroutine, actual async Tasks) that causes Unity to not just crash, but disappear ๐Ÿ‘ป

Should probably give some code for context, my bad:

function.CallAsync(request).ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                // blabla bla checks
            }
            FSLog($"GetAllMessages - ResponseMessage: {response["content"]}"); // all good
            var serializedJson = JsonConvert.Serialize(response["content"]) // Works fine
            var finalObj = JsonConvert.DeserializeObject<ObjType>(serializedJson); // Finishes?  Probably not, since stepping over nukes Unity
            callback(response);
        }

And on this topic, even creating the new object without the Deserialize wrapper nuked it:

function.CallAsync(request).ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                // blabla bla checks
            }
            FSLog($"GetAllMessages - ResponseMessage: {response["content"]}"); // all good
            var myObj = new ObjType(); // Nuked :D. When I removed all code and left just properties, it looked like it worked.
        }
upbeat path
robust nexus
stuck plinth
robust nexus
#

That is Firebase own extension method. Getting a sample one sec (but it doesn't seem firebase related, just async in general)

stuck plinth
#

i can't think of a way async would make this crash somehow unless there's some weird compiler bug, but sudden unity crashes are often stack overflows and stuff like that

robust nexus
#
    {
      continuation(t);
      return true;
    })))).Unwrap<bool>();
#

It's a bottomless pit of running on main thread calls lol, it should work well, and I don't think the bug is with that, it has something to do with my own setup. Any general rules I should follow? Not exactly an async champ here ๐Ÿ˜…

#

I just now that sometimes when I allocate new mem on the heap with new() in async methods it just sends the whole thing to oblivion. Was hoping there was a known scenario where that might happen that I can take measures to avoid

stuck plinth
#

assuming your call starts on the unity main thread in the first place, can you change your code to the following? just in case there's something unexpected going on with their method

await function.CallAsync(request);
var serializedJson = JsonConvert.Serialize(response["content"]);
var finalObj = JsonConvert.DeserializeObject<ObjType>(serializedJson);
robust nexus
#

The solution currently was to use the Firebase snapshot.ConvertTo<SupportMessageCollection> using deserialization with FirestoreProperties. Pretty sure that's doing heap allocation internally but maybe it's doing it in some special way? It doesn't nuke itself at all, I must be missing something

#

.... That's a good point. I'll try to find a slot to run that and see what happens, maybe with a Try Catch and hope it doesn't just disappear again ๐Ÿซ 

stuck plinth
#

i don't know if it'll fix it but it takes some extra layers out of the mix for debugging at least

#

there should be nothing special at all about allocating in a task continuation

robust nexus
#

So no risk of the thread trying to access memory that it shouldn't, causing the OS to insta kill the entire process tree? That was my assumption. But I also recall that exceptions inside threads can fail silently if not awaited and may bring the whole thing down suddenly

stuck plinth
#

not really, in this case (both with the await and their method) it's supposed to be running on the main thread, so it's no different to allocating in Update or something

robust nexus
#

... True

stuck plinth
#

exception handling can be a problem, await might help with that

robust nexus
#

๐Ÿค” I guess more debugging as per your suggestion is the best course of action. ๐Ÿ‘ Thank you very much simon!

stuck plinth
#

good luck ๐Ÿ‘

stiff ravine
#

is there no better alternative to using AnimationEvents ?

#

im trying to create a Hitbox function that can be called via animation events with args about the boxcollider to use, the damage, knockback type and amount but i cant seem to find any easy way to do this

sly grove
flint wraith
#

It is a bit hard to test this so iam going to ask here.
I am using dotween library and want to release that package onto unity asset store.

I would like to make package to use assembly definition which requires me to reference dotween assembly definition and that is handled through dotween utility package.

If i reference it within my package and release it, my guess is that reference would be broken and user would have bunch of errors until he fixes references right? Is there solution to this?

stiff ravine
sly grove
#

you don't need to

#

just call a parameterless function

#

and have that function call your other function with all the parameters you want

stiff ravine
#

but i want the parameters to be in the animation
the way ive done it is my component holds an array of structs that provide data, and the animation event simply calls a function and passes the index of the struct it wants to use

#

esp since some structs may be used multiple times within a single gameobject and their animations

dusty wigeon
stiff ravine
#

i worry that scriptable objects might take up more overheard

sly grove
#

that's a nebulous concern

patent niche
#

as you can see it disables the box colliders but doesnt switch the tile when i jump

hardy jacinth
#

Is there a way to get PropertyPath from Property during visitation in PropertyVisitor from Unity.Properties package?

sick flame
#

Hi all!
One of our colleagues already helped me connected to this. So I know that I can reach the shadowmap from the shader directly, but I am still curious.

Can I access the shadowmap in the builtin pipeline on the c# side?

flint sage
#

That sounds like a thing you shouldn't do because it'll be horribly slow

#

Why would you want to do that

somber swift
#

if your game mechanic depended on things being or not being in shadows, often times raycasting from the surface towards the direction of the light source would give you good enough estimation with less performance impact (basically ray tracing in CPU against the colliders in the scene)

sick flame
# sly grove what's the end goal?

I just want to visualize it in screenspace. I am gonna use a shader to do it as I can access the shadowmap there, however I just wonder if it is accessible on the c# side. For simply curiousity. ๐Ÿ˜ƒ

In urp, it is in the rendering data class as far as I know, but I am not sure if built-in let us access these buffers at all.

sick flame
dusty wigeon
# stiff ravine i worry that scriptable objects might take up more overheard

If you worry about overhead on Animation Trigger, you should not use them because they are not performant. Also, there is no difference between a call towards a component or a scriptable.

Personally, I use scriptable object for Animation Trigger such as PlaySFX or PlayVFX. It is easier to edit scriptable object than to edit component in those situations.

somber swift
# sick flame So this way I won't have to use the shaders just some raycasting. Good to know, ...

sure. though for something like visualizing the shadow map that you talked earlier raycasts won't perform well enough assuming you are not sticking with some 10x10 resolution but for checking whether given point is in shadow or not, raycast would be a good idea. note that raycast can only check against colliders, not the actual 3d geometry (you can use mesh colliders for the objects of course)

deep jasper
#

hi guys

#

I currently develop a multiplayer big-world game with physics of some objects like iron ingots which can be pushed around with your body, or picked up

#

My current multiplayer approach in-game is pure tcp with a server running on somemone's machine

#

So, one player hits Create Lobby, Sets world name, difficulty and other stuff, and then player limit from 2 to 4(rn it's just 4 players), and after that creates a lobby

#

UDP and TCP clients are starting on his machine, where udp is for displaying info in serverlist when somebody from lan network hits "refresh list" or just opens up list of lobbies

#

or well, if i add a master server, it would send the data to the server and transfer it to the user

#

so when player decides to connect, he enters password, passes modcheck and gets added to the lobby

#

When all players are joined, host presses start and new world gets created with own serverside save folder and stuff

#

And well, players should get switched to Game Scene, where they all create their characters with race/gender and so on

#

And after all guys finished(like in for the king, for example), they get to the game and spawn in different chunks according to their race/biography pick

#

So well, i need to make some kind of serverside player's control so server tells player to spawn on chunk 0;0, or 99;14 or other

#

and player, using that information, gets tossed to this location and starts rendering it

#

after spawning static objects like terrain, trees and stones/mountains/buildings and so on, server should tell players which physical objects should spawn around them

#

For example, several NPC's and a set of armor lying on the ground

#

and well, server should somehow control physics of all this so dynamic objects don't drop through the floor

#

any clue or link to how this can be achieved?

#

I use HDRP/NavMesh/Terrain(with Terrain Tools to make terrain based on heightmap)/TCPClient/Unity Physics and running on Unity 2023 latest

#

And in order to load objects I use AssetBundles and ScriptableObjects, along with a custom ModLoader and serverside PluginLoader(which currently does nothing since it's for a future API to let users make plugins for the game)

#

and that's what i'm trying to achieve for all players in the world, depending on their location and mod set

#

i don't plan adding quests or dialogues, but would like to learn how to make physics and npc's

#

so players could just walk around, see each other and NPC's, and their would should look 100% same if modlist is matching

#

this is more of a learning project to get understanding of TCP, ModLoading, c# reflection and physics

stuck plinth
deep jasper
#

thanks

#

i saw ones with Netcode

#

is that what i should look for?

stuck plinth
#

netcode is one of the official unity ones, if you're not using DOTS it's probably the one you want

#

otherwise there's similar 3rd party ones

deep jasper
#

I'm planning on using DOTS ig

stuck plinth
#

netcode for entities then!

#

netcode for gameobjects is the one people were talking about but netcode for entities is the DOTS one

deep jasper
#

i never used DOTS before, but as i see it, it's a stack of stuff which optimizes both code and scene processes

#

am i right?

stuck plinth
#

it's a totally different architecture from gameobjects, you have to write your game differently if you use it

deep jasper
#

Yeah, yeah

#

But well, it will definitely help players to load my large-scaled world with lots of trees, grass, terrains, static objects and physical objects with more performance, right?

#

or this is not what i'm looking for and i should stick with default unity stack

#

gameobjects, rigidbodies, colliders and so on

stuck plinth
#

it could, but it really depends heavily on what's in your game, so only you can really decide that

deep jasper
#

tho, DOTS work fine with HDRP?

stuck plinth
#

it's easier to start with a prototype the classic way at least

#

yeah

deep jasper
#

and does dots support terrain features?

deep jasper
#

but it lacks the chunk loading part

stuck plinth
deep jasper
#

i mean terrain itself and terrain tools extension

#

since i'm planning to use heightmaps which are only supported in TerrainTools

#

alr, time to spend another week learning DOTS

kind sigil
#

I want to achieve the same effect that SpriteShape package gives, but I want it to render on the canvas instead of world space. Any ideas?

dusty wigeon
mossy vine
#

Hello, I made this code that moves the UI a little bit based on the mouse position. How can I make it so if the screen size changes the UI changes with it? Thanks for the help ahead.

using UnityEngine;

public class UIMover : MonoBehaviour
{
    [SerializeField] private float smooth = 5f;
    [SerializeField] private float maxOffset = 20f; // Maximum offset from the initial position

    private RectTransform rect;
    private Vector3 initialPos;

    private bool canMove = false;


    void Start(){
        rect = GetComponent<RectTransform>();
        initialPos = rect.position;

        Invoke("setCanMove", 1f);

    }

    void Update()
    {
        if (canMove){
            Move();
        }
    }

    void setCanMove(){
        canMove = true;
    }

    void Move()
    {
        // Check if the mouse position is within the screen bounds
        if (IsMouseWithinScreen())
        {
            // Calculate the normalized mouse position (-0.5 to 0.5 range)
            Vector3 normalizedMousePos = new Vector3(
                (Input.mousePosition.x / Screen.width) - 0.5f,
                (Input.mousePosition.y / Screen.height) - 0.5f,
                0
            );

            // Calculate the target position based on the max offset and the normalized mouse position
            Vector3 targetPos = initialPos + (normalizedMousePos * maxOffset);

            // Smoothly interpolate towards the target position
            rect.position = Vector3.Lerp(rect.position, targetPos, smooth * Time.deltaTime);
        }
    }

    // Helper method to check if the mouse position is within the screen bounds
    private bool IsMouseWithinScreen(){
        return new Rect(0, 0, Screen.width, Screen.height).Contains(Input.mousePosition);
    }
}
#

nvm i fixed it

regal olive
half swan
regal olive
#

Wdym?

half swan
#

It's often the case where you SAY the issue, then end up figuring it out just by trying to frame is as a question

regal olive
#

Then just font post question

#

If you figure it out while phrasing

half swan
# regal olive Wdym?

Well, time is linear in the human perspective. So things can happen before or after other events. The question was asked BEFORE they figured it out

#

Then, after posting the question (later in time) they figured it out

regal olive
#

Ah, so you are referring to the theory of time linearity?

#

Cool

#

I mean you always learn new thing in your life.

#

Today I learned about event chronology, tomorrow I might create nuke.

untold moth
#

I agree, they should've went back in time and prevented themselves from posting that question if they already figured it out.

livid kraken
#

Some people canโ€™t even go back in time to fix their mistakes smh. This generation is doomed am I right guys ?

shy nebula
#

I had a dream last night that I wrote a function that executes code from the top of a script to the bottom in sequential order ๐Ÿ˜…

#

Unity has rotted my brain to its core

hardy jacinth
#

Can I somehow make SerializedProperty work with properties marked with [CreateProperty]?

#

I need a potential undo support and multi-object editing

floral flower
#

Hey guys, TMPro -> sprite's from rich text via TMP_SpriteAsset that is in TMP_Settings. When i change the default sprite asset in TMP_Settings in runtime, my sprite's refresh only after scene reload, i can bypass this by calling TMPro_EventManager.ON_TMP_SETTINGS_CHANGED(); but that works only in editor. Do you know any other way to refresh settings in build version?

serene oxide
#

How do I stop my player and enemy to be blurry using cinemachine?

split inlet
# serene oxide How do I stop my player and enemy to be blurry using cinemachine?

I guess this really depends on how they are rendered. SpriteRenderer? MeshFilter+MeshRenderer? something different?
(Are you sure you're inspecting them through the game view i. e. not through the scene view?)

If it is a sprite/texture: make sure that the base image is large enough. Make sure that the mas resolution is high enough. Check the current quality settings.

If nothing of this helps, it might be good to get some more details, e. g. a few screenshots. (What does it look like? What are the settings?)

umbral stirrup
#

Anyone know how could I achieve the same as Unity's SerializeField attribute in Non-Unity c#? I want to import a DLL and make an attribute in there to be able to serialize private fields in editor. For Json Purposes I am using Newtonsoft.Json.JsonProperty but i'm not sure how to achieve the editor aspect

hybrid belfry
#

I'm building a script which allows the developer to choose a Scene to load after a "Loading" scene has completed. An Editor script allows the developer to hit a button which regenerates and enum. A public field allows the developer to pick a value from the enum. The trouble I have is finding a way to wait until the enum is regenerated before selected a new default value, since the chosen inspector value for the scene might now be invalid, after generation. Does anyone know how I can wait for Unity to stop compiling the script before the rest of the code is executed?

dusty wigeon
# hybrid belfry

Using enum for this is not a good idea. Read on Primitive Obsession (https://refactoring.guru/smells/primitive-obsession)

Ideally, you should use Scriptable Object.

upbeat path
dusty wigeon
upbeat path
# dusty wigeon You are entitle to your opinion. That would be cool if you could elaborate a bit...

well let's just take one thing he says
'If you have a large variety of primitive fields, it may be possible to logically group some of them into their own class. '
And this reduces the number of primitives used by how much? Zero. All you have done is added another level of complexity.
What he is effectively saying is bad design basically stems from no design. So go and design your code properly rather than trying to stick a band aid on it

hybrid belfry
#

Hmm I don't see why I need a ScriptableObject since I don't need any of its features, unless I am missing something

hardy jacinth
# hybrid belfry Hmm I don't see why I need a ScriptableObject since I don't need any of its feat...

Scene is a ScriptableObject. If you want to select a scene, why go through an indirect enum that describes the scene, instead of referencing the scene itself?
I.e. if you are doing scene <-> enum mapping, and in the editor script you are doing selection by scene enum, then you can just display a list of Scenes directly (SciprableObjects) and use that. What's more, if you just use a Scene targetScene, then you get for free a default inspector field that automatically lets you pick up the scenes from the project

hybrid belfry
hardy jacinth
#

then you are most probably looking for a custom property drawer for scene asset types

#

NasughtyAttributes has an existing implementation of [Scene] attribute you can use

#

you could then use something like

[Scene] public string bootScene; // scene name
[Scene] public int tutorialScene; // scene index
dusty wigeon
# upbeat path well let's just take one thing he says 'If you have a large variety of primitive...

Primitive Obsession, as most design principle is a "guiding" principle. The idea is to increase maintainability by regrouping field with high cohesion together. Obviously, in some scenario it is overdesigning such as when you are using regrouping primitive in a already highly cohesive class.

In this situation, it is clear that you might add additional data per scene such as Level Name, Level Assets, Loading Screen, Spawn Points, etc. A scriptable object enable you to serialize all this information together.

hybrid belfry
#

I think I found the simplest way and works perfectly. No File reading or hard work needed

tall ferry
frozen arrow
#

This is my cameracontroller. I have two camera methods. One allows me to follow the player while being able to zoom in and out with the scroll wheel. Pressing Y key toggles methods. My 2nd method is a free form method that allows me to move the camera with the edges of the screens. The problem is that zoom does not work during the 2nd method. If I scroll wheel during the 2nd method the variables do change. I can tell because if I'm zoomed out during lock, swap to free form, zoom in (no visual change shown), then swap back to locked cam, it snaps to all zoomed in like I wanted it.

Code is attached. Please help ๐Ÿ™‚

plush prism
#

Hey guys - I'm trying to write a script that will convert a skinned mesh renderer to a static mesh per frame of animation.

I'm running into an issue though where I'm also trying to capture all the static meshes attached to the skinned mesh renderer... but they're not being translated in 3d space.

I'm a bit of Unity Noob though so I'm probably missing something. I am looping through all the regular meshes and trying to translate them into localspace... but i might be missing something ?
https://pastebin.com/B2jeLEEb

#

intended outcome:

#

What's being generated:

#

ignore the box - it's a hitbox where i forgot to remove the mesh

#

In this Unity tutorial you will learn how to bake animations as a series of "snapshots" of meshes. These snapshots can be taken at a configurable framerate that suits your game.

The concept here is attacking a similar problem as Animation Instancing: https://blog.unity.com/technology/animation-instancing-instancing-for-skinnedmeshrenderer, but ...

โ–ถ Play video
#

Sorry it's not very clean ๐Ÿ˜ญ

long ivy
#

well you say it's translated into local space, but that's not true. And according to the docs, BakeMesh bakes the mesh using the position and rotation of the skinned mesh renderer's transform so seems like line 142 would be wrong at first glance

plush prism
#

gotcha

#

yer i tried that as it didnt work at first

#

i'll try and take itouu

long ivy
#

once you fix that, fix the static mesh transforms so they're in local space of the skinned mesh renderer's transform also

plush prism
#

oh derp

#

combinedMesh.CombineMeshes(combineInstances.ToArray(), true, true);

#

i had the last argument as false

#

useMatrices

#

so.... when combining them of course it was not going to work

#

have set it to true now

long ivy
#

looks closer, but still need to fix the static mesh transformations

frozen arrow
hardy jacinth
#

doesnt this: if (Input.GetKeyDown(KeyCode.Y)) freeFormCameraEnabled = !freeFormCameraEnabled; basically flip the freeFormCameraEnabled ON and OFF every frame the Y key is pressed?

#

an alternative, if I may suggest, look into Cinemachine package, because what you seem to be trying to implement, they have basically out of the box

frozen arrow
#

I will check that out thank you

elfin salmon
#

Hey guys, does someone know how I could proceed to fill a cell with a pavewalk or other to place my houses on?

#

( procedurally )

#

the cell generated would take form of a large polygon

#

What I'm thinking would be to make a mesh from the polygon and apply a material to it

tired fog
#

Can someone explain what's going on here?

public class TestAlloc : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        NativeArray<float> test = new NativeArray<float>(1000*1000*60, Allocator.Persistent);
        test.Dispose();
    }
}

If i run this the memory in the profiler keeps increasing

#

I thought dispose was supposed to free it????

tiny pewter
#

try to allocate it other than persistent?

tired fog
#

tempJob can only be used for 4 frames, i need persistent because it can sometimes be an expensive job

#

and temp only works inside jobs

tiny pewter
#

try raw malloc and free? i doubt that after you freeing the large block of memory unity get some memory internally by new causing heap fragmentation

hybrid belfry
# tall ferry What's happening with buildSettings there? I dont see how it's used

Sorry for the late reply, but it's rather simple:
We cache the EditorBuildSettingsScene settings. If, when we trigger OnInspectorGUI(), the build settings have changed since last checked:
-> Create a temp list of strings to store the names of only enabled scenes
-> Assign the strings according to the latest settings
-> Set the string represented by the index
I just need to add validation checks

split inlet
# serene oxide

I don't know if someone responded in the meantime. I could be wrong (or maybe it's due to the video compression), but the enemy doesn't look blurry to me. You should make sure that it's not just your screen that has difficulties properly displaying moving things (e. g. due to a low pixel response time). Since you have a recording already, make sure that the recording doesn't contain to many compression artifacts. Make sure that you can observe the issue in the video when playing it at normal speed at the correct resolution (i. e. if you record at 1920x1080, the playback should be 1920x1080 i. e. fullscreen for most people). Then, reduce the playback speed and observe if the issue persists. You might also want to step through the video frame by frame. If you don't see the issue this way, there's a good chance that the rendering is fine.

eager willow
#

hello everyone

#

I created a library for myself, but in the code on the editor I did not put it in the editor tag and I created it as a dll when building in unity it got an error, if I tag the editor on visual when creating the dll then It will lose the code on the If unity_editor tag, so how should I do it?

upbeat path
eager willow
#

this link sir

#

I want to do that but in 1 dll

#

or somehow include it in the project so that other people won't see my source code

upbeat path
#

put the non editor dll into Assets/Plugns and the Editor dll into Assets/Editor/Plugins

eager willow
upbeat path
#

no

eager willow
#

thanks sir

serene oxide
eager willow
# upbeat path no

Do you have any way or can you give more details? I tried it and it didn't work

upbeat path
eager willow
#

and a class I call as follows

#

But when I build it, it cannot call the class that I tagged if unity editor

upbeat path
#

did you make 2 configurations in your VS solution

eager willow
#

This is a class without the if unityeditor tag

#
 public class GroupAttribute : PropertyAttribute
 {
     public string Name;
     public Color Color;

     public GroupAttribute(string name, string color)
     {
         Name = name;
         switch (color.ToLower())
         {
             case "red":
                 Color = Color.red;
                 break;

             case "green":
                 Color = Color.green;
                 break;

             case "yellow":
                 Color = Color.yellow;
                 break;

             case "brown":
                 Color = new Color(0.65f, 0.16f, 0.16f);
                 break;

             default:
                 Color = Color.white;
                 break;
         }
     }
 }
#

and This is the class with the if unityeditor tag

upbeat path
#

but propertyattribute is editor only

eager willow
#
[CustomEditor(typeof(MonoBehaviour), true)]
public class GroupedInspector : Editor
{
    private class Group
    {
        public string Name;
        public Color Color;
        public List<SerializedProperty> Properties = new List<SerializedProperty>();
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        var groups = new Dictionary<string, Group>();
        var noGroupProperties = new List<SerializedProperty>();

        var iterator = serializedObject.GetIterator();
        iterator.NextVisible(true); // Skip the "m_Script" property

       
}

upbeat path
#

and so is that class

#

you need to strip out ALL editor code for your runtime version

eager willow
#

it will error untagged unity editor

upbeat path
#

you get 2 dll's one with editor+runtime code and one with runtime code only

#

I just tend to make 2 VS projects anyway, one for editor code and one for runtime

eager willow
#

If the class is not tagged and includes code, I think it will fail at build time

upbeat path
#

yes so wrap ALL editor code in a #if define

eager willow
#

When I build it, it crashes if I don't tag unity editor

upbeat path
#

I use the following set up in VS

Solution
ProjectA
references UnityEngine
contains all non editor code
builds to Assets/Plugins
ProjectB
references ProjectA, UnityEngine, UnityEditor
contains all Unity Editor code
builds to Assets/Editor/Plugins

@eager willow

eager willow
fringe root
#

Any idea why i cant set scene active even though my loaded prints before the error?

#

Even with a yield return new wait for seconds it doesnt set the scene to active, no idea why

sly grove
#

otherwise - unless you're setting allowSceneActivation to false it should activate the scene automatically afaik

wet sail
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assimp;
using System.Linq;

public static class AnimationImporterForAI
{
    public static AssimpContext importer;
    static AnimationImporterForAI()
    {
        if(importer == null)
        {
// *loads something that is big in memory here*
        }
    }
}

this causes memory leak to me since every enter to play mode or modification of a script, the domain gets reloaded without disposing the old stuff stored in memory. what do i do?

sly grove
sturdy timber
#

First one pretty much explains issue every chunk loaded the graphics memory usage increases but chunks gets unloaded as well("destryoing gameobject"). However that doesnt reduce graphics usage in any way. The other screenshot shows the code that sets the mesh.

Can anyone help? Because i have no idea why this is happening (and no i am not using compute buffers in my project)

charred tangle
#

Does anyone have thoughts on Initializing Singletons? In the past, I had a "Manager Scene" which had all the Singleton manager objects -- and loaded the game scenes after (the manager scene is always running and booting other scenes)

misty glade
#

That's how I do it.

charred tangle
#

I know it's common to just DontDestroyOnLoad and set the instance in Awake but I'm concerned I might try to access a Manager during Awake elsewhere

misty glade
#

(I also use this scene to download addressables, prompt the user for privacy/data tracking, and that kind of stuff)

#

track the initialization with a flag then

charred tangle
#

Awesome, just making sure I'm on the right track

misty glade
#

init on awake, check if it's init'd already and early-out if so, elsewhere if you call into it and it's not initialized, then init it

scenic forge
#

It does kind of suck that you lose the ability to start a particular scene, you'd need to hack something together.

misty glade
#
        private bool _isInitialized = false;
        private void Awake()
        {
            if (instance != null)
            {
                Destroy(gameObject);
                return;
            }
            instance = this;
            Initialize();
        }

        private void Initialize()
        {
            if (_isInitialized) return;
            _isInitialized = true;
            // do stuff
        }
}```
#

this is my pattern

#

and then anyplace that needs init (that could happen before awake) just pre-emptively call Initialize() .. just be careful of circular dependencies

#

since this is obviously not resilient to that ๐Ÿ™‚

broken dawn
#

MetaXR Spatial Anchors

hushed echo
#

Excuse my noobishness but this is my first time interacting with the unity job system. I am attempting to parallel process a potentially large number of targets using a threaded task but I am running into an issue. The issue I am running into is that the targets seem to be being managed incorrectly somewhere along the line but I'm just struggling to see what I'm doing wrong here. I've tried a number of things but I still can't seem to quite figure out what the issue is.

sly grove
#

what are you expecting to happen and what's happening instead

#

Also please share your code via !code

thorn flintBOT
hushed echo
#

Ah you got it, gimme a minute and I'll reformat the post to give 1. Better info 2. A more in depth explanation

hushed echo
#

The reason I reckon that is because upon reverting to my commit before attempting to thread the code, The system worked fine

sly grove
#

What's the multithreaded code do?

#

ooooh wait you're modifying the list in the job?

hushed echo
#

I thought that was the point of IParallelJobFor. I could be way off base though.

sly grove
#

well...

#

you can't actually even TOUCH managed memory

#

in any job

#

and I don't think you are here

#

This is a little weird/inefficient but I don't see how it would break things:

        for (int i = 0; i < RegisteredTargets.Count; i++)
        {
            RegisteredTargets[i] = new TargetData(RegisteredTargets[i].TargetGameObject, RegisteredTargets[i].TargetRB, RegisteredTargets[i].IsEmpty, scoreResults[i]);
        }```
#

pretty sure you could just do RegisteredTargets[i].TargetScore = scoreResults[i];

#

wait nvm it's a list

#

not an array

hushed echo
#

The job itself writes to some lists then the job does work on the lists then the results of the calculation are added to the struct value so I don't think I ever write to managed memory from inside the job itself. I could convert the list to an array and pass it into the nativearray constructor

#

that might be more efficient

sly grove
#

no no. What you have is the way

sly grove
bright wind
#

Is there any way to check if GPU instancing is supported by the hardware at runtime? I have a release build that I've tested on a few machines that works, but on one particular machine, all the stuff I'm rendering with DrawMeshInstancedIndirect() just doesn't show up and I see no indication as to why?

#

I believe I've also tested the same gen GPU previously, but a slightly different model so I'm not sure if its a hardware thing or not

bright wind
bright wind
#

So those both return true on that machine.... Anyone have any ideas as to why DrawMeshInstancedIndirect() would not render on one machine but not others?

untold moth
#

Otherwise the dedicated graphics debugging tools for the platform(pix for windows for example)

upper vector
#

Does anyone have tips for dealing with native crashes in production? Native Crash - KiUserExceptionDispatcher
I've enabled Cloud Diagnostics but the stack traces aren't helpful.
All I see is: 12 GameAssembly 0x00007ffef67c2cc0 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
I've uploaded the pdb file with the corresponding UUID but the logs aren't being updated.

#

I'm getting lots of refunds over this issue, appreciate any help ๐Ÿ™

untold moth
upper vector
untold moth
#

I don't know much about cloud diagnostics, but it would be weird if you can't get the crash dump file.

upper vector
# untold moth I don't know much about cloud diagnostics, but it would be weird if you can't ge...

I can download a json file and I have the pdb file for the build. Is it possible to see which line of code is correlated to the following stack trace locally?

12  GameAssembly                       0x00007ffef67c2cc0 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
13  GameAssembly                       0x00007ffef6555701 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
14  GameAssembly                       0x00007ffef6211704 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
15  GameAssembly                       0x00007ffef621a201 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
16  GameAssembly                       0x00007ffef6210eee <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
17  GameAssembly                       0x00007ffef6017726 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
18  GameAssembly                       0x00007ffef60171c9 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d> 
untold moth
upper vector
untold moth
#

Yes.

#

It seems like cloud diagnostics doesn't collect the crash dump.

#

You might need to contact a user that experience the issue and ask them to provide crash dump.

#

Also, just in case you don't know, this is not the official unity support, but a community server. You should contact the actual support, seeing how it's a native crash.

upper vector
#

Ok thanks for your help โค๏ธ

#

I've contacted Unity but technical support requires a Pro license atm.

flint sage
#

You can still open bug reports etc

stiff ravine
#

hey so i have an issue where

#

i have a gameobject with an animator

#

and i sometimes disable the gameobject but

#

if an animation is running and i disable the gameobject, then re-enable it

craggy spear
#

this isn't an advance code issue

#

is it even a code issue?

stiff ravine
#

yes

craggy spear
stiff ravine
#

i was going to ask if theres a way to make an animator reset to its defualt statethrouygh code

fringe root
#

Hello guys. Kinda need some advice on not creating a whole bunch of spaghetti code here.

So.. In my project i want to able to to select the enemy i'm attacking on mouse click, but i am also using composition and it would be cool to make a reusable attack component that would be able to be attached to the Player Character and the Enemies.

Both the Character and the Enemy inherit from an Actor class.

So far, whenever i click on an Enemy, i set a static variable Enemy enemyTarget to the clicked enemy, and in my attack component(for the player) i'm checking on trigger stay to see if other == enemyTarget.
For the enemy im just checking on trigger enter and on trigger exit for the player.

Then i need to be able to call the TakeDamage method inside the HealthComponent of my target, but i dont really have acess to it as Actor doesnt have the HealthComponent, but the Player Character and the Enemy does.

Should i create another class that inherits from Actor and will be the base class for Player and Enemies?
Should i just add an interface to the Player and Enemy classes, i didnt really want to have to write a TakeDamage method in those classes, i wanted to be able to let the healthcomponents deal with all that

Any advice someone can give to this situation_

frail kestrel
# fringe root Hello guys. Kinda need some advice on not creating a whole bunch of spaghetti co...

I think this is more a question for #archived-code-general but anyway: There's multiple approaches and in theory there's no good or wrong. But by following a set of pre defined rules it makes it easier for everyone (Including yourself) to understand the code and not make spaghetti out of it. Have a read of the SOLID principles. I usually fall back to this Medium article as it explains exactly how to implement it in Unity: https://medium.com/@alejandrodiazjllo/s-o-l-i-d-principles-for-unity-a1556ee99e7c

A good video to fall back to: https://www.youtube.com/watch?v=QDldZWvNK_E

fringe root
#

Yeah, im familiar with the SOLID principles but in this specific situation I'm having some trouble. I think i might go with the inheritance route

dusty wigeon
fringe root
#

Get component seems like a decent route too! I have my components inside an empty gameobject inside my prefabs so it stays organized. But i might just add all of it to the prefab parent

dusty wigeon
#

Should i just add an interface to the Player and Enemy classes, i didnt really want to have to write a TakeDamage method in those classes, i wanted to be able to let the healthcomponents deal with all that

Use Composition to be able to reuse the "component" through your classes.

public class Player : ITakeDamage
{
  private DamageHandler damageHandler;
  
  public TakeDamage()
  {
    damageHandler.TakeDamage();
  }
}
fringe root
#

Yeah, i didnt really want to go that way because i think thats really ugly. I'd rather call take damage directly on the damage handler

dusty wigeon
#

One thing you might need to note, is that "Health" is usually used by a considerable amount of system. Making it in a seperate component might work for simple game, but if your game start to be a bit more complicated you realize that your health componenet needs a considerable amount of "Customization". By example, you might have modifiers, you might invulnerability period, you might complex interaction for the damage taken.

#

In any circumstance, I believe the easiest way to handle simple scenario is to have a "Character Class" i.e. god class. As long as your game is relatively simple, it might be more than enough.

#

Obviously, that would means that you are vulnerable to the same issue, but in a different way, then what I described with using components.

regal lava
#

I've gotten to the point where if I'm not using singletons to grab references, then I'm using bi-directional references to reference upwards the hierarchy.

#

Large reason for this is a lot of stuff that I want to be grabbing components from should be its own gameobject, for quicker component accessing instead of convoluting a single gameobject. All my objects with colliders will have some script that's composed of just properties that point to their respective script.

fringe root
#

Yeah.. i might go with a bit more inheritance to solve that

tired fog
tired fog
#

Can someone explain the differences between Allocation Types in the scope of using UnsafeUtility.Malloc?

#

I understand TempJob being for jobs, Temp of 4 frames, and Persistent to be more persistent. But none of those warnigns are thrown with UnsafeUtility.Malloc, so what's actually happening behind the scenes with those allocation types?

stuck plinth
#

only persistent actually allocates real memory, the others go to a faster bump allocator that gets cleared 1 or 4 frames later

tired fog
#

Ah good to know

#

also, to have a list of pointers

#

is this a good approach?

public unsafe struct MapPointerHolder{
    public float4* pointer;
    public int Length;
    public void Dispose(){
        UnsafeUtility.Free(pointer, Allocator.Persistent);
    }
}

and then list of that struct?

#

or could that bring problems

stuck plinth
#

i don't think there's exactly a safe way to do that, so it depends how it's being used? you could maybe improve it a little by making pointer get-only and setting it to null on dispose to avoid double frees

tired fog
#

Alright

#

I transformed it to this

 public unsafe struct MapPointerHolder{
        public float4* pointer{get;}
        public int Length{get;}
        public NativeArray<float4> array{get;}
        public void Dispose(){
            UnsafeUtility.Free(pointer, Allocator.Persistent);
        }
        public MapPointerHolder(float4* pr, int Lenght){
            this.pointer = pr;
            this.array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float4>(pr, Lenght, Allocator.Persistent);
            this.Length = Lenght;
        }
    }
#

and it breaks unity, great

stuck plinth
#

that seems a little redundant now if you convert it to a native array - NativeArray already does everything your wrapper does ๐Ÿ˜…

tired fog
#

buuuuut that's where the issue is

#

Im doing this because for some reason, native array. dispose doesn't really free all the memory

#

it seems to generate some garbage that I cant delete

#

example here

#
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;

public class TestAlloc : MonoBehaviour
{
    // Update is called once per frame
    unsafe void Update()
    {
        //Normal way
/*         NativeArray<float> test = new NativeArray<float>(1000*1000*60, Allocator.Persistent);
        test.Dispose(); */

        //Manual way
        var ptr = (float*)UnsafeUtility.Malloc(1000*1000*60,UnsafeUtility.AlignOf<float>(), Allocator.Persistent);
        NativeArray<float> newtest = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float>(ptr, 1000*1000*60, Allocator.Persistent);
        UnsafeUtility.Free(ptr, Allocator.Persistent);
    }
}
#

if you uncomment and test the normal way you will see that memory starts increasing, while the second, the manual, doesn't

long ivy
#

are you sure? you're allocating a lot of memory (240MB in the NativeArray) every frame. You could be causing a lot of fragmentation, and Unity never releases heap memory once acquired. It looks like your Malloc is only allocating 60MB btw, assuming Malloc is in bytes

tired fog
tired fog
#

yeah so i tried now with 240mb (adding sizeof(flaot) into the method of manual) and it stil stays consistent

stuck plinth
#

i tried it and it does level out after a while, i think it might just be unity not bothering to free memory until a certain point to save time

tired fog
#

that could be but when doing testing on a bigger scene (before getting to this point) my issue was that memory keept increasing while exiting and entering play mode, and I wasn't getting any reports of memory leak anywhere

long ivy
#

Editor profiling can be misleading and outright wrong due to extra stuff it does. You tested in an actual build right?

tired fog
#

i did not

#

lets see

#

interesting, it doesn't happen in an actual build

#

But then its problematic too, because im doing a unity tool and therefore it should work fine on the editor and not accomulate memory

stuck plinth
#

are you sure dispose is always being called in your tool? assuming it's not just disposing immediately after allocating like your example ๐Ÿ˜„ normally i'd try to avoid using persistent allocations in editor because of how easy it is to create a leak

tired fog
tired fog
#

Or check if that's the problem?

#

Ah no, heap memory seems to be fine

misty glade
#

I have a bit of performance issues in my game, and I think I've narrowed it down to local material creation on an object that I'm sometimes creating several (N=2-10) per "move" (typical moves are 1 per 1-3 sec).

I have this prefab that has a number of special effects on it, and in order to not have materials "collide", i create a copy of the material at Awake time.

Could I use object pooling for something like this?

sly grove
misty glade
#

.material

#

usually like this:

        private void Awake()
        {
            Tile2Image.material = new Material(Tile2Image.material);
            _shineMaterial = Tile2Image.material;
}
#

then I do some tweening and animations and shader nonsense on the _shineMaterial

sly grove
#

you you might even be making two copies of the material like that

#

use .sharedMaterial

#

because accessing .material tends to create its own copy internally

misty glade
#

right - that's what I want, though

sly grove
#

Basically I think you can just get rid of that first line

misty glade
#

like, if I use shared material, won't the effect on one item affect all the items?

sly grove
#
private void Awake()
{
  _shineMaterial = Tile2Image.material;
}```
#

this will already create a copy

misty glade
#

oh? ok.. this is a bit of cut and paste coding from the uh.. shader component thing i have

sly grove
#
private void Awake()
{
   Tile2Image.sharedMaterial = new Material(Tile2Image.sharedMaterial);
}
``` this would _also_ create one copy
#

just more verbosely

misty glade
#

k, trying it out.. tbh i was raising my eyebrow at that code too

sly grove
#

I think in both cases you also will need to Destroy the copy when you're done with it

misty glade
#

oh, also good to know, i wasn't doing that

#

ok - so commented those extra ctors out and functionality is ๐Ÿ‘ .. will profile again

#

ah but it does this nonsense:

#

ie, just entering play mode modifies the .mat file in the repo

#

(which is super annoying both for me and all the designers)

sly grove
#

uhhh what code did you end up with? That shouldn't happen ๐Ÿค”

#

if you're using .material it should definitely make a copy

#

I would expect that if you modify the material returned from .sharedMaterial directly

misty glade
#

Oh, i wasn't using shared material sorry

#

well hang on.. maybe i'm not understanding something.. lemme just paste code, sec

sly grove
#

well you shouldn't use sharedMaterial if you wish to create a copy to modify

misty glade
#
        private Material _shineMaterial;
        private void Awake()
        {
            _shineMaterial = Tile2Image.material;
        }
// elsewhere:
            _shineMaterial.GetFloat(_shineId);
            seq.Append(_shineMaterial.DOFloat(1, _shineId, 0.3f).SetEase(Ease.Linear)); // dotween sequence
            seq.AppendCallback(() => _shineMaterial.SetFloat(_shineId, 0));
#

basically i'm setting the float on a shader on the material.. when i don't make a copy of it, it affects every sprite in the game that uses that material

sly grove
#

that should have worked without modifying the asset ๐Ÿค”
Tile2Image is... a renderer or what?

#

or is it a UI Image?

misty glade
#

just a UI image, yeah

sly grove
#

Ahhhh

misty glade
#

i am using a custom component for this, btw, so the problem might be in there - All In 1 Shader

sly grove
#

that explains it

#

Yeah you'll need to manually create the material like you had before then. Sorry for the misunderstanding I thought it was a Renderer

misty glade
#

k.. no worries

sly grove
#

I don't think UI Image actually has a separate .sharedMaterial property

#

yeah it doesn't

misty glade
#

yeah i .. recall going down a rabbit hole trying to get shared materials in UGUI things and it just not working

sly grove
#

I would think if you manually point multiple Images at the same material instance it should be shared amongst them

misty glade
#

this might not even be the problem with my frame stutter anyway.. the profiler isn't really showing me any bad offenders, just .. a lot of shit going on in this frame

#

maybe a lot of shit going on in the UGUI render pass

sage radish
# misty glade .material

You may already know this, but in case you don't, duplicated/created materials, whether it's with .material, Material constructor, or Instantiate, do not get cleaned up automatically unless it's no longer referenced anywhere and Resources.UnloadUnusedAssets() is called, which Unity will also call for you if you load a scene in Single mode. Until then, it will hang around in memory. This applies to all Unity objects. To unload them manually, you need to Object.Destroy them.

sly grove
misty glade
misty glade
#

is there a better tool to navigate a single frame from the deep profiler? this is a little.. not great

#

Also FWIW I get this hiccup only once at the start of a level.. but normal gameplay is several hundred moves (for a level) and is super fast. I'm not sure why the hiccup in this frame exists

sly grove
#

well it seems to be doing a ton of initialization stuff right?

misty glade
#

yeah.. I'm digging.. the tile init seems to take 12-17ms, which is a lot but.. this is a 200ms frame so it's not like.. the worst thing in the world

#

i suppose i need to clean that up some because it's not unexpected to create 5-10 tiles per turn

#

like here's a "normal" turn:

sly grove
#

is that a single instantiate taking 12ms??

misty glade
#

the tile init takes 12.92ms but .. the bulk of that is those 2 material copies - 5.35+5.27

#

yeah ๐Ÿ˜

sly grove
#

most of that seems to be the editor drawing the material property drawer in the inspector though no?

misty glade
#

oh, good call

sly grove
#

Close the inspector window and see ๐Ÿ˜†

misty glade
#

well, i don't have the inspector open on that specific tile

#

or does that not matter?

#

i assume that's the problem - this particular library has like... hundreds of editor knobs

#

wow.. i drill down and it's filled with String.Equals stuff.. i'm assuming the library has some sort of string property lookup nonsense

#

that's actually reassuring though - this shouldn't be the case on-device

sly grove
#

Yeah I think that MaterialEditor stuff can be handwaved away

misty glade
#

closing/disabling inspector didn't have an effect on the instantiate time unfortunately

sly grove
#

it should be editor only

#

Maybe it's time to do a profile on a build?

misty glade
#

i haven't done any on-device profiling in the past.. not sure if I'm gonna need to but this 200ms hiccup is annoying

#

aye.. i've been putting off learning how to do it basically forever

#

premature optimization and all that

sly grove
#

you could start with a PC/Mac build if that's at all feasible with your game

#

but really it's not that bad to do on-device profiling

misty glade
#

nah i have a good CICD pipeline for device based builds but.. just have never profiled before so I'd have to read up on how to do it

#

there's a .. feature that you can connect a unity instance to a device instance to profile, yeah?

sly grove
#

yes

#

you use ADB for android

misty glade
#

the 3 object.instantiate() calls in the 75.79 OnGameStarted call in the middle seem like the worst offenders atm

sly grove
misty glade
#

k, thanks, i'll give it a shot

#

oh.. this is interesting.. i have a 250ms frame a bit after the level start that's doing some .. FMOD stuff..

#

I can't tell what LoadFMODSound() is doing - there are thousands of calls to SyncRequest()

#

That fixed it. Preloaded all audio and it's peachy now. Still need to improve my tile instantiate time ๐Ÿ™‚ but hopefully that's not an issue on-device. Thanks for the help PB

elfin bane
#

Hi

I want to somehow block login to my account on the second device (due to lack of data synchronization)

there are 2 options

  1. a popup is shown on the new device with a message that if you want to log into your account, log out of your account on the old device
  2. auto logout on the old device and login on the new one

Option 1 requires session tracking

Option 2 seems like it can be done, but then there is a question about implementation

ala request to the server every couple of seconds โ€œtell me which device you logged into your account fromโ€, and if the deviceId matches then everything is ok, but if not then we automatically log out the user

misty glade
#

2's better, if that's your question (ie, if you left yourself logged in in another physical location but want to play, you shouldn't need to go home to log yourself out)

#

if you have a server already, track your sessions in a dictionary with device id & connection id, and if someone logs in with a duplicate userid, log out the existing device id (also make sure your client doesn't have auto-reconnect functionality, or at least build functionality to disconnect a user with a reason why and for "logged in from another device" as a reason, prevent the auto-relog)

elfin bane
#

i use firebase auth with my own server (store accounts)

misty glade
# elfin bane But wonโ€™t there be a heavy load on the server if I, from a device that has alrea...

Depends on a million things like how often you poll the server, whether or not the server is maintaining connections and you have some way to identify users based on connection id or whatever. If you are just having some sort of stateless server that takes webapi requests for things that happen in game, then make a login API and don't accept calls unless they're from the most recently logged in device

elfin bane
misty glade
#

but for a game I made last year, it was tcpip & stateful - users had to maintain connections, and we allowed cross platform play so .. I'd look up the userid from the deviceid (we had some features to link devices so a user could have multiple device ids), and stored connections in a dictionary of connection ids. If a user connected but was already connected on another device, we'd disconnect that device.

#

i'm not super familiar with firebase but i'm assuming a firebase id is a unique id "per person"? ie, i could log in from my computer or my phone with the same firebase id? And I'm assuming you're concerned about duplicated/desynced user data?

#

I'd say you should just ignore (and logout the client from) subsequent "save" requests if they originate from a deviceid that isn't the last logged in device

elfin bane
misty glade
#

well i mean, what else are you doing? I guess I don't understand.. if the client is just auth'ing to firebase (and nothing else), what's the problem with multiple copies of the user being logged in?

#

Like.. I'm assuming you have a client/server architecture for a reason.. like save state persistence or .. just allowing people to play together? There's something your server provides to users, right? ๐Ÿ™‚ What I'm getting at is .. whatever your server is providing to the users - you have an opportunity to handle all the "who's who" at that surface

#

If your server stores save files, the client has to ask the server to save it - the server can reject it if it's not the correct device.

If the server handles matchmaking - and a client asks for a game, the server could reject it if it's not the correct device.

If the server has a persistent world, clients will need to ask the server for the state, which again.. the server could reject if the client is making that request from an incorrect/old device.

elfin bane
#

i save my messages on server

#

and i dont have sync when I use two account in one moment

misty glade
#

ok so every chat with the bot is going to have some text payload.. just include the device id with it

elfin bane
#

yes, we have an account linked to deviceId

#

Is this way normal?

  1. when you log in on the second device, the server automatically goes through all the accounts from which you need to log out and sets some flag (you need to log out of the account)
  2. the client represented by Unity polls the server every few seconds and checks this flag; if it is set, then it is necessary to exit
misty glade
#

This probably isn't an advanced question FWIW (and I have to go in a moment), but basically you'll need to keep track of the users "last logged in device" (since I'm assuming you're using the firebase ID as the primary key) and .. any requests into your server should include the device id and firebase id with the request - and your server needs to track the state of the most recently logged in device

misty glade
#

You haven't really told me about your connection architecture - if you have a stateful/permanent connection thing, then when someone logs into a second device, find the original connection and just log it out.

If you don't, then each and every request should come with the device ID. When a user logs in successfully, you save the "last known device ID" to their user, and you only accept requests from a device id and firebase id that match (ie - users can use multiple devices and devices can allow multiple users to play).

raw ravine
#

My ML agent does not want to train. and only half of people AI agents start to move (10 out of 126). I attached all of the separetly. Also in Heuristic mode lights does not switch on on pressing on G.
Need your help!

pastel finch
#

Given a generic mesh made of of a grid of points (and enclosed by a spline) and a getHeight(x,z) function... I want to take that 2d closed spline and fill the space between the area represented by the spline toward the grid of points. Anyone have suggestions how to accomplish this?

pastel finch
#

Or perhaps, conversely, is there an algorithm to find and fill holes in a mesh with tris?

misty glade
#

I have a teammate who deleted a cs file out of the /Library/PackageCache folder and committed it to their PR. The entire directory is in gitignore so I'm not sure how deleting it made it but.. how can I resolve this? Is there a way to force the package cache to be rebuilt? Should I just send him the cs file and have him drop it in his directory?

scenic forge
#

(And of course, fix that commit)

misty glade
#

k.. not sure if this is a unity question, even, but I'm puzzled at how it's in the PR when the entire folder is in the gitignore

scenic forge
#

Yeah that's weird, might want to make sure nothing in Library got accidentally checked in in older commits and no one caught that.

outer barn
#

my profiler is showing these spikes is it because of the behavior updates?

#

I currently have around 200 zombies that use a* to find the player

shy nebula
outer barn
#

@shy nebula which part says that

shy nebula
#

the... blue area?

#

light blue is anims

outer barn
#

@shy nebula my bad , yeah i see it

#

I am using spine for the animatinos

untold moth
# shy nebula

Pretty sure this is scripts. Animation has a slightly different color. Also looking at the hierarchy, it's clearly scripts.

untold moth
shy nebula
untold moth
#

Anyways, it would be clearer if they share more details

shy nebula
outer barn
#

No worries

hybrid belfry
#

I'm getting strings from a JSON (using Newtonsoft JSON), but the trailing zero's are being removed. How can I maintain the trailing zeroes?

untold moth
stuck plinth
hybrid belfry
frail kestrel
# hybrid belfry I'm getting strings from a JSON (using Newtonsoft JSON), but the trailing zero's...

Wouldn't String.Format()work for this too? String.Format("{0:0.00}", 0.8); should make 0.80

Source: https://stackoverflow.com/questions/6951335/using-string-format-to-show-decimal-up-to-2-places-or-simple-integer

sick haven
tall ferry
#

!code this isnt viewable on mobile. Also more likely a beginner or general issue based on the description

thorn flintBOT
ionic timber
regal lava
#

usually something slow enough that only a handful of people know

tall ferry
half swan
# ionic timber Got it

I always consider it more about the level of the questioner. Are THEY advanced? Then they likely know how to debug and research. If it is a kind of novel or ambiguous issue that thorough research isn't answering, it is likely advanced.

outer barn
half swan
#

It is the same thing, EXCEPT the build isn't also running the editor

#

Now, the device running the build could be less performant than the one running the editor...

outer barn
#

@half swan I added a profile marker and I can see that the path calcualtion is taking up too much resources, since I am using A*

untold moth
#

Probably contributing to that cpu time quite a bit.
But you'd use the hierarchy view to see what exactly is the issue. The marker doesn't really help in that regard.

delicate mural
#

Say, if you guys had to make a dynamic system of weapons attachments, how would you go about routing the references to the main part of the gun?
I have the FirearmAttachment, and it goes on an AttachmentMount, which could be on a FirearmAttachment of it's own, so on and so forth
Actually just pipe a reference to the main body of the gun through those chains? Seems bulky. Let me know if you guys can think of a better way.

#

And what if, for example, you had a barrel (attachment) and a muzzle device on the end of the gun that reduces recoil. The muzzle device has a reference to the reciever, and then if the barrel gets disconnected then there is just a muzzle in the world still reducing recoil not attached.

compact ingot
delicate mural
#

Not here, no.

#

I already figured out one potential solution that I like.

zealous fern
#

Hello, anyone who has worked with Oculus lipsync here?

hardy jacinth
#

do unity sub-assets have some kind of key?

#

when I add something with AssetDatabase.AddObjectToAsset(...)

#

then when I later want to retrieve a sub-asset I can use AssetDatabase.LoadAssetAtPath<SomeType>(...)

#

or GetAllAssets and similar

#

but they only return by type

#

I'm lacking some kind of mechanism to ensure that there is only one sub-asset with, let's say, key currentSomething

flint sage
lusty basalt
#

Hey! One of my students tried building a project where the build failed(got stuck for an hour and then failed, as she explains it) for some reason(my guess is lack of HD space, but since I wasnt there and all the logs are gone I cant confirm) She tried several more times and then tried to troubleshoot by doing a full project reimport. After the reimport, she tried building again, and during that failed build all of her scripting assets and most other local assets simply disapeared without a trace.
Since then, before I was told, she's done a bunch of troubleshooting togheter with her partner, commendable, but it also means I have no logs to go off of an a lot of the cache files have been overwritten by new ones. Anyone have any idea what might have happened, and if there is any binary, dynamic library or similar I can do black magic on to try to get her work back?

#

They are using version control, but since this was quite a crunchy weekend for them noone thought to commit anything since saturday. I feel so sad for them, but I cant find a fix

#

Or even know what happened

bold shuttle
#

I dont know if/ how to get back the progress

#

But good learning experience none the less, version control doesnt do anything if you dont use it ๐Ÿคทโ€โ™‚๏ธ Simply having something installed is not "using version control"
At least now they know for next time i guess?

flint sage
#

It's a good story to tell new students and get them to use vcs

#

If it was out of disk space, I guess it could've written partial corrupt files

#

And then deleted them after

lusty basalt
#

Yeah in the long term its a good learning experience. I just hate seeing them so down. ๐Ÿ˜ญ

hardy jacinth
#

Several days of work, a shame indeed, but also a good lesson for the future. Now that they know and remember roughly what they did, they can treat it as a "burned prototype" they can build more solid foundation on though.

#

possibly investigating Library/Artifacts could yield something

lusty basalt
#

Yeah, the real kicker is that they were aiming for a contest deadline yesterday and were actually building the final submission. But get burned once like this and it never happens again I supposed

#

This body is made from infinite swords etc

robust drift
#

I have a python library that I'd like to use for my Unity-made Android app. Is it possible to run python code on Android via Unity?

#

Doesn't need to be massively performant

lusty basalt
robust drift
#

Hmm, possibly, but since the output is an audiostream I'm not sure the result would be particularly good. I guess it depends on the bandwith I could get between the two apps using that method ๐Ÿค”

lusty basalt
#

In that case my gut reaction is to have the python app do playback and then sync output via timestamps in some way

#

maybe give visual output a bit of a delay and then just have the unity program write the audio events it wants to a file

#

or sumthing

#

then you dont have to worry about bandwidth

#

its a messy solution

robust drift
#

I think I could get away without sync, as it's essentially a text to speech library. A small delay is perfectly acceptable, as long as the audiostream isn't choppy. I could try to just output a .wav file and then read that from Unity, no need to read it as a stream. I'd need a way to clean up the files so I don't bloat the storage, but that should be doable.

#

I was hoping to find a way to do this via the unity app though, it's a little messy to start a secondary app on the side

lusty basalt
#

like I said, dont take my word for it, there could easily be sopmething

#

๐Ÿ™‚

robust drift
#

Yeah, I'll keep looking ๐Ÿ˜›

tiny pewter
#

in you own machine, you can start a new python process=>io redirection=>call python process=>listen to stdout=>done
but i am not a android developer and i dont if android os provides such functionalities
so keep waiting....

sturdy timber
#

Hey can anyone help why this eroor keeps occuring, even tho i check if its completed, it still throws this error, is it because if noise job is finished the iscompleted becomes true even if surface job has jus started or wasnt finished

sly grove
tiny pewter
#

how often you call Schedule Job, seems like two instances of GetMeshJob()? write to the native list at the same time

sturdy timber
#

But i think thats possible to fix with queue system.

sturdy timber
livid kraken
robust drift
livid kraken
#

Anyone know why this is taking so much time when I async load a new scene in ? Deep profiling does not show anything else. Is it loading in the audio for the scene ? It does not have that much audio. And if that is the problem how can I check ?

hardy jacinth
#

are you loading many scenes in parallel?

livid kraken
#

No, I also found that forum thread by QA Jesus ๐Ÿ˜„

#

Just one scene

hardy jacinth
#

xd

#

what's your loading type on audio files?

#

Streaming or Decompress on Load?

#

if you don't have Streaming you may check it out

#

if it's working for you ofc

#

(the setting on the audio importer)

#

try to use Streaming on clips and see if it helps

livid kraken
#

I should first check the memory profiler maybe to see what audio gets loaded in

#

I know about the streaming option I believe most of our bigger audio like long running ambiences etc are set to that

misty glade
#

I have an admin tool exe (built in unity) that my level designers use. It's got a whole bunch of logging content that is kind of a pain to view in real time - the admin tool doesn't have a lot of visual space (I already have a "console" in it that the users can press to view the log, but the functionality is really rudimentary and clunky). I know that the logs already go to the player.log file but it'd be nice to have it visible in realtime.

Any ideas for .. opening a cmd/terminal window and hook into stderr/out on windows for logging?

thick thorn
#

how do people have game logic asynchronously request player input without undue coupling to the UI system? do you have some request queue or something that is processed by a ui manager?
for example, i have a calendar that is executing game events at given times. some of these game events require player input. i don't want the calendar to call the ui. should i have the calendar have access to some sort of "player request queue" that stores events with possible choices and a callback?

sly grove
split inlet
# thick thorn how do people have game logic asynchronously request player input without undue ...

As stated already, your calender should trigger events. Depending on how you want to implement it, it could be beneficial to also take a step back: your calender UI is displaying the state of the calendar data i. e. which "apointments" there are (even if not all are displayed to the player), what the current time is, how many and which activities are pending and mandatory, etc.
once the current time reaches an appointment, an event about this state change would notify other systems in your game about this. Maybe this means that a time stopping popup appears to get the player to do something, maybe there is another notification. The Calendar icon (assuming you have one) could now indicate that there is a mandatory activity in the calendar (if there is one) so that the player can click on it.
In the calendar, the appointment could be highlighted to indicate pending input from the player.

Keep in mind that I made a few assumptions about how this could look like, and your game might look different from this.

thick thorn
#

The way it's implemented right now, the calendar records GameEvents (custom class) into a SortedList and pulls them off and executes their "execute" method when the time comes. What it appears you guys are suggesting is that, in addition to this, I should also fire off a "GameEventExecuted" C# event every time this happens. The GameEventExecuted event can have signature (delegate) Action<GameEvemt> and thus pass the game event that was executed so that anybody who cares about this GameEvent can examine it and determine what to do.

#

Hmm, connecting some sort of UI manager/filterer to this singular event and filtering all events based on whatever desired criteria is probably a good way to delegate the events to appropriate UI elements without having the engine know about the UI.

#

Thanks guys.

misty glade
#

I'm .. experiencing something weird, and not sure if I'm missing something obvious.

I'm instantiating this prefab and fiddling with local position, scale, etc. Sometimes it works, and sometimes it doesn't. I seem to have narrowed it down to whether or not the parent is active, which is weird, because there's no layout/fitter stuff in this object or anywhere up the hierarchy.

Any ideas what would cause the following code to place this object in a different place based on whether or not the object is active when this code runs?

                _spineCrew = Instantiate(SpineCrewDatabase.GetSpineCrew(crewType), SpineCrewContainer.transform);
                _spineCrew.SetState(CrewState.Idle); // animation stuff - doesn't touch location
                _spineCrew.transform.localScale = Vector3.one;
                _spineCrew.transform.localScale = Vector3.one * 1.6f;
                Vector2 pivotedPosition = _spineCrew.GetPivotedPosition(); // code pasted below
                RectTransform newActorRT = _spineCrew.transform as RectTransform;
                newActorRT.anchorMin = new(0.5f, 0.5f);
                newActorRT.anchorMax = new(0.5f, 0.5f);
                (_spineCrew.transform as RectTransform).pivot = new(0.5f, 0.5f);
                _spineCrew.transform.localPosition = Vector2.zero - pivotedPosition;
                _spineCrewLocalPosition = _spineCrew.transform.localPosition;

        // Gets a "center" of this object based on the pivot - I use this to focus on the "nose" of the character
        public Vector2 GetPivotedPosition()
        {
            Vector2 diff = (_originalPivot - new Vector2(0.5f, 0.5f)) * transform.localScale.y;
            float y = diff.y * 350;
            float x = diff.x * 175;
            Vector2 ret = new(x, y);
            return ret;
        }

#

nothing in the above block seems like it should depend on the game object being active or not

#

wait.. i'm dumb, I have some init in the prefab that sets _originalPivot. ๐Ÿคฆโ€โ™‚๏ธ

#

thanks rubber ducks :p

upper island
#

does Camera.rect get temporarily set to 0,0,1,1 while rendering? I'm trying to read it in RenderPipelineManager.endCameraRendering but it always returns 0,0,1,1 even though I set it to different value before

scenic zinc
#

Hi All, I've implemented a function to check if four same colored(tag) crates form a winning pattern Diagonally, the win condition should be met, the problem I'm facing here is that, I have a 7 column and 6 rows grid array, the win condition is perfectly triggering in " \ " this diagonal direction. However, it's not triggering the win condition on " / " this direction, can someone please look into the code below and tell me what could be the possible reason behind?

private bool CheckForDiagonalWin(string crateTag, int startX, int startY, int startZ)
{
// Check diagonal
if (startX <= gridSizeX - 4 && startY <= gridSizeY - 4)
{
for (int i = 0; i < 4; i++)
{
if (gridArray[startX + i, startY + i, startZ] == null || !gridArray[startX + i, startY + i, startZ].CompareTag(crateTag))
return false;
}

        Debug.Log("Diagonal \\ Win Condition Met!");
        LogWinningCrates(crateTag, startX, startY, startZ, 1, 1, 0);
        return true;
    }

    // Check diagonal /
    if (startX >= 3 && startY <= gridSizeY - 4)
    {
        for (int i = 0; i < 4; i++)
        {
            if (gridArray[startX - i, startY + i, startZ] == null || !gridArray[startX - i, startY + i, startZ].CompareTag(crateTag))
                return false;
        }

        Debug.Log("Diagonal / Win Condition Met!");
        LogWinningCrates(crateTag, startX, startY, startZ, -1, 1, 0);
        return true;
    }

    return false;
}
tiny pewter
#

!code

thorn flintBOT
tiny pewter
#

thats why i dont recommend early return

scenic zinc
tiny pewter
#

yes

#

either use goto or create two method eg

return no '/' pattern && no '\';
scenic zinc
#

I'm sorry, I'm new to this channel and don't understand too much of coding words.. Please accept my apology. Please help me with the issue I'm facing

lament salmon
#

Might wanna stick to code-beginner then. Btw dont cross post. Have some patience

tiny pewter
#
private bool CheckForDiagonalWin(string crateTag, int startX, int startY, int startZ){
    // Check diagonal '\' pattern
    if (startX <= gridSizeX - 4 && startY <= gridSizeY - 4){
        for (int i = 0; i < 4; i++){
            if (gridArray[startX + i, startY + i, startZ] == null||!gridArray[startX + i, startY + i, startZ].CompareTag(crateTag))
                return false;<--early return...
        }
        //other codes
    }
    
    // Check diagonal '/'
    //other codes
    return false;
} 

scenic zinc
tiny pewter
#

yes

#

if first one fail then it will check the second

#

if both fail then there is no '/' or '\'

scenic zinc
scenic zinc
tiny pewter
#
if (gridArray[startX + i, startY + i, startZ] == null||!gridArray[startX + i, startY + i, startZ].CompareTag(crateTag))
```to
```cs
GameObject obj=gridArray[startX + i, startY + i, startZ];
if(obj==null||!obj.CompareTag(crateTag))
```to prevent you forget to change the way of calculating coordinate in future, eg
```cs
if (gridArray[startX + i, startY + i, startZ] == null||!gridArray[startX - i (not + i), startY + i, startZ].CompareTag(crateTag))
scenic zinc
tiny pewter
#

you can ask for help from the others in other coding channels

eager willow
#

hello everyone

#

How do I hide the code of the functions I have coded in unity?

long ivy
#

what did your research turn up?

eager willow
long ivy
#

It sounds like you haven't started the "try to answer your own question" part of the research

soft moon
remote pumice
humble leaf
# eager willow thanks bro

You be clear, it's impossible to hide anything. You can only make it slightly more difficult for people.

remote pumice
#

You're welcome, I never researched anything in that direction, but I know there are some assets for that (read reviews first xD)..
Also, this doesn't make your project "secure" by default, people with the skills and the motivation will still be able to reverse engineer your project without a doubt

eager willow
#

I looked for it, but it seems to be the part I want

humble leaf
#

You had no issues with your English, I'm just letting you know that if someone wants to modify your game, they can

eager willow
#

I'm trying to find the problem I want, specifically I have created a function and people who code in the same project as me will be able to use it but I don't want them to see it, what should I do?

remote pumice
#

Oh, that's a whole different thing..
Why wouldn't you want the people that work on the same project to see your work?
That's probably harming their productivity

eager willow
#

I want my code to be protected from others when developing games, I don't want them to see it

remote pumice
#

Yes, I understood that, but why..
I'd almost guess you're not using any version control?

eager willow
#

It took me a lot of time. If they found out, the values โ€‹โ€‹I worked on would be taken away in a way that made me uncomfortable.

remote pumice
#

Dude.... Please.... Give me the why .
If they work on the same project as you do, they should be able to see your stuff

remote pumice
eager willow
#

Well, maybe I didn't make it clear, I did create modifiers on the editor, changes for the attributes, it's quite flexible and I don't want it to be stolen.

remote pumice
#

Idk if it's possible to obfuscate a single .dll and include that obfuscated .dll in the project and have it still working

#

But that should be your direction of research, if you're serious about that

tall ferry
#

Sounds.. suspicious. If you are working on a project with people, theres nothing you can really do about it. And I doubt people would wanna work with such style where their team members are hiding functionality.

remote pumice
tall ferry
#

Imagine the chaos when theres a bug and you cannot even check stuff like the editor scripts or attributes that may be affecting it

eager willow
#

The editor codes that I code, I think maybe after the project they can use them without me being able to do anything

remote pumice
remote pumice
#

And even if you put some kind of copyright comment or whatever into the files, doesn't matter because 1. It's obfuscated and 2. Probably stripped from build anyways

#

The best advice here is probably, don't take this as an insult.. Do not work with people

eager willow
#

I think I should adapt to it

rugged radish
#

if you're paid for that work, creating artificial obstacles like that sounds malicious

#

and if it's something you developed in your own time and you want recognition or compensation, best way to go is making it open source (for recognition) or publishing it in an asset store (for compensation) imo

half swan
hallow creek
#

i sometimes dont even understand what my code does

lofty inlet
#

is there a way to do this in one line without using &&?

GameObject object = transform.Find("X").gameObject
if(object) object.SetActive(false)
half swan
#

And don't use Find

somber swift
lofty inlet
#

why no find?

lofty inlet
somber swift
lofty inlet
somber swift
lofty inlet
#

I think both of yall thought I was using gameobject.find lol

#

I don't think it would apply to transform.find

#

should be the same speed as getcomponent

#

only searches the children of the transform

somber swift
lofty inlet
#

but not nearly as slow as gameobject.find

#

which I never use

lofty inlet
#

just the string comparison making it super slow?

half swan
lofty inlet
#

no

somber swift
#

yeah, I wouldn't say string comparisons are necessarily that slow or bad coding practise but relying on gameObject names isn't usually very good practise

half swan
lofty inlet
#

yeah that might work ๐Ÿ‘

half swan
#

If you can, it is always the preferred choice.
If you cannot, at least try to pass the reference via the instantiate return.

lofty inlet
#

the thing is there's a lot of gameobjects with that script
so if I set a reference at on start/awake, I feel like that might decrease overall speed (load time) versus if I just do the 2 liner every couple seconds max

dusty wigeon
half swan
lofty inlet
#

I'll try that

dusty wigeon
#

You clearly do not know what could go wrong.

lofty inlet
lofty inlet
dusty wigeon
# lofty inlet what can go wrong

Unity is overriding the null operator. If you destroy an object, you still have a reference to the object but unity will says that the object is no longer valid.

lofty inlet
#

what if the object is never destroyed?

dusty wigeon
# lofty inlet what can go wrong

You could create an extension method

public static GameObject FindAndDeactivate(this GameObject gameObject)
{
  //Beware that you could have a null exception with you current code if you do not find the object and that object is not a valid name.
  GameObject object = transform.Find("X").gameObject
  if(object) object.SetActive(false)
  return object;
}
dusty wigeon
lofty inlet
#

what

dusty wigeon
# lofty inlet what

The error is not obvious, when you are going to hit it, you will probably search for a long time.

lofty inlet
#

I'll roll that dice ๐Ÿ˜

dusty wigeon
#

What have I done.

tall ferry