#archived-code-advanced

1 messages Β· Page 95 of 1

bleak citrus
#

allocate once, return many times

#

but I think pooling is going to be the way to go here

full ledge
#

Hello, help me!
I'm storing Dictionaries in firebase as Dictionary<string, object>'s. This way I can have dictionaries with different values(The dictionaries contain <string, string>'s and List<string>'s. I'm assigning the pulled dictionary to a local object but when I try accessing it this happens.

List<string> unlockedTaskIds = userObject["UnlockedTasks"];
error CS0266: Cannot implicitly convert type 'object' to 'System.Collections.Generic.List<string>'

This makes the compile error go away but triggers an error on runtime.
unlockedTaskIds = (List<string>)userObject["UnlockedTasks"];
Exception occurred while getting user: Specified cast is not valid.

sly grove
full ledge
tiny pewter
#
if(the value is List<string> list){
}else{
  Debug.LogError($"WHAT {value.GetType()}");
}
```please verify the value is list<string>
untold moth
full ledge
tiny pewter
#

so check it
you think it is list<string> but your runtime doesnt think so

full ledge
untold moth
#

You must be having several lists, both with strings and with objects. And the errors are probably coming from casting the wrong one to the wrong type.

#

Honestly, I'd scratch that implementation entirely. Boxing with Objects is not a great idea.

full ledge
# untold moth You must be having several lists, both with strings and with objects. And the er...

My work around for now is to request it separately
List<string> unlockedTaskIds =await RequestAny("Users", fBAuth.UserId, "UnlockedAdventureIds");
Not sure why this would work instead of accessing it from the dictionary but o well

And i don't, here's the schema. strange issue

    public Dictionary<string, object> ToDictionary()
    {
        Dictionary<string, object> dict = new Dictionary<string, object>();
        dict["UserID"] = UserID;
        dict["Username"] = Username;
        dict["Email"] = Email;
        dict["CreatedAdventureIds"] = CreatedAdventureIds;
        dict["UnlockedAdventures"] = UnlockedAdventures;
        dict["UnlockedTasks"] = UnlockedTasks;
        dict["CompletedTaskIds"] = CompletedTaskIds;
        dict["ImageRefs"] = ImageRefs;
        dict["AvailableNFCTags"] = AvailableNFCTags
        return dict;
    }

    public User()
    {
        UserID = "";
        Username = "";
        Email = "";
        CreatedAdventureIds = new List<string>();
        UnlockedAdventures = new List<string>();
        CompletedTaskIds = new List<string>();
        UnlockedTasks = new List<string>();
        ImageRefs = new List<string>();
        AvailableNFCTags = new List<string>();
    }
hardy jacinth
#

missing ending code fence

hardy jacinth
full ledge
# hardy jacinth and a newline after opening code fence

If that were the problem I'd know, It's just a snippet to show I dont have any List<object>'s in my schema. It's a functional application, I would just cut down on firebase requests if I could resolve this type strangeness.

hardy jacinth
full ledge
craggy sierra
full ledge
craggy sierra
#

The cs is on a newline I think

#

Its showing in your code

#

It has to be on the same line like I showed to work

full ledge
#

It was

craggy sierra
#

Oh, its because you added a space

full ledge
craggy sierra
full ledge
craggy sierra
#

Yea now it should have syntax highlighting like in the IDE

lyric mirage
#

yo peps

misty glade
#

I could use a code review on the following: https://pastebin.com/96hcwrC5

I have a list of "animations" and an enum of the states. There are .. a lot of states (15ish?) so there's ~225 possible transitions. The library I'm using handles the transitions automatically, but allows for us to play animation transitions ourselves manually. I need a way to .. allow the animators to create an animation, add it to a list (at design/compile time) and at runtime, look for an animation transition.

Worse, there's "fallback" states - ie, the "Excited" animation will play the "Happy" animation if Excited doesn't exist.

This is my current solution, but it feels extremely smelly, but a better one isn't popping out to me.

I already hate this approach (hard coded stringifying enums and back) ..

#

or perhaps something that's easier to read/understand is like..

List<(fromState, toState)> fallbackStates = new();
CrewState fallbackFrom = from;
CrewState fallbackTo = to;
while (fallbackFrom != None)
{
  while (fallbackTo != None)
  {
    fallbackStates.Add((fallbackTo, fallbackFrom));
    fallbackTo = GetFallbackState(fallbackTo);
  }
  fallbackFrom = GetFallbackState(fallbackFrom);
}

// then iterate the tuple list until we find an animation - the first item will be the non-fallback "to" and "from" states ...
tired fog
#

I want to make a bunch of jobs that read and write to the same Native Hash Map, whats the best way to do it?

dusty wigeon
misty glade
#

Yeah I just.. haven't brained-up something that is easy to read/maintain for when something in this piece of code breaks a year from now

brisk pasture
#

2 iterations of loop deep and recursions yeah that is going to be slow

misty glade
#

well it's not gonna be slow unless it's broken πŸ™‚ we're talking N = 5 or 10 here

#

it's more the.. complexity/readability

dusty wigeon
#

Just moving the condition "if (fallbackFrom == CrewState.None)" into the while could help with readability. Maybe

misty glade
#

yeah, or maybe this is the rare case of a do {} while () loop

dusty wigeon
#

Also, you could divide into two function.

#

One with the inner loop, and the other with the other loop

brisk pasture
#

so dont really understand the the intent, but if its recursing is that because its walking down them as nodes in a tree?

#

also if n == 5 - 10 really could just move on to the next thing that needs to be solved

misty glade
#

sorta.. so like, imagine this list of transition animations:

A to B
A to C
A to D
E to F
E to G
E to H

and this fallback definition:

I to A
J to E

I need a call for: GetTransitionAnimation(A, B) to return A to B (as expected, it's defined); but also GetTransitionAnimation(I, B) to return the same result, since "I" can fall back to "A" as a valid.. animation fallback.

#

Any time I GetTransitionAnimation(from, to) I need to iterate all the "froms" and "tos" that are valid for the call, and look those up in a list of animations

brisk pasture
#

if it works would move on, if it gets costly it does not look that hard to cache the relationships to a dict as you find them for faster retrival in the future

misty glade
#

this is what a typical "data set" looks like:

dusty wigeon
misty glade
#

so if there's a call to SetState(Idle) then SetState(Nervous) - the animator plays Idle, then Idle_To_Nervous, then Nervous.. If there's no Idle_To_Nervous that's fine, it just plays idle, then nervous (directly)

#

Hmm.. and just craft that at awake time?

dusty wigeon
#

That, given that you do not have a "priority" over which one to use

brisk pasture
misty glade
#

I do have a priority

#

Or rather.. there won't be any complex graph loops here

brisk pasture
#

or is CrewState a enum?

misty glade
#

crewstate's an enum, yeah

brisk pasture
#

flag enum

dusty wigeon
#

Yeah, then it wont work.

brisk pasture
#

if its a flag enum the keys could just be bitwise or operations

misty glade
#

definitely not going that route since it's not a flag. πŸ™‚ there's only one "value" per se

#

like, i don't want to make the admin tool have some UI element other than a dropdown for "play this animation".. if that makes sense

#

like I don't want to do "play this animation or this one or this one"

brisk pasture
#

value tuples might work then to combine the multiple enum values into 1 dict key

fallow echo
#

so if you want A to E, but you don't have that and you have fallbacks A->B and E->F, and you have both A to F and E to B B to E animations - which one would you use?

misty glade
#

neither

#

it would just play "E" directly from A

fallow echo
#

why neither?

misty glade
#

that's how this particular library works.. lemme maybe show rather than tell πŸ˜› sec

#

here's sad, nervous, and nervous-to-sad

fallow echo
#

(corrected myself up there a bit, but I think you got the point)

misty glade
#

if nervous-to-sad doesn't exist, just go from looping on nervous to looping on sad - there might be a little hiccup in the framerate but it's nbd

brisk pasture
#

oh its spine

misty glade
#

yeah

brisk pasture
#

yeah using spine too, but i ended up skipping there stuff and used mecanim with it

misty glade
#

but since we have so many programmatic "states" - there's states^2 possible transition animations, only a fraction of which are going to be defined

#

(there's also 65 distinct characters so we're talking a huge amount of animation)

misty glade
#

but in-game, we might say "whoever the character is, SetState(Excited) and it should just work

#

if Excited isn't defined, then show Happy

#

(Happy is the fallback for Excited)

fallow echo
#

okay, but that doesn't affect the transition?

misty glade
#

but it gets more complex (which is offtopic a bit, but just so you get the concept) some crew's Excited fallback is Angry (since they're "angry" as a positive emotion)

#

it does affect the transition but not too badly, since spine sorta "does the magic" by itself

brisk pasture
#

it really sounds like you got a whole tree structure going on then

dusty wigeon
#

The fallback i not really a fallback but a replace ?

misty glade
#

but in cases where there's .. flipping sprites or doodads, they can flicker or disappear awkwardly if the transition animation isn't built

brisk pasture
#

think i would just kinda traverse it with a stack

fallow echo
#

my point is, you're not looking for transitions from/to fallbacks

misty glade
#

yeah, it's kind of a tree structure

misty glade
#

like say "HappyToAngry" is defined, and "Excited" is defined (but no ExcitedToAngry). If I SetState(Excited) then SetState(Angry) I should play the HappyToAngry transition animation, then the Angry animation

dusty wigeon
#

Why you do not fallback then look for a transition ?
Like Excited= Happy for a given charater, hence a transition from Excited to Angry would be Happy to Angry ?

misty glade
#

starting the HappyAnimation directly from Excited? hm, that's an idea, but I don't think it solves my problem (i would still need to build the "what transitions do I have and then what fallback state should I go to to start the transition" data structure)

#

I mean, let's be clear - what I have "works" but I think it's just smelly

brisk pasture
#

like i said before what you have is not that much code, and if it works fairly bug free

dusty wigeon
#

I mean, I feel like I either do not understand your issue or you are making your issue bigger than what it is.

brisk pasture
#

i would just comment it and explain what is going on and move on

dusty wigeon
#

What we want: Transition -> Excited to Angry.
Character is replacing Excited by Happy.
Hence: Transition -> Happy to Angry

misty glade
#

Aight - I mean, yeah, it "works" but my issue is more that this.. feels smelly, feels ricketey, and I don't quite know why, and worry about hacky sort of solutions like this. πŸ™‚

brisk pasture
misty glade
#

like if I saw one of my juniors write two embedded while(true) loops it would immediately stop me from what I was doing to .. criticise it πŸ™‚

brisk pasture
#

the outer one is literally a do while with fallbackFrom == CrewState.None for condition

dusty wigeon
#

So yeah, to clean it I would personally do that.

misty glade
#

ya i suppose i'll just change to do/while (not a loop construct I use all that often tbh) but feel like between the recursion and that, it's.. hard to grok

#

Aight, gotta run, thanks for the look friends

fallow echo
#

isn't the recursive call kinda duplicate work? πŸ€”

#

the two while loops already do all the enumerating, no?

dusty wigeon
#

Yeah, why is there a recursion there πŸ€”

brisk pasture
#

having both is what i found most strange

fallow echo
#

@misty glade might be worth thinking about that πŸ‘†

brisk pasture
#

find i tend to have iterative or recursive approaches

#

not both at once

#

though i really prefer iterative so tend to convert recursive approaches to iterative with a stack

fallow echo
#

yep, I think one of them can be "removed"

brisk pasture
#

its only 1 thing to a other thing as a transition so 2 loops makes sense but that is the depth of iteration it would need no further

fallow echo
#

recursive here would be super short... but kinda Fibonacci-y πŸ˜„

brisk pasture
#

give the size of data set would be fine too, not going to blow a stack with it

#

fallbacks i think i would have called overrides

#

but really its just a preprocess before doing it

fallow echo
#

why? they seem pretty much like fallbacks to me πŸ€”

brisk pasture
#

oh maybe i was mixing it up with osmething they were saying

#

thought the explained cases like for character A excited == happy or something like that

fallow echo
#

ah, that they did, yeah

brisk pasture
#

maybe character B it maps to something else

misty glade
#

The iteration is for the exact match, the recursion is for fallback matches, recursively, because the fallback state can also have a fallback: ie "angry" falls back to sad falls back to idle

west kestrel
#

I know this is a weird question, but is there a way to modify a script during a build? I'm trying to make a tool that allows you to edit the default values of variables in static classes from the inspector, but I would need to hard-code those values in for it to work in the build, so is there something in the build pipeline that allows for editing of scripts on build?

untold moth
west kestrel
#

I mean like edit the script during the building process, not in the runtime application that's produced from the build, so it would edit it and then compile it

cloud wadi
#

Im getting an Error CS1503 anyone know the reason?

west kestrel
untold moth
fallow echo
paper pendant
#

WARNING:We recommend using a newer Android Gradle plugin to use compileSdk = 33

This Android Gradle plugin (7.1.2) was tested up to compileSdk = 32

Does anyone familiar with android apk error?

devout hare
paper pendant
#

Thanks i think you are not familiar πŸ₯² @devout hare

paper moth
#

can someone DM me to help me with some Unity Job System Code.. it is my first time working with that and i really try to figure out what i am doing wrong.. i also watched some tutorials but i don't see my mistakes (i am self tought and maybe do not understand everything perfectly) πŸ™‚

tiny pewter
#

why dont you just post your code?

paper moth
#

it was too long.. i will split it sec

tiny pewter
#

!code

thorn flintBOT
tiny pewter
#

btw asking in dots maybe better

paper moth
half swan
paper moth
#

the problem is that i have zero performance improvement when i use the jobsystem.. either i do something completly wrong or i am just dumb πŸ˜„

tiny pewter
#

dont allocate a persistent array in update

paper moth
#

daaamn this should be temp

tiny pewter
#

and use i job parallel for transform

paper moth
#

could this be the issue why i don't have any performance differences?

tiny pewter
#

btw dont do that

 NativeArray<float3> enemyPositions = new NativeArray<float3>(activeEnemies.Count, Allocator.Persistent);

if (enemyPositions.Length == 0)
    return;
```check before you allocate
malloc a 0 size buffer is undefined behaviour, may result on memory leak if you dont free it
paper moth
#

please a fair answer.. how far i am away from a good solution? πŸ˜„ πŸ˜„ like i said everything self tought and way early beginner πŸ˜„

tiny pewter
#

learn how to use i job parallel for transform should be ok right now if you are moving bunch of transforms

paper moth
#

i will have a look into that thanks a lot!!

paper moth
tiny pewter
#

no, probably the one who write it use malloc a lot and forgot temp allocation

#

btw this page just demonstrates the job not the allocation options differences

paper moth
#

okay thanks for explanation

tired fog
#

they must be structs and/or value type

tired fog
#

Btw, unity crashes when the Dispose method of a NativeArray gets called, is there any clear reason why that would be?

#

i create the native array, call a job, complete the job, and then call dispose and unity crashes

sly grove
tired fog
#

yup it says it crashes when I call Dispose on the native array

#

or at least the stack trace bring me there

#

Sorry, not NativeArray, but NativeList

#

In line 507 of NativeList, which there's this

[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
bleak citrus
#

How are you allocating the list?

#

Do you ever alias the list by calling AsArray() on it?

#

I think it'll also implicitly convert to NativeArray if you pass it to something that wants a NativeArray

wet ore
#

Hello guys, i'm having a little problem

I made a resources folder and my goal is to load the good resource from it with this code

public void SpawnWeapon(NetworkVariable<int> weaponSpawn)
    {   
        GameObject temp = Resources.Load<GameObject>("ScriptableObject/Player/Weapons/W_" + weaponSpawn.Value);
        ////weapon = AssetDatabase.LoadAssetAtPath<SO_Weapons>("Assets/Resources/ScriptableObject/Player/Weapons/W_" + weaponSpawn.Value + ".asset");
        PlayerController playerController = GetComponent<PlayerController>();
        if (Resources.Load<GameObject>("ScriptableObject/Player/Weapons/W_" + weaponSpawn.Value) != null)
        {
            playerController.playerWeapon.text = temp.GetComponent<SO_Weapons>().m_weaponName;
        }
        else
        {
            Debug.Log("Weapon not found");
        }
    }```
but when i build i always have an error and i don't know why
#

here is the folder and path

tall ferry
#

Asset database is editor only iirc

wet ore
#

well seems like i can now make a build unity must used a bit of magic

slender stag
#

IΒ΄m trying to modify one of samples that are from TouchExamples, my only issue is that OnDragged is called only when user drags something around, but not hold stationary, what can I do to create an OnHeld or something? Apparently, OnAction is only called one time per user action (but not incluiding if the user is helding button, which only detects when user drags around)

protected virtual void Awake()
        {
            m_Controls = new PointerControls();

            m_Controls.pointer.point.performed += OnAction;
            // The action isn't likely to actually cancel as we've bound it to all kinds of inputs but we still
            // hook this up so in case the entire thing resets, we do get a call.
            m_Controls.pointer.point.canceled += OnAction;

            SyncBindingMask();
        }

protected void OnAction(InputAction.CallbackContext context)
        {
            var control = context.control;
            var device = control.device;

            var isMouseInput = device is Mouse;
            var isPenInput = !isMouseInput && device is Pen;

            // Read our current pointer values.
            var drag = context.ReadValue<PointerInput>();
            if (isMouseInput)
                drag.InputId = Helpers.LeftMouseInputId;
            else if (isPenInput)
                drag.InputId = Helpers.PenInputId;

            if (drag.Contact && !m_Dragging)
            {
                Pressed?.Invoke(drag, context.time);
                m_Dragging = true;
            }
            else if (drag.Contact && m_Dragging)
            {
                Dragged?.Invoke(drag, context.time);
            }
            else
            {
                Released?.Invoke(drag, context.time);
                m_Dragging = false;
            }
        }
proven thorn
#

is there something like memset for nativearray/list? e.g. when I want to set a whole NativeArray<float> to 0

tiny pewter
#

I would get the pointer then memset
Btw memset float to 0 sounds weird

untold moth
upbeat path
severe loom
#

Hey guys, i made this simple spritesheet for an enemy slime. The first 3 sprites are for its charge, the 4th is for the going up part of its jump, the 5th for the falling part, and the last two are for ground contact after falling. What are some good way to make sure that my code for jumping and the correct animation is playing at the right times? Should i keep track of animator times in my code, or code animator times through script? What is generally the right approach here?

proven thorn
severe loom
#

Is it possible to convert the variable _context to a SlimeStatemachine class even though it is defined as EnemyBaseStateMachine in the parent abstract class? By that i mean change the type of variable? Dont know if im wording this right

#

A slimeStateMachine does have the IsGrounded() function, but the EnemyStatemachine parent abstract class does not so im unable to access IsGrounded here, in the picture you can see im trying to perform a cast

severe loom
# severe loom

It happens because My Base State defines the _context as EnemyBaseStateMachine for abstraction purposes

tiny pewter
#

not code advance
you can cast parent class to child class

#
public abstract class BaseState<T,U> where T:Machine where U:Factory{
  protected T _machine;
  protected U _factory;
}
```idk if this works for you
severe loom
#

This is what I came up with now, do you see any problems with this approach?

tiny pewter
#
public class SlimeJump:BaseState<SlimeMachine,SlimeFactory>
severe loom
#

I think you are talking about generics right? Learned a bit about them during my bachelor but knowledge has left me haha

tiny pewter
#

yes

sage radish
severe loom
# tiny pewter yes

Alright, ive been trying your advice a bit. So if my state factory is aware of a context, it should be like this right:

#

This seems right to me, however an issue arises here because of it:

hazy epoch
#

Can anybody explain in lamens terms the difference (if any) between UnityEvents and Actions/EventHandlers?

Other than UnityEvents being serialized in the inspector.

soft marlin
#

Other than UnityEvents being serialized in the inspector, that's pretty much it

tiny pewter
# severe loom Alright, ive been trying your advice a bit. So if my state factory is aware of a...
public abstract class State<TState,TMachine,TFactory>
    where TState:State<TState,TMachine,TFactory>
    where TMachine:Machine<TState,TMachine,TFactory>
    where TFactory:Factory<TState,TMachine,TFactory>{}
public abstract class Machine<TState,TMachine,TFactory>
    where TMachine:Machine<TState,TMachine,TFactory>
    where TState:State<TState,TMachine,TFactory>
    where TFactory:Factory<TState,TMachine,TFactory>{}
public abstract class Factory<TState,TMachine,TFactory>
    where TState:State<TState,TMachine,TFactory>
    where TMachine:Machine<TState,TMachine,TFactory>
    where TFactory:Factory<TState,TMachine,TFactory>{}

public class FactoryA:Factory<StateA,MachineA,FactoryA>{}
public class MachineA:Machine<StateA,MachineA,FactoryA>{}
public class StateA:State<StateA,MachineA,FactoryA>{}
#

probably others may give better ideas for your state machine

craggy summit
#

Is there any way to get multiple different generics ?
I have a generic class Generator<T>, and I would like to GetComponent all the classes that inherit from that class (like Generator<Enemy>, Generator<Environment>, etc)

#

I am pretty sure it is impossible to do, but I'd rather ask here just in case

sly grove
#

or an interface'

plucky laurel
#

the end type is generic?

icy field
#

hey i want to move my inverse kinematic leg smoothly from one point to another with vector3.lerp, but i want to use an animation curve to control the y axis so, it moves like a human leg first up and down, how can i implement that? i can't manage to get it working properly

tepid ridge
plush talon
#

Anyone know if a raycast command can hit the same object twice? for example, a cube's front and internal backface? I have the query parameters setup properly and maxHits set to 2 but it doesnt seem to want to hit it. If that's unsupported does anyone have a solid scalable strategy to get the "exit" position of a raycast commnad?

#

hitMultipleFaces is also enabled, but still not working...

#

Disregard, docs say the following:

For solid objects (Sphere, Capsule, Box, Convex), this returns a maximum of one result.

Idiotic at best... Anyone know a workaround?

hexed meteor
#

Does anyone here know how to access a post process volume element, say bloom, and manipulate its values or enable/disable it individually at runtime ?

hexed meteor
austere jewel
#

SRPs use the volume system, not PPV2

hexed meteor
#

then that's what I mean. The volume system.

hexed meteor
#

I'm using URP though 😦

#

or is it the same concept

austere jewel
#

The concept is similar/identical

hexed meteor
#

thanks a bunch! However this for instance is not working (no errors, just no effect at all)

#

it does work, nevermind sorry about that

#

thank you - you are awesome!

untold moth
#

Anyone else experiencing weird issues where reloading the domain when a vs debugger is attached causes some of the cache(I assume) to be corrupted? Specifically, a TerrainData reference and asset is getting broken and messages about invalid GC handle are spammed. In the explorer I can see the asset increasing in size several times and unity consumes as much memory as it can, eventually crashing. After restarting the asset is back to normal until the issue occurs again.
This is happening on unity 2022.3(I've tried several minor versions, currently the last one) and vs 2022.

#

I'm still not sure about reproduction steps, but it doesn't seem to happen when the debugger is not attached.

fallow echo
untold moth
fallow echo
untold moth
fallow echo
#

I see, I see... not great. I've got no other ideas right now πŸ€” Good luck with it! 🀞

upbeat path
untold moth
upbeat path
untold moth
#

I guess we can try that.

uncut ermine
#

Hello everyone. I need help with json download file on android. It is okay with unity editor but smth wrong when i open apk build on my phone. Just blue screen. I need download file and the serialize file data.

upbeat path
uncut ermine
upbeat path
uncut ermine
#

I will try rn

cedar cradle
#

Im trying to make a custom pathfinding so i can add realistic roads to my procedural terrain and i have a for loop that runs untill verey pixel has been checked right now. It is supposed to save only the direction the current Cell came from to a texture right now but for some reason this function must always return false as it only runs through the while function once and then never again

sly grove
cedar cradle
sly grove
#

!code

thorn flintBOT
cedar cradle
sly grove
#

So what's the question exactly?

cedar cradle
#

why does my for loop stop immediately

sly grove
#

Well typically for A* or Djisktra's you would be adding eligible neighbors to the frontier list

#

Add some debugging but it seems like you're never doing that

#

i.e. frontiers.Add(current); is never happening

#

you'll need to debug to see why

#

but you know presumably the if statement is failing if (diff <= 1)

sly grove
cedar cradle
#

I removed the if statment where it checks if a neighbouring cell hasnt been assigned and i got a line over my texture so the diff isnt failing

if(diff <= 1)
            {
                flowMap.SetPixel(Mathf.RoundToInt(current.x), Mathf.RoundToInt(current.y), Color.green);
                if(!colors.Contains(flowMap.GetPixel(Mathf.RoundToInt(current.x), Mathf.RoundToInt(current.y)))) //this one is failing
                    frontiers.Add(current);
            }

and the diff doesn not fail becuase then there should be magenta pixels wich there arent

cedar cradle
sly grove
#

you're guessing and removing code

#

but you're not debugging

#

attach a debugger or use log statements or both

cedar cradle
#

but if the diff would fail then there would be magenta pixels

sly grove
#

I don't really know why that is true or what I'm looking at here

#

I can only tell you that you should be debugging rather than using roundabout ways to infer things

tired fog
#

How should I do it?

misty glade
#

If you want to use them in your own precompiled DLL, open a new visual studio project, import those dependencies and it should just work

tired fog
#

Unityengine and unityEditor are there, but I cannot find jobs an burst

misty glade
tired fog
#

Well, wtf, what do i do now? XD

#

I want to beta release a paid unity package with the code obfuscated

misty glade
#

bump the post and +1 the roadmap. πŸ™‚

#

I mean, you can still do that - just make some core logic part of your package (that doesn't have the jobs/burst stuff as a dep) precompiled into a DLL, and voila, !OSS

#

although better might be to release it, open source it, and payment is honor system because.. you know, that's how software should work, maybe

#

i dunno that anyone's getting really rich writing and selling plugins

tired fog
#

I don't think that's part of the discussion, although I do plan on open sourcing the package once I stop develpment, since I truly belief that if there's no work being done, there shouldn't be payments

tired fog
misty glade
#

sure, and you're allowed to do whatever you wish tbh πŸ™‚ just saying, unless your plugin is selling several thousand copies, the amount you're making is likely somewhat insignificant.. but yeah, if you're intent on that route (which is totally fine and OK - that's obv your choice) then that's probably what I'd do.. drop as much non-unity code as possible in an external DLL and make your plugin depend on that

#

honestly even a relatively insignificant part of it buried in the DLL is likely enough to get the purchase - if someone's really intent on stealing your plugin, compiling it into a DLL isn't going to stop that (unless you're intending to stand up some licensing server and always-online kind of licensing entitlement server)

tired fog
#

I mean the beta release has already a set of limited features. But I will check what I can and what I cannot build intk a different dll, otherwise i will just have it as is, it's beta release and my current branch already has many changes that would make the beta pretty outdated. I wanna test out the UI part of it mainly

glacial wedge
#

Hi, Need help with add editor debug code

#
    public static AudioClip GetAudioClip(this DictionaryOfLanguageAndAudioClip dict)
    {
        dict.TryGetValue(DataManager.language, out AudioClip result);
        if (result == null)
        {
            dict.TryGetValue(Languages.NONE, out result);
        }

        if (result == null)
        {
            Debug.LogWarning($"AGGIUNGERE Localization per lingua {DataManager.language}");
        }

        return result;
    }
#

I have this static method to retrieve an audioclip from my dictionary

#

the debug.logwarning say in which language the audioclip is missing

#

but I need to know which dictionary is empty

#

in what monobehaviour / scriptableobject

upbeat path
#

The stack trace of the warning will show you where the method is being called from

glacial wedge
#

Ok

signal stirrup
#

Is there any way to realtime (on device) generate a uv unwrap (non overlapping, like a lighting unwrap. The use case is to map unwrap the scanned mesh with a quest 3 so you could draw on it, for example

torn rose
#

I'm creating a "volumetric" mesh in blender using delaunay tetrahedralization. Faces created do not match the mesh's surface, but instead 1 quad per tetrahedron is generated.

In unity, I'd like to determine what triangles lie on the surface of the mesh. My current idea is to iterate through all the faces of every tetrahedrons and offset a point based on their normal, and then see if the point resides in one of the tetrahedrons. If it doesn't, then it's relatively safe to assume the point is outside of the mesh.

Unfortunately, this isn't exclusively for preprocessing, I will need to use this at runtime as well. I am hoping someone knows of a faster way.

soft marlin
#

I'm having a hard time visualizing / understanding your problem. but it sound like this might be more an optimization problem than anything. maybe an AABB or k-d tree + a little threading would be more than fast enough for RT use. have you benchmarked your current idea / solution?

sly grove
dusk trout
#

Hello, I'm doing a test and would like an idea on how to make a feature.
The idea is to create the inertia effect of stacked food like the one in this video:
https://www.youtube.com/watch?v=h5BZPXj-bo8

However, it cannot be done using Unity Joints in 3D.

Would anyone have any pointers on how to do it?

Noodle Run is a food running game where you control a bowl and collect the ingredients for a perfect ramen noodle soup and feed the boy at the end of each level. How high can it get?
Ramen noodle soup is made by collecting the ingredients on the way. Your mission is to collect as many ingredients as you can to make the highest noodle bowl. There...

β–Ά Play video
sly grove
dusk trout
sly grove
#

I don't see any reason you need trigonometry either

dusk trout
sly grove
#

each node follows the previous node

#

and tilts itslef based on its lagging calculated velocity

dusk trout
torn rose
#

@sly grove @soft marlin So your comments inspired me to think of a way to bake extra data to help. One of the ideas was to have a per-face structure that stored connected tetrahedrons, which then led me to notice something that should have been obvious, but wasn't to me I guess...

Every "internal" face is shared by 2 tetrahedrons. So it's safe to assume that if faces aren't shared, then they're on the surface.

That'll be fast enough for me.

#

Thanks for the help

foggy sonnet
#

What is the best method of encryption and does it have any good tutorials?

abstract folio
foggy sonnet
#

thx

sly grove
foggy sonnet
#

I just want things like meshes and textures encrypted

abstract folio
sly grove
#

what are you doing with the encrypted data?

#

who are you trying to prevent from reading it?

foggy sonnet
sly grove
#

As soon as your game loads, the mesh will need to be unencrypted in memory. At that point, a sufficiently motivated actor will be able to snatch it

foggy sonnet
#

Is there a way to make it more difficult?

sly grove
#

Sure you can encrypt the mesh, ship it as a separate file, load it at runtime, unencrypt it, do what you need to. But you'll need to provide the user the encryption key at some point to make the game playable so you're going to spend weeks building a system that makes your game slower and less maintanable and in the end maybe 10% harder to extract the asset.

foggy sonnet
#

oh

sly grove
#

The only "real" way to do this is make your game only playable on a streaming service like Stadia for example

#

such that your mesh data never lives on Hardware you don't control

#

Does Stadia even exist anymore? IDK

subtle river
#

it's dead πŸ˜›

sly grove
#

Why are you so afraid of people ripping your assets?

foggy sonnet
#

I'd be willing to share if I was getting credited and I knew what they where doing

sly grove
half swan
foggy sonnet
sly grove
#

In general though, I would be absolutely ecstatic if a game I made was cared enought about by people to bother ripping the assets

half swan
sly grove
abstract folio
#

I think a simple encryption of the files, that you decrypt when loaded, will make it MUCH harder to extract the data. But as other have pointed out, not impossible.

subtle river
#

At the end of the day if your game is drawing a model, it will be unencryped in GPU memory. People can essentially take a "3D screenshot" of a frame and grab any 3d models they want. So it doesn't even matter if it's encrypted on a harddrive or in regular memory
Example: http://www.deep-shadows.com/hax/3DRipperDX.htm

sly grove
#

Yep - trivial to rip from memory at runtime regardless of any at-rest encryption

#

it's a waste of time to try this stuff tbh

foggy sonnet
#

Thanks

abstract folio
#

Disagree. I think any extra pain=in the ass step you can add reduces the chances of theft.

torn rose
#

@subtle river Can shader information be obtained from those "3D screenshots"?

sly grove
#

But it's a tradeoff

#

is it worth the effort and how much worse your workflow will be?

#

And how much jankier your game is likely to be?

subtle river
sly grove
#

You won't get the benefits of any precomputation phases Unity does with the meshes at build time for example

foggy sonnet
#

My models aren't that good anyway, someone would be an idiot to try and steal them.

torn rose
#

@subtle river So I guess you could apply some obfuscation to meshes and then revert whatever you did at shader level. I mean I wouldn't ever consider this, but it's interesting to know it could be done

half swan
abstract folio
foggy sonnet
#

These probably aren't worth stealing anyway so I should be good πŸ’€

subtle river
# abstract folio agreed, always a tradeoff

A casual actor can easily download software that lets them rip models from the GPU regardless of the encryprion you use. So no I would not say it's worth it since they can completely bypass it

torn rose
foggy sonnet
subtle river
# torn rose <@120967199249793024> So I guess you could apply some obfuscation to meshes and ...

Potentially? I'm not an expert by any means but you could theoretically make your own shaders that decrypt arbitrary mesh data before drawing it. You can store encryped data in a compute buffer and decrypt it in your shader when it draws. People use this approach with unencrypted data already https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html

However I can't speak to whether people could just grab the unencrypted mesh regardless after it's been unencryped by your shader. And you'd be paying a performance cost for unencrypting the data on the fly. AND you'd be re-implementing a ton of stuff that Unity takes care of for you. Essentially building your own render pipeline

torn rose
tired fog
#

I want to create a custom graph view, are there any good tutorials/docs to create one? I've found some youtube tutorials, but I would prefer a readable tutorial

bleak citrus
#

i am also interested in this

#

i looked into it briefly and my brain fell out

#

(and i desperately do not want to watch a 4 hour video tutorial)

subtle river
tired fog
fallow echo
#

You can use some asset that does graph views. Otherwise it's somewhat annoying. I aaaalmost have an asset that does it... but I'd say it's not prod ready yet πŸ˜… so you can use something like xNode or 2-3 other ones. There are decent free ones, I think.

lofty solstice
#

Creating your own isn't that complicated depending on your requirements. I suggest following YouTube videos, though, as they usually explain more than written articles. They usually include a GitHub repo too

#

That said, making a graphview and understanding all of its workings will take time (more than 2 hours lol) so if those YT videos are too long for you, maybe just pick up an asset

carmine hinge
#

not much you can do

#

(coming from a professional unity game modder with slight unreal experience too)

#

renderdoc also exists too

brisk pasture
#

RenderDoc or like NSight can be used to get anything once its on the gpu

untold moth
#

Imagine Nintendo face if there was a fail proof method of preventing piracy and asset stealing.

sturdy comet
#

Is it possible to disable a list of components through script? And I don't mean Behaviors and yes I'm aware of GetComponent<>().enable....what I mean is: List<Component> components; and disable all of them

thin mesa
#

Component does not have an enabled property. your list would need to contain Behaviour or its derived types

brisk pasture
#

just with a loop

#

loop over the components set enabled on each one

brisk pasture
#

what do you mean no, to act on the whole lot of them you need to loop it, and after that its just making sure the type is correct

#

Behaviour is the first type after Component that can be enabled or disabled

sturdy comet
brisk pasture
#

the list needs to be of Behaviour not Component

sturdy comet
brisk pasture
#

or if it must be of type Component in the loop you will need to do a if (cmp is Behavior b) {} or something similar

#

Collider implements its own enabled bool

#

would have to get a list if Component, then check if something is a collider then set enabled

#

Collider seems to be one of the few edge cases

#

so could do the loop over a list of Component
have a check for Behaviour if (cmp is Behavior b) {}
then have a check for collider if (cmp is Collider c) {}

bleak citrus
#

Renderer is another case

brisk pasture
#

ugh, thats annoying

brisk pasture
sturdy comet
untold moth
#

Maybe just deactivate the desired gameObjects instead of trying to break the system.

north tundra
#

This is more of a general C# question, but I have a base class (Neuron) wherein there's a method (NeuronFunction, will always take in a float and return a float) that, depending on the neuron instance's ID value, should do different things. For example, if I create a new Neuron and set its ID to 3, then I want NeuronFunction to do some specific thing based on what I hardcoded into that ID.

#

Is this a situation where I use delegates? I've been trying to do that but they don't seem to be fine-tuned for this kind of use.

#

I'm trying to accomplish this in this specific way because it'll be easier than manually making a bunch of classes that inherit from Neuron - I want to be able to basically create one unique Neuron in a target organism for every single unique neuron type that can exist, which I'm setting now to 255 so that I have room to add more types for the forseeable future.

untold moth
regal lava
#

int, delegate dictionary

#

[0] = > method1();
[1] = > method2();

flint sage
#

Sure dictionaries work, but that sounds like a pain to manage, where derived types are a lot easier to handle...

terse inlet
# north tundra This is more of a general C# question, but I have a base class (Neuron) wherein ...

I would use composition... Let Neuron be a class, and let it be composed of other classes that contain the functionality...

public class Neuron
{
    private NeuronFunctionality _functionality;

    public static Nueron Factory(int id)
    {
        var instance = new Nueron(){
            _functionality = GetFunctionalityFor(id);
        }
    } 
}

Something like this that allows you to add functionality as you develop, you can also make it give a default functionality for ids you havent gotten to yet. NeuronFunctionality could easily be an interface as well. Think lego bricks, and Nueron is the platform the lego bricks are connecting to

flint sage
#

If you only have one component, it's not really composition (and it's not really different from inheriting from Neuron)

terse inlet
#

Composition is using pieces inside an object rather then inheritance and overrides. It is a architecture difference that will pay dividends as the project progresses. Especially as they add more interactions inside the Nueron object. It is a significant difference in how you approach solving problems: inheritance vs composition

tired fog
tired fog
# lofty solstice That said, making a graphview and understanding all of its workings will take ti...

Indeed it takes more than two hours, but I was hoping to find at least a 10 minute video of a "this is exactly what you need to have it working" and then explore by myself what everything does. But after watching and following the first hour long video, and now having a graph view, it's actually just the basic straight up "this is what you need". There's barely any explanation which means I doubt I can find anything shorter as complete as that

#

It's cool tho, i also learnt how to use UI Toolkit a bit which I never used before

lofty solstice
#

@tired fog which one are you watching?

lone hare
#

I'm planning on turning an editor tool I use in my game into a unity package. I have looked into how to create and use asmdef and I think I understand most of it however there are some concerns that I have.

The first of which is if unity will let me know if I'm trying to use code that I haven't added a reference to? for example I use ImGui to render my tool in play, do I need to add this reference to the asmdef of my package or no?

The second one which is a bit more annoying, currently I have the tool together will all the other code in my game so it compiles to Assembly-CSharp.dll and in the tool I get the active assembly and look for a specific attribute on classes, methods and fields and process them.
This works fine since they all are in the same assembly but when I turn it into a package it gets a bit more difficult cus I want to look for the classes, methods and fields of the asset scripts and not only on my own package code. Is this possible and if so how can I do it?

upbeat path
# lone hare I'm planning on turning an editor tool I use in my game into a unity package. I ...

Pretty sure you have to specify all dependencies that your asmdef has otherwise it wont compile.
To get an array of loaded assemblies use
https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.getassemblies?view=net-8.0
Then you can loop through to find Assembly-CSharp and run your code as normal

Gets the assemblies that have been loaded into the execution context of this application domain.

tired fog
# lofty solstice <@340856284259549184> which one are you watching?

This video is an hour long epic into how to create behaviour trees using ui builder, graph view, and scriptable objects. UI Builder accelerates editor tool development by visual drag and drop editing. Scriptable objects are used for serialisation, and graph view is the same node graph backing used by shader graph.

Project files available here!
...

β–Ά Play video
lofty solstice
#

@tired fog

tired fog
#

Hahahah

tired fog
# lofty solstice It's been a while so I don't fully remember, but I used this at the start. Very ...

Yeah, so I'm actually thinking there are only three channels with info. I started looking at this one https://www.youtube.com/watch?v=7KHGH0fPL84, and after a bit I found out that it was missing the last video (and the most important) so after that I found the playlist that you sent, and continued following that one. It seems that that playlist comes from a guy that watched the video I sent and found that it was unfinished and continued working on it. Which is nice, but after a bit I felt like it was teaching and adding a lot of code very specific to a dialogue system and polishing it (which I wasn't interested) so i ended up finding the KiwiCode video, which is nice because it's building the graph view on top of a very barebones SO structure, also it's newer, and overall simpler

In this tutorial we are going to create a SUPER SIMPLE node based dialogue system with the ability to branch story lines. We gonna create the main setup and make our graph entirely functional in this episode.

In the next episode, we gonna add save&load system for nodes and game play implementation.
This tutorial will help you to build your bran...

β–Ά Play video
lofty solstice
#

Fair, I just wanted to share the bit-sized videos in case you hadn't found them yet! It is indeed tailored to a dialog tool but there's some stuff that's universal, of course

tired fog
#

Of course! Thank you for it, if it's not for me surely someone else will find it useful!

frigid smelt
#

how can i make the player can pick all of object in my game without add any public float on my script?

tired fog
#

Or do you want to hide the floatsΒΏ

frigid smelt
#

should my script have all public float to input the pickable object?

tired fog
#

I don't understand still, but you might be better asking in #πŸ’»β”ƒcode-beginner , if it's not your code (tutorial) then I would suggest watching it again to understand it better, otherwise unless you are starting, you should be able to know what and how to change.

tired fog
# frigid smelt should my script have all public float to input the pickable object?

But to answer, you don't need to have the variables public unless they are being used by other components. You can change public to private, if you want to still be able to modify the float in the editor you can add the attribute [SerializeField]. If the problem is more related to the code itself then I should ask you, what are you trying to solve? What's the initial problem?

frigid smelt
#

i want to make my code more efficient,
I want to create an object that can be picked up like in this picture without having to add a public float, just by adding a pickable script to the desired object

tired fog
#

Removing the public float doesn't make it more efficient, but if you mean that you want to build a system to pick any object that has a pickable script there are mutliple wasy to do so, you can add a script that adds itself to a list on the player, or make a method that finds all the objects with that script, or play with on trigger Enter on trigger Exit to update the list of available objects and then check with raycast or directly the distance to the object, if it's within range pick it up, otherwise dont.

#

But you still haven't answered my question, what are you trying to accomplish? Making the code more efficent is not related at all to a float, are you having performance issues? If so might be better to share the code that you are working with

frigid smelt
frigid smelt
thorn flintBOT
thorn flintBOT
frigid smelt
#

what bro?

#

there is empty on the link

#

i think u must

// Your code here

type like that bro

wild bane
frigid smelt
#
using System.Collections;
using UnityEngine;

public class CarryObject : MonoBehaviour
{

    public GameObject pickAbleObj;
    ArrayList pickableObj = new ArrayList();
    public Transform handPlayer;

    public float range = 2f;

    public GameObject pickUpButton;
    public GameObject dropButton;

    private void Update()
    {
        CheckForPickableObject();
    }

    public void CheckForPickableObject()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit, range))
        {
            // Memastikan bahwa objek yang terkena adalah objek yang bisa diambil
            if (hit.collider.gameObject == pickAbleObj)
            {
                pickUpButton.SetActive(true);
            }
            else
            {
                pickUpButton.SetActive(false);
            }
        }
        else
        {
            pickUpButton.SetActive(false);
        }
    }

    public void PickUpObject()
    {
        if (pickAbleObj != null)
        {
            pickAbleObj.transform.position = handPlayer.position;
            pickAbleObj.transform.SetParent(handPlayer);
            pickUpButton.SetActive(false);
            dropButton.SetActive(true);
        }
    }

    public void DropObject()
    {
        // Memastikan ada objek yang dipegang sebelum mencoba melepaskannya
        if (handPlayer.childCount > 0)
        {
            pickAbleObj.transform.SetParent(null);
            dropButton.SetActive(false);
        }
    }
}

humble leaf
# frigid smelt ```cs using System.Collections; using UnityEngine; public class CarryObject : M...

This is a #πŸ’»β”ƒcode-beginner question. You can move over there.

If you want to find all the objects that you can pick up, use an OverlapSphere:
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html

If there is at least one collider in the array, you know there is something nearby to pickup, and therefore, you can show the prompt. When the player uses the prompt, you can just sort the objects by distance and pick them up one by one.

frigid smelt
#

oke bro

steady oracle
#

hello. i am looking to start multiple timers for a game. these timers call a callback at the elapsed event, and i want to bind additional variables to the function being called. these variables need to also be passed by value. not by reference. the reason is that i am initiating all the timers from a for loop, which means i have the desired bind be dependent on i. but when these functions get called, they are all getting called with the last value of i, not the one that was assigned to them initially

sly grove
steady oracle
#

temp?

tiny pewter
#

not code advance
you have to capture the variable

sly grove
# steady oracle temp?
for (int i = 0; i < n; i++) {
  int temp = i;
  mything.AddListener(() => DoSomething(temp));
}```
steady oracle
#

i see

#

makes sense

sly grove
#

If you use i directly, it's by reference

#

it's always by reference

#

but this creates a different variable to reference which won't change

tiny pewter
#

compiler wont do it for you, or make a custom struct that capture data yourself

steady oracle
sly grove
#

there's no way to capture by value

steady oracle
#

alright

sly grove
#

variable capture is always by reference

steady oracle
#

but that temp soltion would work?

sly grove
#

yes

steady oracle
#

alright appreriate it

#

it works. thanks man

#

i was going down some weird rabbit holes for a while there

tiny pewter
#
public struct DataHolder{
  int i;
  public TheMethod();//here you use i
}
```then
```cs
event+=DataHolder.TheMethod
```basically how your c# code work and what you get after decompilation
sly grove
wary bobcat
#

(I would think cross-scene communication goes here, but okay, thanks)

steady oracle
#

another question. i am using a spline animate on my enemies that i am looking to spawn. the problem is that it appears i cannot set the spline container of the spline animate at runtime. how would i do this?

#

nvm i solved it. i need to change the variable named "container" not "spline container"

hybrid belfry
#

Is there a way I can use a property to access an array like so:

sly grove
#

(not static though)

tired fog
#

So im continuing my work to generate a graph view

#

A problem I've found is that, each node needs a node view, to set up it's content. The problem is making those nodeviews out of a single node scriptable object. I have two options in mind. A factory, that returns the objects (whcih doesnt feel right) or a custom property (similar to the [CustomPropertyDrawer(type)[

#

How can I build on the second?

lofty solstice
#

You mean a custom attribute on your node SO class? Or am I misunderstanding?

tired fog
#

Indeed, but I managed to do it! Got the attributes working

#

How could I simplfy this two pieces of code so that there's no repeated code?

public Type GetNodeViewType(Type type){
    var types = TypeCache.GetTypesDerivedFrom(typeof(NodeView)).ToList();
    foreach(Type foundTypes in types){
        Attribute[] attrs = Attribute.GetCustomAttributes(foundTypes);
        foreach(Attribute attribute in attrs){
            if(attribute is CustomNodeViewAttribute customNode){
                if(customNode.target.IsEquivalentTo(type))
                    return foundTypes;
            }
        }
    }
    return null;
}

public CustomNodeViewAttribute GetNodeAttribute(Type type){
    var types = TypeCache.GetTypesDerivedFrom(typeof(NodeView)).ToList();
    foreach(Type foundTypes in types){
        Attribute[] attrs = Attribute.GetCustomAttributes(foundTypes);
        foreach(Attribute attribute in attrs){
            if(attribute is CustomNodeViewAttribute customNode){
                if(customNode.target.IsEquivalentTo(type))
                    return customNode;
            }
        }
    }
    return null;
}
sly grove
#

What's the difference?

#

oh just the return value

tired fog
#

The first one returns the foundtype, which is the type where there is the right attribute, the second one returns the right attribute

tired fog
#

i dont' see a way to return one or the other without having to do another check as that one

long ivy
#

the most simple solution would be two out parameters imo, and just discard whichever thing you don't care about on the caller side

#

(merge both of those into one method)

sly grove
#

so yeah I'd agree with returning both (either in a struct or with out params)

#

then you could create wrappers if you want that just return one.

tired fog
#

i guess then this ?

public Type GetNodeViewType(Type type, out CustomNodeViewAttribute attributeInNode){
    var types = TypeCache.GetTypesDerivedFrom(typeof(NodeView)).ToList();
    foreach(Type foundTypes in types){
        Attribute[] attrs = Attribute.GetCustomAttributes(foundTypes);
        foreach(Attribute attribute in attrs){
            if(attribute is CustomNodeViewAttribute customNode){
                if(customNode.target.IsEquivalentTo(type)){
                    attributeInNode = customNode;
                    return foundTypes;
                }
            }
        }
    }
    attributeInNode = null;
    return null;
}
sly grove
#

sure that's one way.

tired fog
#

alright

#

settled with this

Type GetNodeViewType(Type type){
    GetNodeAndAttributeViewType(type, out Type nodeType, out CustomNodeViewAttribute attribute);
    return nodeType;
}

CustomNodeViewAttribute GetNodeAttribute(Type type){
    GetNodeAndAttributeViewType(type, out Type nodeType, out CustomNodeViewAttribute attribute);
    return attribute;
}

public void GetNodeAndAttributeViewType(Type type, out Type nodeType, out CustomNodeViewAttribute attributeInNode){
    var types = TypeCache.GetTypesDerivedFrom(typeof(NodeView)).ToList();
    foreach(Type foundTypes in types){
        Attribute[] attrs = Attribute.GetCustomAttributes(foundTypes);
        foreach(Attribute attribute in attrs){
            if(attribute is CustomNodeViewAttribute customNode){
                if(customNode.target.IsEquivalentTo(type)){
                    attributeInNode = customNode;
                    nodeType = foundTypes;
                    return;
                }
            }
        }
    }
    attributeInNode = null;
    nodeType = null;
    return;
}
#

thanks!

pastel finch
#

I have a server running for my game, and I have a shared service definition file to build the client in Unity. Is there a recomended way to share this file?

lofty solstice
twilit narwhal
#

Hi, I'm a beginner unity coder, but I figure the question im asking is advanced.

How do I create cutscenes in unity? The reason I'm asking is because I want to make a shark game for one of my classes, and basically I want a cutscene of the shark seeing its entire family getting hunted by humans at the start.

#

Any help would be great

untold moth
twilit narwhal
untold moth
half swan
twilit narwhal
timber shadow
#

Is there a asset post processor type which has a callback that works for Scriptable Objects?

#

AssetPostprocessor's API doesn't mention anything which seems to fit.

#

I suppose OnPostProcessAllAssets will have to do it for me.

full tendon
#

hey guys. I need your help on this I been trying to fix this for a while but I'm making my camera manager to follow my polygon collider with in the border but I got a issue with it as some parts of my stage my camera needs to be a little higher. while the camera manager gets the min x and y position of the border it doesn't get the one closet to it if I were to add more then 4 points.

#

here how it should work

#

and here what happens when I add one point lower while far from the player

#

the point in the bottom is the minuamal point in y and the ones in red are the ones that need to be the main focus when the player is on that border

#
private void HandleClamp()
    {
        transform.position = ClampToStageBounds(transform.position);
        scroller.position = ClampToStageBounds(scroller.position);
    }

    private Vector3 ClampToStageBounds(Vector3 position)
    {
        Bounds stageBounds = stageCollider.bounds;


        position.x = Mathf.Max(position.x, stageBounds.min.x - (frustumWidth * 0.5f));
        position.x = Mathf.Min(position.x, stageBounds.max.x + (frustumWidth * 0.5f));
        position.y = Mathf.Max(position.y, stageBounds.min.y - (frustumHeight * 0.5f));
        position.y = Mathf.Min(position.y, stageBounds.max.x + (frustumHeight * 0.5f));

        return position;
    }```
long ivy
#

Your solution seems way too simple for what you're trying to do with it. What are you actually using for your stage bounds? If it's a polygon collider, it might be better to find the nearest bottom two points on the left and right side of the camera on that collider if you want to try and salvage your existing code

#

otherwise, maybe it makes sense to use a spline to control the lowest camera position, and then choose the max of that and some character-centered-ish value so the camera never sees too far below the map surface

full tendon
#

yes its a polygon collider

long ivy
#

no, you're using the collider bounds which is an AABB, so your code is looking at these values

full tendon
#

So what would I have to do?

long ivy
full tendon
#

Mhh seems tricky. I’ll try tomorrow. I’m wasted in all the shader code i did today

#

Ok I see what you mean

edgy walrus
#

i need some help with understanding and making changes in the template from unity asset store, can anyone help me with that?

untold moth
frigid smelt
#

yes ofc

terse inlet
# tired fog How could I simplfy this two pieces of code so that there's no repeated code? ``...

@tired fog I would create a struct to hold your return values, and clean up your exit/continue conditions in your loop. I highly recommend inversing your stay conditions into exit conditions. It cleans up the readability and makes following the logic easier across all code

public bool TryGetNodeAttributeInfoForType(Type type, out NodeAttributeInfo info)
{
    info = default(NodeAttributeInfo);
    var types = TypeCache.GetTypesDerivedFrom(typeof(NodeView)).ToList();
    foreach (Type foundTypes in types)
    {
        Attribute[] attrs = Attribute.GetCustomAttributes(foundTypes);
        foreach (Attribute attribute in attrs)
        {
            if (attribute is not CustomNodeViewAttribute customNode) { continue;  }
            if (customNode.target.IsEquivalentTo(type) == false) { continue; } 

            info = new NodeAttributeInfo() 
            {
                attachedToType = foundTypes,
                attribute= customNode,
            };
            return true;
        }
    }
    return false;
}

public struct NodeAttributeInfo 
{
    public Type attachedToType;
    public CustomNodeViewAttribute attribute;
}
tired fog
#

What's the way to create the extensionContainer in a graph view node?

#

For example, the main node has a struct with many parameters

#

I want to create a field for each value of that struct so you can modify it on the node

#

I started by doing something like this

protected override VisualElement CreateParameters()
{
    NoiseNode node = this.node as NoiseNode;
    VisualElement parameters = new VisualElement();
    NoiseSettings settings = node.settings;
    EnumField noiseType = new EnumField(){
        label = "Noise",
        value = settings.noiseType,
    };
    
    FloatField scale = new FloatField(){
        label = "Scale",
        value = settings.scale
    };

    parameters.Add(noiseType);
    parameters.Add(scale);

    return parameters;
}

the returned visual element is added to the extensioncontainer

#

But I have two problems:
1- I need to manually map each value to a field in a large struct, is there a faster way to do that?
2- How do I actually make the enum work?

#

Is it better to use the UI Toolkit with the editor or code it like this? Im confused

soft marlin
# tired fog How could I simplfy this two pieces of code so that there's no repeated code? ``...

I know this isn't your current question, but I was scrolling up to get some context and I have some ideas on this point. first off seems like the perfect fit for generics, also I think linq read better, but that doesn't matter as much.

public T GetNodeInfo<T>(Type targetType) where T : class
{
    return TypeCache.GetTypesDerivedFrom<NodeView>()
        .SelectMany(type => Attribute.GetCustomAttributes(type)
            .Where(attr => attr is CustomNodeViewAttribute customNode && customNode.target.IsEquivalentTo(targetType))
            .Select(attr =>
            {
                if (typeof(T).IsAssignableFrom(attr.GetType()))
                {
                    return attr as T;
                }
                return null;
            }))
        .FirstOrDefault(result => result != null);
}

then use:
Type nodeViewType = GetNodeInfo<Type>(someType);
CustomNodeViewAttribute nodeViewAttribute = GetNodeInfo<CustomNodeViewAttribute>(someType);

or for any other type you might need

sly grove
#

once you get used to how to bind elements to variables in code it becomes a better workflow than manually coding the UI, IMO.

tired fog
tired fog
#

Mmm, i see

#

I hate magic strings, but might take a look at it

untold moth
plain abyss
untold moth
shrewd vale
# full tendon

is this a open project, how many levels are there, are they humanoid can characters be selected ?

full tendon
# shrewd vale is this a open project, how many levels are there, are they humanoid can charact...

No this is not a open sourced project. The original code was not made by me and it was made by the owner of freedom engine. I tired contacting him to see if its ok to make this open source but I couldn’t get reach of him. There is only the green hills act 1 at the moment which you can see it still wip. While sonic is the only one in the game. I plan to bring in tails, knucks, amy, and possibly trip. Most likely the case I will also add modern sonic and shadow

#

But I pretty much overhaul all the scripts expect the physics because there no need to fix the physics. It’s really great

#

Here the link to the engine

#

Though I’ll add it open source soon and add credit to the original source. @shrewd vale If anything I’ll send a link once it open source

tired fog
#

Hi, continuing my progres with graph view, two questions:
1- How can I set a value (float field, or integerfield) to have a min , max value?
2- How can I update the node once one of the parameters changes? I though that adding RefreshExpandedState() inside register valuechanged callback woudl work, but it doesnt

little cosmos
#

Hello, can someone help me with async file loading?
I have a song loading system, which is just a for loop calling song load coroutines, where I grab the song using www.GetAudioClip from disk.
The problem is that the game freezes until everything is loaded.
Is it possible to load files from the thread pool? I tried to use UniTask and its thread pool, but it said that UnityWebRequest is part of unity API and I have to call it from the main thread.

sly grove
#
  1. UWR/WWW themselves should definitely be happening in a bg thread automatically
#

so i suspect something is off with your code

compact ingot
little cosmos
# sly grove so i suspect something is off with your code

I don't see anything wrong, but I can show

    private void LoadBeatmaps(string[] beatmapFolders){
        beatmapsTotal = beatmapFolders.Length;
        if(DataKeeper.instance.beatmaps.Count == 0){
            beatmaps = new List<Beatmap>();
            for(int i = 0; i < beatmapFolders.Length; i++){
                string beatmapFolder = beatmapFolders[i];
                string beatmapJSONPath = Path.Combine(beatmapFolder, "beatmap.json");
                if(File.Exists(beatmapJSONPath)){
                    // level loading
                    StartCoroutine(ImportSong(beatmap.songFolderName, beatmap));
                    beatmaps.Add(beatmap);
                }
                else{
                    Debug.LogWarning("Invalid beatmap folder: " + beatmapFolder + " (beatmap.json not found)");
                }
            }
            DataKeeper.instance.beatmaps = beatmaps;
        }
        else{
            beatmaps = DataKeeper.instance.beatmaps;
            songsImported = beatmaps.Count;
        }
        beatmapsLoaded = true;
        DisplayBeatmaps();
    }
    IEnumerator ImportSong(string folderName, Beatmap beatmap)
    {
        bool audioFound = false;
        foreach (string extension in validAudioExtensions)
        {
            string fullPath = Path.Combine(directoryPath, "Beatmaps", folderName, "song" + extension);
            if (File.Exists(fullPath))
            {
                audioFound = true;
                string url = "file://"+fullPath;
                WWW www = new WWW(url);
                yield return www;
                beatmap.song = www.GetAudioClip();
                songsImported++;
                break;
            }
        }
        if(!audioFound){
            Debug.LogWarning("Audio file not found for beatmap: " + folderName);
            songsImported++;
        }
    }

I tried UnityWebRequests, but the result was exactly the same

hardy jacinth
#

is there a way to see what is causing shader to fail and fallback to one defined in the Fallback "..." (in .shader file)?

tired fog
dusty wigeon
tired fog
#

How should I do it?

dusty wigeon
#

Using a constructor ?

tired fog
#

So for example, I have a class that has the field lacunarity, ideally i want to automatically show that field on the node, but unless i make that (with a custom node view) i don't see an easier option. My alternative was to add attributues to each field and use reflection to get the types and somehow bind them together

dusty wigeon
#

No idea what you are talking about. I am just talking about clean code.

tired fog
#

Ah lol

dusty wigeon
#

Ideally, you do not want to use pattern the way you are doing it now.

tired fog
#

This is related to graph views and the way UI toolkit is setup

dusty wigeon
#

You asked if it was a good way to make something. I simply stated that it is not for the given reason.

tired fog
#

Yeah, im just saying that the message has context

dusty wigeon
#

Create a factory or wrapped it.

#

Alteranatively, look into if there is not already factory or constructor for the field.

full tendon
long ivy
#

post your updated code. But you should be looking for (at least) two points, same as your original snippet so hopefully that's a typo

full tendon
#
private Vector3 ClampToStageBounds(Vector3 position)
    {
        // Find the closest point on the collider to the camera's position
        Vector2 closestPoint = stageCollider.ClosestPoint(position);

        // Clamp camera position based on the closest point and frustum size
        position.x = Mathf.Clamp(position.x, closestPoint.min.x + paddingX, closestPoint.max.x - paddingX);
        position.y = Mathf.Clamp(position.y, closestPoint.min.y + paddingY, closestPoint.max.y - paddingY);

        return position;
    }```
long ivy
#

so you're not looking for the two points any more. How exactly do you want the camera to behave? If you just want to use the center point, you will probably need to tweak position so you're not inside the collider because that will give wrong results

full tendon
#

Let me look back on my orginal

#

yea no clue what I'm doing wrong

#

here the modified but original script before that one

#
    {
        Bounds stageBounds = stageCollider.bounds;//Get the stage bounds
        Vector2 closestPoint = stageCollider.ClosestPoint(position); // Get the closet point

        //Problem need to find two of the cloests y points and two of the cloest x points

        position.x = Mathf.Max(position.x, closestPoint.x - (frustumWidth * padding));
        position.x = Mathf.Min(position.x, closestPoint.x + (frustumWidth * padding));
        position.y = Mathf.Max(position.y, closestPoint.y - (frustumHeight * padding));
        position.y = Mathf.Min(position.y, closestPoint.y + (frustumHeight * padding));

        return position;
    }```
#
    {
        Bounds stageBounds = stageCollider.bounds;//Get the stage bounds
        Vector2 closestPoint = stageCollider.ClosestPoint(position); // Get the closet point

        //Problem need to find two of the cloests y points and two of the cloest x points

        position.x = Mathf.Max(position.x, closestPoint.x - (frustumWidth * padding));
        position.x = Mathf.Min(position.x, closestPoint.x + (frustumWidth * padding));
        position.y = Mathf.Max(position.y, closestPoint.y - (frustumHeight * padding));
        position.y = Mathf.Min(position.y, closestPoint.y + (frustumHeight * padding));

        return position;
    }```
#

I think I see what my code is doing its getting the position of my closet point and its making the camera mid point go look stright on it

long ivy
#

yes, because you are probably feeding it the camera position which is already on the polygon collider, which returns the input point as the docs say

full tendon
#

So what would I need to do here as the camera has its own controls over the player

long ivy
#

make sure you are checking a point that's outside your collider. If you want the exact point, maybe it would be better to just raycast (from outside the collider) from some point below the camera towards camera center

#

I still think this is janky though, and a spline makes much more sense to me

full tendon
long ivy
#

how so? which bounds?

full tendon
#

the bounds that I'm working on

#

how would a spline work nsimiler to what I want

long ivy
#

it would define the lowest point your camera can see. You can combine it with code to limit the height, and more code to prevent it from going out of bounds left or right. I'm not sure what the issue is?

full tendon
#

There are parts of the map that the bounds are lower and when the bounds are higher

#

While thats not the issue. Big issue is when the camera is far from the bounds sonic would be in the middle of the screen

#

Well i will try

long ivy
#

I still don't understand. So if sonic is high enough, he should be offscreen? I thought you didn't want the camera to see below the map

full tendon
#

But what im trying to do is in some parts of the map the camera is higher to show sonic below the screen and after that if he not close to the death area or the bottom bounds he will stay in the middle

full tendon
# full tendon

This is the example. And the bottom is what I don’t want

full tendon
#

@long ivy Sorry to bother once more but do you think it be better to restick a border by a object. Like a wall or something invisable?

long ivy
#

restrict? If you're talking about the camera I'd say no, otherwise sure some kind of invisible collider is fine

full tendon
#

like it won't allow the camera to go passed this collider

long ivy
#

well now you'll have to come up with a way for the camera to interact with the collider, so unless the edges of your world are weirdly-shaped this seems like a strange design

full tendon
#

well might as well overhaul the camera system. I'm really starting to not like the code

#

now if you were to use spline. how would it follow the player while the spline just keeps track of where no to go?|

long ivy
#

? Camera follows player. Limit min y of camera pos based on spline. Simple as that

full tendon
#

ok I guess thats really it then

full tendon
#

@long ivy I'm sorry to bother you once more but I need to ask if you you now the method needed to find the closet point to the player

full tendon
#

Yes I want to evaulate based on t

#

but it will be based on player position

#

seems the function don't exist in my version

#

ok that werid.i see the version is right but the function is not there

full tendon
#

we good

#

Its a splineutility

#

I do have one issue

#

SplineUtility.GetNearestPoint(spline, ray, out float nearestPoint, out float t); out float nearestPoint is a error. ```Severity Code Description Project File Line Suppression State
Error CS1503 Argument 3: cannot convert from 'out float' to 'out Unity.Mathematics.float3' Assembly-CSharp F:\Game Develoment - Projects\Externalgrade\Sonic The Hedgehog\Assets\Game Mechanics\Sonic Scripts\PlayerCamera.cs 130 Active

long ivy
#

yes? fix your syntax error

full tendon
#

wrong error messgae

#
Error    CS0311    The type 'UnityEngine.Splines.SplineContainer' cannot be used as type parameter 'T' in the generic type or method 'SplineUtility.GetNearestPoint<T>(T, Ray, out float3, out float, int, int)'. There is no implicit reference conversion from 'UnityEngine.Splines.SplineContainer' to 'UnityEngine.Splines.ISpline'.    Assembly-CSharp    F:\Game Develoment - Projects\Externalgrade\Sonic The Hedgehog\Assets\Game Mechanics\Sonic Scripts\PlayerCamera.cs    130    Active
long ivy
#

still a syntax error. You need to provide a spline, not a spline container

full tendon
#

ops

brisk pasture
#

T needs to be a type that implements ISpline

full tendon
#

I didn't realize i put the container

full tendon
#

So................. about my situation I was able to solve my problem by seeing if cinemachine would work in a 3d space and use the confiner 2D.......... And I worked

cinder dirge
#

hi guys

#

my vscode dont recognise all of my folder in unity . there are some files doesnt show in Solution Explore(in vsc) and some scripts inside it are misscellaneous

sly grove
paper moth
terse inlet
#

@paper moth
unsure why you are copying the array back to itself here.
spawnPositions[i] = spawnEnemyJob._spawnPositions[i];
Also you should setup the nativearrays to dispose with the job handle.

In a best case you dont call complete right away, better would be to (per frame) get results and act on them, and schedule a new job, that you pick the results up on next frame. Also I would ensure that you have sufficient enemies that using the job system is actually faster. It has its own overhead.

The code looks functional. I would change from a list to an array and figure out a smart way to handle that. That ToArray call will cause GC to run often with a large list

long ivy
#

how many enemies are there? I'd be shocked if this is outperforming the non-job version unless there are thousands

paper moth
# terse inlet <@136830391079272448> unsure why you are copying the array back to itself here....

you are absolutely correct. this line of code is unnecessary..

spawnPositions[i] = spawnEnemyJob._spawnPositions[i];

"Also you should setup the nativearrays to dispose with the job handle." Can you explain that a little bit more please? If i dispose right after the job handle i can't use it here or am i wrong?

 GameObject enemy = objectPooler.SpawnFromPool("Enemies", spawnEnemyJob._spawnPositions[i]);

"In a best case you dont call complete right away, better would be to (per frame) get results and act on them, and schedule a new job, that you pick the results up on next frame. Also I would ensure that you have sufficient enemies that using the job system is actually faster. It has its own overhead. " - the thing is i have between 1 and 20.000 enemies.. at the moment it seems to be working fine even with 20k enemies.. but those enemies are just 2D sprites without any animation, or collision detection or smth like that..

The next thing i want to implement is a check if they are close to another enemy and push it away.. i think i have to use smth like spatial partioning or smth like that - or is there a common way to do smth like that?

i will try to change the list to an array that's a good hint thanks..

long ivy
#

what's your frame rate like? There are a lot of little inefficiencies here, but the one that is probably tanking you the most is creating a TransformAccessArray every frame for 10-20k transforms

paper moth
#

is this too low? πŸ˜„

long ivy
#

for a bursted job, it's low. For your implementation, it's much higher than I would have thought tbh

gritty lagoon
#

Hi, does someone know how to play the audio data from one audio source to another (or multiple other) audio source(s)?

sly grove
#

There's also AudioSource.PlayClipAtPoint

gritty lagoon
#

yea but i need it to work for 'live' clips

#

so for audio where i don't have the audio clip file

sly grove
#

everything I said still applies

#

You will need to create an AudioClip regardless (that doesn't need you need a "file" per se)

gritty lagoon
#

is it then just as simple as doing targetAudioSource.clip = sourceAudioSource.clip?

sly grove
#

yea

#

or targetAudioSource.PlayOneShot(source.clip);

gritty lagoon
#

what does playoneshot mean

sly grove
#

Or AudioSource.PlayClipAtPoint(source.clip, position);

gritty lagoon
#

what if the source audio source's clip is looped?

sly grove
#

that's part of the source

craggy sandal
#

Hey guys , im having a problem with a simple "Get parent" function that somehow gives me an error.

I have a mapgenerator that spawns planets and starsystems , and that planet has a Starsystem "Parent" and when i call the "GetParent" function , i get a null reference error.

The planet in the inspector has the parent and when i assign the parentsystem in the generator , it gives me no error. I do not touch the parent system in any scripts except the one giving me the error.
Everything looks fine , and ive ran out of ideas.

#

Generator script - not giving any errors

#

Error on Planet.getparentsystem

sly grove
#

or is it printing "Planet is null"?

stuck plinth
#

i think you need to show the code in GetParentSystem too

sly grove
sly grove
#

the logs are all out of order

craggy sandal
sly grove
#

but on the one you're trying to read in the code it is

#

or it's being set to null in the code

#

why not print the name of the parent that has the null system?

craggy sandal
#

I am not touching "Parent system" in any code except set and get , and the set is only from the generator , and the Get is from all the debugging

sly grove
tiny pewter
#

Debug.log has a overload that takes second parameter
also consider log when setting parent system
and learn c# property

sly grove
#

other than the one you showed

craggy sandal
#

I checked all planets , they are all set

sly grove
sly grove
#

you don't need to check them all

craggy sandal
#

Let me do that quickly hold on

stuck plinth
#

when does the generator run? is it during the game or an editor tool?

modest canopy
#

using Epic.OnlineServices.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace EpicTransport {
public static class Logger {

    public static void EpicDebugLog(LogMessage message) {
        switch (message.Level) {
            case LogLevel.Info:
                Debug.Log($"Epic Manager: Category - {message.Category} Message - {message.Message}");
                break;
            case LogLevel.Error:
                Debug.LogError($"Epic Manager: Category - {message.Category} Message - {message.Message}");
                break;
            case LogLevel.Warning:
                Debug.LogWarning($"Epic Manager: Category - {message.Category} Message - {message.Message}");
                break;
            case LogLevel.Fatal:
                Debug.LogException(new Exception($"Epic Manager: Category - {message.Category} Message - {message.Message}"));
                break;
            default:
                Debug.Log($"Epic Manager: Unknown log processing. Category - {message.Category} Message - {message.Message}");
                break;
        }
    }
}

}
i cant access to my backend how do i fix this?

thorn flintBOT
craggy sandal
#

I think i found the issue

#

One planet didnt have a parent. Jesus im dumb.
I ran the "Do all planets have parents" code before i spawned a pre-set planet aka the starter planet

#

My bad guys, thanks for the help ❀️

modest canopy
tiny pewter
#

read the bot message

sly grove
ashen yoke
#

Hi if you have a load of 2d points and a list of walls/lines connecting them. Is there an algorithm to search out the enclosed spaces or rooms? I can do brute force but thinking there might be a known algorithm

tiny pewter
#

points=vertex
walls=edge
enclosed arae space=circle
so https://www.geeksforgeeks.org/print-all-the-cycles-in-an-undirected-graph/
basically run dfs and keep track of all vertices in current stack, once you meet some vertex in those vertices (through a hashtable) then you get a circle

dusty wigeon
ashen yoke
#

ok so graph theory - not my subject, but will look it up! I have a list of points (with ids) and a list of connections (id1, id2)

ashen yoke
#

I think the issue is it can find any loop including bigger than you want - if there are adjacent loops. I did a custom solution to check shortest loops, maybe I can balance between 2 for best option as mine was just a test and not optimised

tiny pewter
#

not
vertices set is unordered (without edge)

ashen yoke
#

so if I add to the example 9,14 and 14,3 I get out a big loop 14,9,5,6,4,3 instead of 14,9,5,3. Not sure I understand

tiny pewter
#

i didnt check the algorithm

ashen yoke
#

anyway recursive search marking what done should work in some form, you need to know the internal corners at junctions, otherwise you just get a long loop around multiple enclosed spaces

bleak citrus
#

If so, the problem gets significantly harder.

ashen yoke
bleak citrus
#

If there are no holes (so, no way to get from one side of an edge to the other without crossing another edge) and no overlaps (no two edges that touch anywhere but at a vertex), then yeah, I'd consider cycle-finding

#

I'm not sure how I'd avoid counting this as three rooms, though:

🟦🟦

Six vertices, seven edges

#

there are three cycles here: the left square, the right square, and the entire rectangle

ashen yoke
#

yes indeed - well the way I sorted that is extra info to know the clockwise connections at joints - so I can get the next edge around a corner in a clockwise manner. I made a working method but it is very ugly so will try and simply it down to something like graph theory example

craggy summit
#

A bit specific sorry, anyone using KCC knows is there is any way to prevent the KCC from pushing any rigidbody ? Setting RigidbodyInteractionType to None doesn't change anything.
Removing the line bodyHit.Rigidbody.AddForceAtPosition also doesn't change anything.

#

Increasing the mass of the receiving rigidbody also doesn't change a single thing. I can't figure out what actually causes them to be pushed around, and how to affect it.

sly grove
#

if you don't want the things to collide at all, set them up to ignore each other in the layer based collision matrix

#

or use the layer overrides on any of the Rigidbody or colliders

tiny pewter
craggy summit
#

My guess is that a non-kinematic rigidbody will always be pushed by a kinematic rigidbody, no matter their respective masses...

sly grove
#

you can move kinematic things

#

you just can't move them with forces

strange bane
#

anyway to create specific categories in memory profiler?
should only include heap allocated memory.
i was looking at telemetry but didn't see anything useful
smth like:

Pathfinding: 10 MB
Inventory: 100 MB
Combat: 20 MB

paper moth
long ivy
# paper moth would you mind teaching me a little how to do things better? Or give further hin...
  1. create your TAA once and add/remove to it as needed
  2. eliminate the ToArray as mentioned
  3. ideally the main thread sets up jobs and then does something else, for example starting job in Update and then finishing in LateUpdate, or completing on the next frame
  4. using a job to compute spawn positions is overkill since calculating sin/cos, even thousands of times, is nothing compared to instantiating thousands of GOs
  5. your move job has some inefficiencies: converting transform.position twice, accessing .localScale multiple times, using distance instead of squared distance, recomputing delta move (moveSpeed * dt) thousands of extra times
  6. if your enemies are simple and don't have any physics colliders as this code implies, you might consider eliminating them as GOs altogether which will let you use neat tricks to improve rendering performance (ex Graphics.RenderMeshInstanced) at the same time
tough flame
#

is there any way to play internet radio station with m3u extension in Unity? Tried this way but couldn't get past the "Attempting to download M3U file..." log in console..

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class RadioStationPlayer : MonoBehaviour
{
public AudioSource audioSource;

void Start()
{
    StartCoroutine(DownloadAndPlayFromM3U("https://radio.punkrockdemo.com/listen.m3u"));
}

IEnumerator DownloadAndPlayFromM3U(string m3uUrl)
{
    Debug.Log("Attempting to download M3U file...");
    using (UnityWebRequest www = UnityWebRequest.Get(m3uUrl))
    {
        yield return www.SendWebRequest();

        Debug.Log($"Response Code: {www.responseCode}");
        if (www.responseCode != 200)
        {
            Debug.LogError("Unexpected response code: " + www.responseCode);
        }

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"Failed to download M3U file: {www.error}");
        }
        else
        {
            Debug.Log("M3U file downloaded successfully.");
            string m3uContent = www.downloadHandler.text;
            Debug.Log($"M3U Content: \n{m3uContent}");
            string streamUrl = ExtractStreamUrl(m3uContent);

            if (!string.IsNullOrEmpty(streamUrl))
            {
                Debug.Log($"Found MP3 URL: {streamUrl}, starting playback...");
                StartCoroutine(PlayStream(streamUrl));
            }
            else
            {
                Debug.LogError("No valid stream URL found in M3U file.");
            }
        }
    }
}
#

IEnumerator PlayStream(string url)
{
Debug.Log($"Attempting to play stream from URL: {url}");
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
{
yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"Failed to play stream: {www.error}");
        }
        else
        {
            AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
            if (clip != null)
            {
                audioSource.clip = clip;
                audioSource.Play();
                Debug.Log("Streaming audio now playing.");
            }
            else
            {
                Debug.LogError("Failed to load audio clip from the stream.");
            }
        }
    }
}

string ExtractStreamUrl(string m3uContent)
{
    foreach (string line in m3uContent.Split('\n'))
    {
        if (!line.StartsWith("#") && !string.IsNullOrWhiteSpace(line))
        {
            return line.Trim();
        }
    }
    return null;
}

}

turbid tinsel
fickle obsidian
#

Am I nuts, or are materials as they relate to UI and the GUI system handled quite differently? Where you'd normally be able to instance a material/shared material and modify what you need, I'm seeing some light documentation on a few canvas specific interfaces like IMaterialModifier. Are these the workarounds/tools available to folks who are constrained to shader hell on the canvas renderer?

tough flame
# turbid tinsel it doesn't work because the download never ends. The file keeps getting larger a...

how could I than play it when it is not finished? Tried like this, doesn't work either:
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class RadioStationPlayer : MonoBehaviour
{
private string radioStationURL = "https://radio.punkrockdemo.com/"; // Ovdje stavite ispravan URL
AudioSource audioSource;

void Start()
{
    audioSource = gameObject.AddComponent<AudioSource>();
    StartCoroutine(DownloadAndPlay(radioStationURL));
}

IEnumerator DownloadAndPlay(string url)
{
    using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
    {
        ((DownloadHandlerAudioClip)www.downloadHandler).streamAudio = true;
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.LogError($"Error: {www.error}");
        }
        else
        {
            AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
            audioSource.clip = clip;
            audioSource.Play();
        }
    }
}

}

uneven atlas
#

hi i have this problem:

untold moth
uneven atlas
#

okey

paper moth
mild breach
#

Hey i have this issue with WebGL:

devout hare
#

You keep posting that to everywhere except where it actually belongs. Post the browser console output to #πŸŒβ”ƒweb

mild breach
lusty basalt
#

Kind of a broad question, but does anyone have a best practice approach for solving scene YAML merge conflicts when they are complex(Inconsistent fileIDs between versions, 10+conflict points stuff like that)?
I tell my students to work in different scenes and try not to do overlapping work on the same scene, but sometimes they dont follow that advice, and for small to medium conflicts I can usually solve it but just reading the YAML.
Is there an apporach or workflow to the bigger conflicts someone would recommend? Start from the bottom and make sure scene Root IDs overlap? Something specfiic to look for?

austere jewel
#

The most important thing is setting up Smart Merge to reduce the amount of YAML merge conflicts in the first place

lusty basalt
#

Ill fess up and say I honestly didnt know there was YAML smartmerge for external git GUIs until just now, thats actually huge.

#

It'll be hell to get all the students to set that up, but still big

#

Still academically interested in an answer to the workflow question, but Γ­t should probably solve most things

austere jewel
#

There really is no nice way around conflicts when they actually occur as far as I'm aware. I just have to go through them manually and if it is totally unworkable just resign myself to redoing the work

lusty basalt
#

Yeah, thats my approach aswell. Just figured I would check if there is a YAML-wizard here that had some attack-vector they use to pick them apart no matter the size.

#

So not so much looking for a way around them as a framework for how to think when solving them

fallow dune
#

Hey! I need some help. I am raycasting to try and detect the collider of the truck bed. I have added a tag but I can't seem to get it to return true .. It's giving me everything but the collider

  bool DetectLedge(out Vector3 ledgePosition)
        {
            float detectDistance = 0.2f;
            RaycastHit hit;
            float sphereRadius = 2.5f; // Adjust based on your needs

            // Visualize the SphereCast
            Debug.DrawRay(hipsRaycastOrigin.position, transform.forward * detectDistance, Color.red, 10f);

            if (Physics.SphereCast(hipsRaycastOrigin.position, sphereRadius, transform.forward, out hit, detectDistance))
            {
                if (hit.collider.CompareTag("Ledge"))
                {
                    ledgePosition = hit.point;
                    Debug.Log("Ledge Detected at: " + hit.point); // For debugging
                    return true;
                }
            }

            ledgePosition = Vector3.zero;
            return false;
        }
flint sage
#

Probably gives you the rigidbody?

#

Your collider is likely turned into a compound collider for performance reasons

long ivy
#

more likely it's not hittable by default, needs Physics.queriesHitTriggers set true or use the overload that lets you specify trigger interaction

flint sage
#

Oh right, I was thinking about the wrong thing πŸ˜›

fallow dune
#

So the trigger is where the player stands to be able to interact and get into the back of the truck

#

The blue collider is set up and I have added the tag and Layer but the actual mesh is being returned:

#

It's like it's ignoring the layer , tag and collider and hitting the actual truck mesh colliders

long ivy
#

oh you're trying to detect the bed itself. Your green collider distracted me completely. You might want to use a variant that accepts multiple results. There's a high chance your convex truck collider is detected first and returned

fallow dune
#

but why is it ignoring the layer ?

long ivy
#

ignoring what layer? Your snippet doesn't specify one

fallow dune
long ivy
#

your raycast doesn't specify a layer, so anything in the physics world (that isn't a trigger unless you set option earlier) is fair game

#

oh you do have a layer there

#

what is your mask set to?

fallow dune
#

Check the image

#

top right

#

Layer - INteractables

long ivy
#

that's the collider, what is ledgeLayerMask set to?

fallow dune
#
 ledgeLayerMask = 1 << LayerMask.NameToLayer("Interactables");
#

if I understand you correctly

long ivy
#

are you sure the truck isn't also on Interactables?

fallow dune
#

πŸ˜•

#

Let me check

#

Nope. All untagged

long ivy
#

tag != layer

fallow dune
#

Un tagged and layer = Default

#

sorry I should be more clear

long ivy
#

what layer is Interactables on and what is the int val of ledgeLayerMask? Everything looks right to me and the implicit conversion to/from int do the logical thing

#

I assume you have checked the obvious suspects, for example you have no compiler errors so your latest snippet is the one that's running and nothing like HotReload in use

fallow dune
#

That is what I was thinking. I ca't seem to see why the layer is not being respected.

The layer I think is 17

long ivy
#

next thing to try is the sneaky stuff. Make ledgeLayerMask serialized and don't set it manually. Maybe you have extra whitespace in your layer name

fallow dune
#

I think I found the issue

#

πŸ₯Ή

#

Not sure if this is it

#

Nah.. not it

sly grove
fallow dune
#

They Ray is shooting strainght through

sly grove
fallow dune
# sly grove From your code before I didn't see you even using a LayerMask
  if (Physics.SphereCast(hipsRaycastOrigin.position, sphereRadius, transform.forward, out hit, detectDistance, ledgeLayerMask))
            {
                // Now the SphereCast will only consider objects on the layers included in ledgeLayerMask
                if (hit.collider.CompareTag("Ledge"))
                {
                    ledgePosition = hit.point;
                    return true;
                }
            }
#

I am

sly grove
#

Ok so what's it hitting now

sly grove
#

You're using a sphere cast

#

Sphere cast has a radius

#

And 3D physics casts do not consider any colliders that they START out overlapping

sly grove
#

So if the start of your sphere cast is hitting that thing, it's going to ignore it

fallow dune
#

please explain this quick ?

fallow dune
#

So the 3D physics cast will ignore any collider is shoots through and only return what it ends on ? Like the End of the cast itself

sly grove
#

No it ignores things it starts out overlapping

#

It will return anything it hits as it casts through the scene

#

As long as it didn't start out hitting it at the beginning

fallow dune
#

Alright. let me give this a try. I'll fix a few thigns

fallow dune
#

@sly grove I quickly added a debug sphere to check

So I know that physics.SphereCast is casting right infront of me and should be seeing the collider on the edge of the truck bed.

paper moth
sly grove
#

as I was saying, the sphere is overlapping at the start

#

and will therefore ignore it

#

if you just want to check a sphere overlapping a spot, use Physics.OverlapSphere or Physics.CheckSphere

fallow dune
#

Let me give that a go. Thanks a bunch

long ivy
fallow dune
# sly grove this is showing exactly that it WON'T see it

Thanks a bunch !! I got it working perfectly!

bool DetectLedge(out Vector3 ledgePosition)
        {
            float detectDistance = 1.0f;
            float sphereRadius = 0.5f; 
            ledgePosition = Vector3.zero; 
            // Use OverlapSphere to check for colliders within a sphere around the origin
            Collider[] colliders = Physics.OverlapSphere(hipsRaycastOrigin.position, sphereRadius, ledgeLayerMask);
            foreach (Collider collider in colliders)
            {
                if (collider.CompareTag("Ledge"))
                {
                    ledgePosition = collider.transform.position;
                    return true; // A ledge was found
                }
            }
            return false;
        }
lapis arch
#

hey guys, anyone familiar with making packages in unity?

#

I have created a package and I want some of the code to be visible in the unity project view when imported

#

however, all of the scripts are hidden inside the package

sly grove
#

wdym by "visible" and "hidden"?

lapis arch
lapis arch
#

However, if you download an asset pack of medieval prefabs for example, they are all shown in the project window

sly grove
#

you can see packages in the project window just fine

#

there's a whole section for it

#

See at the bottom left?

lapis arch
#

Yes, Packages

sly grove
#

Note that it's a very GOOD thing that your packages don't go in the Assets folder

#

if they did - users would have to commit them to version control

#

which is a mess for lots of reasons

lapis arch
#

However, what If one of the packages I have created has some objects that I WANT to be visible in the assets folder?

#

like prefabs or scripts that should be editable

sly grove
#

they're visible in the packages folder, why does it matter which folder?

sly grove
#

packages are IMMUTABLE

#

on purpose

#

if a user wants to edit a prefab btw, they can copy and paste it into the assets folder

#

and edit the copy

untold moth
#

If you want to provide some settings files, like URP does for example, you would need to generate them on package import or let the user generate them manually(by using a menu command that you provided for example).

lapis arch
#

how do asset packs work then? ones that have city builder prefabs and scripts and you can find them in the package manager. You can indeed edit all of those.

sly grove
#

they are not UPM packages

lapis arch
#

Oh, so I can't have both...

sly grove
lapis arch
lapis arch
#

Oh, I found in the link you provided:

  • .unitypackage
  • UPM package
#

are the two types

#

Thanks a lot guys, I figured it out

silver flint
#

Hello guys i have a question what is better to achive ground check on 2D OnCollisionEnter2D or OverlapCircle()?

sly grove
silver flint
#

ok

paper moth
quick bay
#

if I have an assembly definition with a ton of dependencies, can I create another assembly that just references that assembly in order to avoid relisting all the dependencies?

#

it seems like the answer is no, but I don't understand why... it seems like a real pain to tell every assembly definition to reference every package I have

sly grove
quick bay
#

If that's the case, I feel like Unity needs to add a checkbox or something for automatically adding packages to custom assemblies.

sly grove
#

There's a lot about the asmdef workflow that needs improving

#

The best thing though would be for asmdef to die and Unity to fully roll into .NET

#

which supposedly is in progress

tired fog
#

does anyone unerstand this error?
Burst internal compiler error: System.Exception: Error while generating hash for method references: System.Exception: Error while hashing 0x060000D3 in sapra.InfiniteLands, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null ---> System.Exception: Error while visiting referenced token 0x1B000037 in sapra.InfiniteLands, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null ---> System.NotSupportedException: Unexpected type: ILGenericParameter

sly grove
#

something deep in the burst compiler Β―_(ツ)_/Β―

#

it didn't expect to see an ILGenericParameter somewhere, whatever that means

stuck plinth
tired fog
knotty obsidian
#

I'm using the ugs cli to delete players from my game's cloud save.

I got about halfway until I get an error, 429, Too Many Requests, code 50 with detail "quota had been exceeded". I don't know where to check my quota or anything around those lines, and the docs link the error gave me is unhelpful

#

It's been over 10 minutes and I can't resume the deletion of players, or even get a list of players

sly grove
tired fog
#

I might be dumb here, but how can I create a bool Field with UI Toolkit??

tired fog
#

Aaaaah toggle that's the one!

tired fog
#

Also, how can I make a field be clamped between two values? A Visual Element, FloatField for example

sly grove
tired fog
#

That's exactly it!

#

Also, I made this horrible thing to automatically transform a component to UI elements

VisualElement CreateVisualElement(SerializedObject bj, FieldInfo field){
        var type = field.FieldType;
        var value = field.GetValue(node);
        if(field.GetCustomAttribute<HideInInspector>() != null)
            return null;

        if(type.IsEnum){
            EnumField enumField = new EnumField
            {
                label = field.Name,
                value = (Enum)value,
                bindingPath = field.Name
            };
            enumField.Bind(bj);
            enumField.Init((Enum)value);
            return enumField;
        }

        if(type.IsEquivalentTo(typeof(float))){
            FloatField floatField = new FloatField
            {
                label = field.Name,
                value = (float)value,
                bindingPath = field.Name
            };
            floatField.Bind(bj);
            return floatField;
        }

        if(type.IsEquivalentTo(typeof(int))){
            IntegerField intField = new IntegerField
            {
                label = field.Name,
                value = (int)value,
                bindingPath = field.Name
            };
            intField.Bind(bj);
            return intField;
        }

        
        if(type.IsEquivalentTo(typeof(string))){
            TextField intField = new TextField
            {
                label = field.Name,
                value = (string)value,
                bindingPath = field.Name
            };
            intField.Bind(bj);
            return intField;
        }

        if(type.IsEquivalentTo(typeof(bool))){
            Toggle intField = new Toggle
            {
                label = field.Name,
                value = (bool)value,
                bindingPath = field.Name
            };
            intField.Bind(bj);
            return intField;
        }
        return null;
    }

i

#

there must be a better way tho right? Im trying to fill details into a node view with reflection so I don't have a custom editor for each possible node

#

and by a better way i don't mean to refactor this with generics, i mean to be able to add a set of attributes or something that automatically detects and applies things like range, min max attributes and other already available

soft marlin
#

actually no...

label = field.Name,
value = (float)value,
bindingPath = field.Name

that's the same for all of them right? so generics should fix this

#
public static class VisualElementExtensions {
    public static VisualElement CreateVisualElement(SerializedObject bj, FieldInfo field) {
        if(field.GetCustomAttribute<HideInInspector>() != null) return null;

        var type = field.FieldType;
        var value = field.GetValue(bj.targetObject);

        if (type.IsEnum)             return CreateField<EnumField, Enum>(field, bj, (Enum)value);        
        if (type == typeof(float))   return CreateField<FloatField, float>(field, bj, (float)value);      
        if (type == typeof(int))     return CreateField<IntegerField, int>(field, bj, (int)value);
        if (type == typeof(string))  return CreateField<TextField, string>(field, bj, (string)value);
        if (type == typeof(bool))    return CreateField<Toggle, bool>(field, bj, (bool)value);

        return null; // maybe log an error, I dunno?
    }

    private static VisualElement CreateField<TField, TValue>(FieldInfo field, SerializedObject bj, TValue value) where TField : BaseField<TValue>,         new() {
        var fieldInstance = new TField {
            label = field.Name,
            value = value,
            bindingPath = field.Name
        };
        fieldInstance.Bind(bj);
        return fieldInstance;
    }
}

I thiiiink this should do the same thing

cinder dirge
#

how can i detect variables changing in inspector for non monobehavior classes ?

untold moth
sly grove
real blaze
#

Hi. What's the status with webgl tasks?

#

Are they fixed in 22 lts?

#

Is there a standard solution that most companies tend to use?

real blaze
loud echo
tired fog
tired fog
austere jewel
tired fog
austere jewel
#

Yes

tired fog
#

I'm gonna check it, if that's the case, well, it solves everything

tired fog
cinder dirge
#

public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if(instance == null)
            {
                instance = FindObjectOfType<T>();
                if(instance == null)
                {
                    //Warning when there isn't instance
                    Debug.LogWarning("Instance of " +  typeof(T).FullName + " was not found.");

                    //If there isn't instance, create one
                    GameObject obj = new GameObject();
                    obj.name = typeof(T).Name;
                    obj.hideFlags = HideFlags.HideAndDontSave;
                    instance = obj.AddComponent<T>();
                }
            }
            return instance;
        }
    }

    protected virtual void Awake()
    {
        //If there is more than 1 instance, destroy this
        if(instance != null && instance != this)
        {
            Destroy(this.gameObject);
            return;
        }
        instance = this as T;

        //Uncomment the line below for DontDestroyOnLoad
        //DontDestroyOnLoad(instance);
    }

    protected virtual void OnDestroy()
    {
        if(instance == this)
        {
            instance = null;
        }
    }
}
``` i am starting to build my own github page. this is my first script. Can u guys make a review ?
tired fog
#

well, Thank you!

#

maaaaaan this helps so much lol, saving so much time now

#

can have all the attributes directly

tall ferry
# cinder dirge ```using UnityEngine; public abstract class Singleton<T> : MonoBehaviour where ...

I dont think there is much to really say about this, it is a bunch of standard code you see online when googling for unity singleton implementations. theres some things you could change. like do you need to hide and not save the GO? Logging a warning on creation here doesnt really make sense because it seems like its intended to be created through accessing its instance. the game object ctor lets you pass in a name as well

austere jewel
#

I would also note that FindObjectsOfType is expensive and this cost will be felt on startup. I've removed loads of those calls from codebases before to reduce hitching

devout hare
#

Personal preference but I don't like the idea of automatically creating a GO for the singleton if it doesn't already exist. That's just bound to lead to confusion later on

cinder dirge
#

how about this:


public class GameSetupDataManager : Singleton<GameSetupDataManager>
{
    [field: SerializeField] public SetupData setupData { get; private set; }
}
using System;
using UnityEngine;

/*
 * 
 * Replace variable fields to match entire project.
 * For a lot of setup data, using Struct to groub data (Must add '[Serializable]').
 * In entities, objects in game, get data from setup data at Start().
 * 
 */
[CreateAssetMenu(fileName = "NewSetupDataSO", menuName = "ScriptableObject/SetupDataSO", order = 1)]
public class SetupData : ScriptableObject
{
    [field: SerializeField] public string sampleData1 { get; private set; }
    [field: SerializeField] public float sampleData2 { get; private set; }
    [field: SerializeField] public SampleData3 sampleData3 { get; private set; }
}

//Sample data, delete this when using in projects
[Serializable]
public struct SampleData3
{
    public string SampleData3a;
    public float SampleData3b;
}```
i created this on my own
#

i gonna use this Github for my interview. I want to know if my code style is ok

austere jewel
#

Why are the public fields Pascal case but the properties are not?

#

And why all the numbered suffixes

cinder dirge
#

i commented it on header

cinder dirge
tall ferry
# cinder dirge i gonna use this Github for my interview. I want to know if my code style is ok

Maybe use a real example if this is for showcase purposes. Plug in stuff like loading save files, or spawning characters (capsules) into the world. It's really easy to just say "yea this is sample data" but that might translate to "i dont know how this can be used"
Also if your script is full of stuff that says "delete this if..." it's tedious to use. When people want to use a github script, they want to do 2 things. Copy and paste.

#

It's not to say people are incapable of reading and editing, but it's just not something you wanna show off

cinder dirge
#

thanks so much.

untold moth
#

Honestly, if it's something for a portfolio, you'd probably get much more attention with a complete game(even if small and simple one) or an interesting prototype rather than separate scripts taken out of context.

#

Maybe an editor asset/plugin would do, but only if there are not already hundreds of similar assets.

#

Because, code like the one you shared, can be easily generate with AI nowadays. Or even just copypasted from a tutorial.

cinder dirge
#

It is a simple script for my library on github

#

It is for me to read when i forget and for my interview in future

#

I will add more complex script and some projects. Working on refactoring my code and push onto github

polar widget
bleak citrus
#

should be at the bottom of the inspector

#

it's the little button on the right side

polar widget
#

alright , works fine

#

thanks

#

next issue : In rider when i'm following the example in the manual #archived-code-advanced message

I'm gettin a conflict message ,like every assembly have a class generated in their assembly . cf screenshot , any idea why ? Did I miss something ?

gritty lagoon
#

hi, is there a way to 'channel' audio data (that has been modified by one or more OnAudioFilterRead() filters) to play on a different AudioSource?

here's more context:
I'm using a package that uses OnAudioFilterRead to modify the audio source volume to playback other player's microphones. I want to channel that output to multiple different audio sources that are located at different places and have different audio filters applied to them

ivory salmon
#

Is there a way to detect if a gameobject has been destroyed in current frame (the ==null check doesn't work - it doesn't get actioned until end of frame)?

(this is to work around the bugs in Unity Physics where OnTriggerX messages are sent to destroyed objects (thanks, Unity))

stuck plinth
ivory salmon
#

Ugh. I was optimistic there was some trick I didn't know about :). Thanks

stuck plinth
#

implementing a flag or something you set when you destroy the object is so simple i can see why it's not built in, there's not really a need usually

ivory salmon
#

That's ... insanely difficult.

#

Going to contact every developer everywhere and ask them to set your flag?

stuck plinth
#

why would that be necessary?

#

normally if you want an object to be destroyed immediately, you use DestroyImmediate.. otherwise it's perfectly normal for it to keep getting physics events until the end of the frame isn't it?

ivory salmon
#

The code that calls destroy is often (usually) in a different codebase to the code that implements OnTrigger

#

(e.g. a game tyically calls destroy, an asset typically implements physics)

#

Yeah, DestoryImmediate is I suspect OK for my case.

#

(But will require some testing, I've had problems in the past when Immediate violated some expectations of other code - I think those all turned out to be bugs in the other code, so I'm optimistic, but ... I'll test carefully :))

stuck plinth
#

disabling the object should also work

ivory salmon
ivory salmon
#

Changing the destroy code to "1. Disable, 2. Destroy" sounds like it's probably what the code should have been in first place, to be correctly implemented

stuck plinth
ivory salmon
#

(I don't often destroy objects, but if you'd asked me, I think I'd have assumed ondisable was autoamtically called as part of ondestroy, if it hadn't already)

stuck plinth
#

it is i think, but normally it'd happen at the point it's actually destroyed, at the end of the frame

ivory salmon
#

yeah, unfortunatly I'm working with a lot of 3rd party code, so ... trying to find the "most correct, most safe" way of handiling thes things

#

The "disable now, invoke destroy ... destroy happens at end of frame" pattern first - feels most 'correct' and least confusing, and works fine. 3rd party code that isn't paying attention doesn't need to change - it'll typically hook OnDisable if it needs to. Testing it just now ... worked fine.

stuck plinth
#

that's probably safer than trying to check something custom, you usually want something to be completely gone (disabled, destroyed) or not, rather than disabling specific bits of logic!

ivory salmon
#

Thanks - in future I think I'll adopt the Disable+Destroy approach. I'm not sure why that's not standard already - I think (IIRC) it also fixes some of the problems in Physics callbacks where a 'destroyed' object doesn't trigger OnTriggerExit on other objects, where Disable does

#

(or maybe it's already standard, but I so rarely write code to destroy things I hadn't noticed)

solid basin
#

Looking at the SRP Blitter.cs utility, why does it support blitting with both triangles and quads? It's not documented why not just stick to one strategy - is the result not the same?

#

Also am I misunderstanding how SRP is supposed to be used?

It seems weirdly coupled to URP // to include its Blit.hlsl shader I need to include URP core shaders too. Is the SRP intention not that you can create a URP alternative?

bleak citrus
#

to include its Blit.hlsl shader I need to include URP core shaders too

where are you seeing this? I don't see any references to any URP shader code in Blit.hlsl

#

it only includes other core shader code

tired fog
#

Hello friends

#

I've been trying to make a node editor, and found a quirky thing. There's this attribute from NaughtyAttributes, AllowNesting that makes my parameters look nice.

#

with allow nesting attribute

#

Without AllowNesting

#

So i looked into what does the attribute actually do, and it's only this

[CustomPropertyDrawer(typeof(AllowNestingAttribute))]
public class AllowNestingPropertyDrawer : PropertyDrawerBase
{
    protected override void OnGUI_Internal(Rect rect, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(rect, label, property);
        EditorGUI.PropertyField(rect, property, label, true);
        EditorGUI.EndProperty();
    }
}
#

So since I need it for all the fields on all the nodes, and I already have a custom editor for the node, I was thinking of hardcoding those lines. However i'm not sure how to translate it for UI Toolkit

#

Basically, this is the method I call to generate each field

VisualElement CreateVisualElement(SerializedObject bj, FieldInfo field){
    if(field.GetCustomAttribute<HideInInspector>() != null || field.GetCustomAttribute<InputAttribute>() != null)
        return null;
    
    PropertyField propertyField = new PropertyField(){
        label = field.Name,
        bindingPath = field.Name
    };
    propertyField.Bind(bj);
    return propertyField;
}

and works with the attribute and without, that visual element gets added to the nodeview. So i need to add those kinda lines there, but im not sure how or what I could use?

fickle mango
#

Is there a way to change this value automatically before I build? So the built game has the correct version number while it runs.

novel plinth
#

you can just do PlayerSettings.bundleVersion = "xx.x.x";

#

is that your own version or based on the Application.version?

#

and to answer your question, there's IPreprocessBuildWithReport callback that will be called before building

fickle mango
hallow elk
#

Is there a way to remove specific listeners from a UnityEvent via script?

hallow elk
compact ingot
upbeat path
hallow elk
#

That's fair. In this case I was using a UnityEvent as a temporary solution and now I have a more explciit method to handle it, so I am wanting to create an editor script that iterates through these objects and takes the info from the UnityEvent and converts it to the explicit method.

compact ingot
#

but since that’s usually quite complicated and and depends very much on knowledge of the implementation details of Unity events you’ll have to probably do some legwork yourself.

hallow elk
#

I do have a lot of knowledge of UnityEvents! πŸ™‚

#

Reflection it is

toxic marsh
#

Is it possible to use System.Drawing.Common In unity?

upbeat path
toxic marsh
#

Would you be able to help me figure out a way to Screenshot a users Entire Desktop then and make it accessible? my method used that Dll

upbeat path