#archived-code-advanced
1 messages Β· Page 95 of 1
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.
So do some debugging and see what type it actually is? This doesn't seem like an advanced problem
userObject["UnlockedTasks"] is List<string> but userObject is Dictionary<string, object>. I do some research before coming here. I can convert the values of userObject to strings with (string) but haven't found a conversion that works for Lists
if(the value is List<string> list){
}else{
Debug.LogError($"WHAT {value.GetType()}");
}
```please verify the value is list<string>
You would convert(cast) it to a List<string> the same way you might cast it to a string.
I pasted the error i get doing that in my initial message
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.
so check it
you think it is list<string> but your runtime doesnt think so
it reads as an object - System.Collections.Generic.List`1[System.Object]. Maybe I can do something like (List<object>)
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.
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>();
}
missing ending code fence
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.
I mean in your discord message to format it as code xd
ah. For readability or would that make the text smaller
I find it much more readable.
Also you can add cs on the same line after the first ``` to get colors
Are there some examples I can look at?
```cs
Your code here
```
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
It was
Oh, its because you added a space
space removed
There is some extra whitespace after the cs
Its rather picky apparently
ok lol thanks for helping. There we go
Yea now it should have syntax highlighting like in the IDE
yo peps
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 ...
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?
The while(true) is really the worst I believe. The only alternate solution I can think of would drastically change your design.
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
2 iterations of loop deep and recursions yeah that is going to be slow
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
Just moving the condition "if (fallbackFrom == CrewState.None)" into the while could help with readability. Maybe
yeah, or maybe this is the rare case of a do {} while () loop
Also, you could divide into two function.
One with the inner loop, and the other with the other loop
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
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
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
this is what a typical "data set" looks like:
Instead of looking this way, you could reinterprate all your transition by :
(A | I) to B
(A | I) to C
(A | I) to D
(E | J) to F
(E | J) to G
(E | J) to H
After, only a single iteration on all transition would be enough.
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?
That, given that you do not have a "priority" over which one to use
this here could be a dict as well, with a tuple key to the value
or is CrewState a enum?
crewstate's an enum, yeah
flag enum
Yeah, then it wont work.
if its a flag enum the keys could just be bitwise or operations
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"
value tuples might work then to combine the multiple enum values into 1 dict key
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?
why neither?
that's how this particular library works.. lemme maybe show rather than tell π sec
here's sad, nervous, and nervous-to-sad
(corrected myself up there a bit, but I think you got the point)
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
oh its spine
yeah
yeah using spine too, but i ended up skipping there stuff and used mecanim with it
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)
but what about the fallbacks?
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)
okay, but that doesn't affect the transition?
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
it really sounds like you got a whole tree structure going on then
The fallback i not really a fallback but a replace ?
but in cases where there's .. flipping sprites or doodads, they can flicker or disappear awkwardly if the transition animation isn't built
think i would just kinda traverse it with a stack
my point is, you're not looking for transitions from/to fallbacks
yeah, it's kind of a tree structure
I don't understand.. i for sure am..?
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
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 ?
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
like i said before what you have is not that much code, and if it works fairly bug free
I mean, I feel like I either do not understand your issue or you are making your issue bigger than what it is.
i would just comment it and explain what is going on and move on
What we want: Transition -> Excited to Angry.
Character is replacing Excited by Happy.
Hence: Transition -> Happy to Angry
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. π
yeah just a mapping of overrides to apply really for that case
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 π
the outer one is literally a do while with fallbackFrom == CrewState.None for condition
Usually comments can be replace by function.
Whilte true with a break can be replace by a while(condition)/do-while()
So yeah, to clean it I would personally do that.
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
isn't the recursive call kinda duplicate work? π€
the two while loops already do all the enumerating, no?
Yeah, why is there a recursion there π€
having both is what i found most strange
@misty glade might be worth thinking about that π
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
yep, I think one of them can be "removed"
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
recursive here would be super short... but kinda Fibonacci-y π
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
why? they seem pretty much like fallbacks to me π€
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
ah, that they did, yeah
maybe character B it maps to something else
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
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?
There isn't by default. You'll need to include the whole compiler in the build for that to work.
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
Im getting an Error CS1503 anyone know the reason?
What does the error say? That error comes up when you can't convert one type to another. It should tell you the types and the line in the console.
Ah, sure that's possible. Should be able to hook to the build pipeline, or use preprocessor directives.
https://docs.unity3d.com/ScriptReference/Build.BuildPlayerProcessor.html
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
I really doubt that's an advanced question. Share more details in #π»βcode-beginner
But you go through all the fallbacks in the iteration part already (hence the while loops and not just a single fallback thing)
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?
Wrong channel, and it's a warning not an error. #π±βmobile
Thanks i think you are not familiar π₯² @devout hare
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) π
why dont you just post your code?
it was too long.. i will split it sec
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
btw asking in dots maybe better
i am not using ecs only job system thats why i was not sure .. can you have a quick look i think its pretty basic but i can't figure out where my problem is
Dots encompasses ecs, jobs, and the burst compiler
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 π
dont allocate a persistent array in update
daaamn this should be temp
and use i job parallel for transform
could this be the issue why i don't have any performance differences?
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
please a fair answer.. how far i am away from a good solution? π π like i said everything self tought and way early beginner π
learn how to use i job parallel for transform should be ok right now if you are moving bunch of transforms
i will have a look into that thanks a lot!!
can you tell me why in the unity documentation --> https://docs.unity3d.com/ScriptReference/Jobs.IJobParallelForTransform.html they are allocating a persistant array in update?
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
okay thanks for explanation
We cannot use this type of object in Jobs
they must be structs and/or value type
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
Have you checked the crash log?
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")]
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
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
Showing what the error is would be a good start. Also doubt this is really an advanced issue
Asset database is editor only iirc
well seems like i can now make a build unity must used a bit of magic
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;
}
}
is there something like memset for nativearray/list? e.g. when I want to set a whole NativeArray<float> to 0
I would get the pointer then memset
Btw memset float to 0 sounds weird
You'd probably use the third variant of the constructor with options to clear the memory
https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1-ctor.html
why are you trying to load ScriptableObjects as GameObjects?
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?
thanks for linking this! I guess I'd share results, turns out this is actually faster than doing .CopyFrom, not by much, but measurably!
NativeArray<byte> pixelArray = maskTexturePixels.GetPixelData<byte>(0);
// 0.020ms
pixelArray.CopyFrom(_maskTextureClearData);
// 0.015ms
unsafe {
void* colorPixels = pixelArray.GetUnsafePtr();
UnsafeUtility.MemSet(colorPixels, 0, pixelArray.Length);
}
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
It happens because My Base State defines the _context as EnemyBaseStateMachine for abstraction purposes
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
This is what I came up with now, do you see any problems with this approach?
public class SlimeJump:BaseState<SlimeMachine,SlimeFactory>
I think you are talking about generics right? Learned a bit about them during my bachelor but knowledge has left me haha
yes
If you specifically want to set everything to zero, then MemClear is more appropriate. No idea if it's any faster.
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:
Can anybody explain in lamens terms the difference (if any) between UnityEvents and Actions/EventHandlers?
Other than UnityEvents being serialized in the inspector.
Other than UnityEvents being serialized in the inspector, that's pretty much it
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
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
make a non generic base class they inherit from
or an interface'
its possible with reflection
the end type is generic?
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
i think add ons like DOTween have stuff like that although you can probably do without it
._.
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?
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 ?
Post Processing V2?
I think that's the one. The one meant for SRP.
SRPs use the volume system, not PPV2
then that's what I mean. The volume system.
The concept is similar/identical
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!
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.
Do you have any code that does something with said asset in the editor? Perhaps it has a bug? That would be my first thing to look at. And alternatively seeing if it repros on an empty-ish project or after removing various things from current project, but that does require being able to reproduce it reasonably consistently.
There's an asset called microverse that allows procedural terrain editing. I've contacted their support but they say that they can't reproduce the bug and then some generic stuff like clearing the library. I'm sure that the asset plays a role in the issue, but there are just no clear proof of that.
Does it take time for the thing to happen? Next time it happens, can you add breakpoints in their code, see if they get hit and follow them to see what happens? π€
It happens on domain reloads. Not always. I'm still trying to figure out the conditions. Sometimes it happens on the first domain reload after opening the editor and sometimes it doesn't happen for several domain reloads.
The asset code is mostly in a dll and I don't have the debug symbols or source code. Whatever I do have access to, doesn't seem very relevant.
I see, I see... not great. I've got no other ideas right now π€ Good luck with it! π€
Does the asset specifically support 2022? In my own asset saving Terrains I noticed some differences between 2020/2021 and 2022 so I produced a package specifically for 2022
Mmm... The latest change logs mention fixing bugs in 2022, so I'd assume that it's supported. Also, when I contacted the asset dev, they didn't mention anything about my unity version being not supported.
I dont know how microverse is manipulating the terrain data but if you want to DM me your Terrain data asset I can run it through my code to see if anything pops out
I guess we can try that.
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.
have you run it with the Android LogCat package installed to see if any errors occur?
Oh no. I did not even know it exists. Can i see android errors in inspector on my computer?
yes, if you install the Android Logcat package into your project then do a Build and Run to your Android device you will see the Android logging in your Editor
Thank you alot.
I will try rn
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
What "while function"? You'll need to share the code if you want help. It's also unclear why you're looping over pixels if you want to do pathfinding.
how do i send code correctly, i dont wanna sned it wrong
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/xihimeqixi.cs
^the code
and im looping over pixels to get the flowmap ? that i can then use to get the path from my target to the start
Im trying to replicate pathfinding like its explained here https://www.redblobgames.com/pathfinding/a-star/introduction.html
So what's the question exactly?
why does my for loop stop immediately
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)
you mean the while loop right?
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
yes
You're not debugging
you're guessing and removing code
but you're not debugging
attach a debugger or use log statements or both
but if the diff would fail then there would be magenta pixels
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
I'm trying to make a package as a dll following the docs https://docs.unity3d.com/Manual/UsingDLL.html. But the code i want to package makes use of UnityBurst and Jobs, but I can't find those DLL in the managed folder
How should I do it?
They aren't here?
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
Nop, that's what i mean, jobs and burst arent there
Unityengine and unityEditor are there, but I cannot find jobs an burst
Appears to be a known shortcoming/limitation with Burst
Well, wtf, what do i do now? XD
I want to beta release a paid unity package with the code obfuscated
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
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
Mmm, that could work, but I don't think it's worth it. The main important part is the whole jobs and burst code
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)
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
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
The stack trace of the warning will show you where the method is being called from
Ok
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
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.
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?
Can you process the mesh once to create e.g. an SDF for further/optimized usage?
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...
Definitely don't get physics involved here, looks like a pretty straightforward delayed following kind of thing, along with tilting based on the calculated velocity.
The path I'm trying to follow doesn't involve physics, because I can't either, it involves calculating sin and cos. But I can't find a solution.
Yeah i specifically said not to use physics
I don't see any reason you need trigonometry either
Of course, which path would you take?
this path
each node follows the previous node
and tilts itslef based on its lagging calculated velocity
very interesting!
You could do this with the Animation Rigging package
https://docs.unity3d.com/Packages/com.unity.animation.rigging@1.0/manual/constraints/DampedTransform.html
@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
What is the best method of encryption and does it have any good tutorials?
depends on the use- but public key encryption is the most common in use nowadays. it will let anyone encrypt a messge to you, but only you would be able to read it.... this is what banks use for online banking.
thx
Depends on what you are doing with it.
I just want things like meshes and textures encrypted
if you don't need anyone else to send you encrypted information, public key might be overkill. Also, if you will be doing this decryption on a client system, you'll need to, somehow, have/get the decryption key & method ON that client system.
That's a really vague answer though
what are you doing with the encrypted data?
who are you trying to prevent from reading it?
I am just trying to prevent anyone from being able to datamine assets out of my game such as the player mesh.
impossible
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
Is there a way to make it more difficult?
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.
oh
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
it's dead π
Why are you so afraid of people ripping your assets?
Idk, I just don't wanna see some person take something I worked hard on
I'd be willing to share if I was getting credited and I knew what they where doing
This is what lawyers and license agreements are for
Well they can't take it and use it commercially, legally
But fair use is a thing
I am 15 I can't afford a lawyer over some blender model.
In general though, I would be absolutely ecstatic if a game I made was cared enought about by people to bother ripping the assets
It would be for when you need them, after the fact
you wont need the lawyer unless your game is successful enough that you can afford one
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.
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
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
Thanks
Disagree. I think any extra pain=in the ass step you can add reduces the chances of theft.
@subtle river Can shader information be obtained from those "3D screenshots"?
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?
Yes, but that's one of the few things that's harder to grab since it's going to be low level shader instructions and not the shader source you work with
You won't get the benefits of any precomputation phases Unity does with the meshes at build time for example
My models aren't that good anyway, someone would be an idiot to try and steal them.
@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
Reduces the chances of a casual actor doing it, and does nothing to a determined actor, and can reduce the wellbeing/enjoyment of a normal user
agreed, always a tradeoff
These probably aren't worth stealing anyway so I should be good π
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
I think it looks lovely for what matters π
Thanks
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
Yeah if they can grab the final output then it won't matter what work we do I guess
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
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)
Best I could find when I last looked was the Kiwi Coder video. There's also a livestream from Game Dev Guide but I haven't finished it.
I haven't found any good written stuff :/
https://youtu.be/nKpM98I7PeM?list=PLyBYG1JGBcd009lc1ZfX9ZN5oVUW7AFVy
https://youtu.be/uXxBXGI-05k
kiwi coder is what im following but that's almost 2 hours (counting part two)
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.
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
anyone can just use nsight graphics if they have a nvidia gpu
not much you can do
(coming from a professional unity game modder with slight unreal experience too)
renderdoc also exists too
yeah there is no stopping it
RenderDoc or like NSight can be used to get anything once its on the gpu
Imagine Nintendo face if there was a fail proof method of preventing piracy and asset stealing.
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
Component does not have an enabled property. your list would need to contain Behaviour or its derived types
no
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
do you have a code example, because as boxfriend said, you can't do components[0].enable or something like that
the list needs to be of Behaviour not Component
yea but you can't put a Collider for example in a List of behaviors
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) {}
Renderer is another case
ugh, thats annoying
looks like the got smarter with later features, like Collider2D extends from Behaviour
I understood what you meant, thanks
Maybe just deactivate the desired gameObjects instead of trying to break the system.
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.
There are many ways to o about it. Delegates could work. Alternatively, retrieve the desired objects defining the behaviour from an array or dictionary.
Sure dictionaries work, but that sounds like a pain to manage, where derived types are a lot easier to handle...
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
If you only have one component, it's not really composition (and it's not really different from inheriting from Neuron)
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
Yeah I prefer articles because normally they include links to other references and it's easier to move around to certain sections
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
@tired fog which one are you watching?
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?
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
Kiwi Code video, https://www.youtube.com/watch?list=PLyBYG1JGBcd009lc1ZfX9ZN5oVUW7AFVy&v=nKpM98I7PeM
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!
...
It's been a while so I don't fully remember, but I used this at the start. Very bit sized, specific videos:
https://youtube.com/playlist?list=PL0yxB6cCkoWK38XT4stSztcLueJ_kTx5f&si=aGtzxYHn7oNxQMLp
@tired fog
Hahahah
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...
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
Of course! Thank you for it, if it's not for me surely someone else will find it useful!
how can i make the player can pick all of object in my game without add any public float on my script?
Sorry what? you want the character to be able to grab an object witout having a new public float on the script? Hows it related?
Or do you want to hide the floatsΒΏ
should my script have all public float to input the pickable object?
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.
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?
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
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.
This would fit better on #π»βcode-beginner or #archived-code-general
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
So basically here I am making a cooking themed game, so I am trying to make it in mobile form, and for the purpose of what I am asking is I want all the food ingredients to be taken by this player.
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what bro?
there is empty on the link
i think u must
// Your code here
type like that bro
He's telling you to use one of these methods to share your code, instead of sending screenshots.
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);
}
}
}
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.
oke bro
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
you need a temp value in your for loop
temp?
not code advance
you have to capture the variable
for (int i = 0; i < n; i++) {
int temp = i;
mything.AddListener(() => DoSomething(temp));
}```
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
compiler wont do it for you, or make a custom struct that capture data yourself
how would i capture the variable by value and not ref? would it be cleaner han a temp variable?
there's no way to capture by value
alright
variable capture is always by reference
but that temp soltion would work?
yes
alright appreriate it
it works. thanks man
i was going down some weird rabbit holes for a while there
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
C#/VB/F# compiler playground.
(I would think cross-scene communication goes here, but okay, thanks)
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"
Is there a way I can use a property to access an array like so:
(not static though)
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?
You mean a custom attribute on your node SO class? Or am I misunderstanding?
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;
}
am I missing something? Aren't they identical already?
What's the difference?
oh just the return value
The first one returns the foundtype, which is the type where there is the right attribute, the second one returns the right attribute
yup
i dont' see a way to return one or the other without having to do another check as that one
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)
I was looking at https://learn.microsoft.com/en-us/dotnet/api/system.attribute?view=net-8.0#properties to see if there was an "TypeIMAttachedTo" property but there doesn't seem to be
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.
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;
}
sure that's one way.
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!
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?
Nice work, think thats a pretty good approach!
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
This is not advanced coding question. This is not even a coding question. You'd ask it in #π»βunity-talk
To avoid duplication though, you'd either use the Timeline package or implement your own system for cutscenes.
Okay, I'll ask it in #π»βunity-talk , but when you mean duplication, do you mean like the player being moved during the cutscene?
No, I mean duplication of posts, cross posting.
Also, for the future, ask in the one for YOUR skill level, not the difficulty of the question. If you are a beginner, it would go in #π»βcode-beginner (if it were a code question)
Okay thank you'
Okay
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.
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;
}```
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
Iβm looking for the two closest bottom points. Issue is I already tried multiple times and it would override what I did. Not sure if you can give me a example on finding the two closest points?
yes its a polygon collider
no, you're using the collider bounds which is an AABB, so your code is looking at these values
So what would I have to do?
you need to look at the collider itself https://docs.unity3d.com/ScriptReference/Collider2D.ClosestPoint.html
Mhh seems tricky. Iβll try tomorrow. Iβm wasted in all the shader code i did today
Ok I see what you mean
i need some help with understanding and making changes in the template from unity asset store, can anyone help me with that?
Are you sure that's an advanced question?
bro do you make it
yes ofc
@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;
}
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
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
I find it easier to use the UI Builder and load in the uxml
once you get used to how to bind elements to variables in code it becomes a better workflow than manually coding the UI, IMO.
How do you bind the data from an uxml to the code?
which is pretty much analagous to JQuery stuff in JS
They're not magic if you define them in the inspector
They're not magic if you define them in
the inspectorSCREAMING_SNAKE_CASE in a static class
That are auto code-generated from file names.
is this a open project, how many levels are there, are they humanoid can characters be selected ?
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
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
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.
Well 1. WWW is obsolete, use UnityWebRequest instead
- UWR/WWW themselves should definitely be happening in a bg thread automatically
so i suspect something is off with your code
You can use the async/non-blocking overloads of the Unity web API or the native C# web API that is async. In unitask you have to specify explicitly that you want it to run on a thread. By default unitask runs on the main thread.
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
is there a way to see what is causing shader to fail and fallback to one defined in the Fallback "..." (in .shader file)?
Is this a good way to create a field?
IntegerField lacunarity = new IntegerField(){
label = "Lacunarity",
value = settings.lacunarity
};
lacunarity.RegisterValueChangedCallback((a)=>node.settings.lacunarity = a.newValue);
Yes and no. Depends on if the value are optional or not. In your case, a constructor should be better given the name of the class.
The issue is that, at some point, you might get classes that are not configured correctly. It also make it harder for people to know what the class is expecting.
How should I do it?
Using a constructor ?
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
No idea what you are talking about. I am just talking about clean code.
Ah lol
Ideally, you do not want to use pattern the way you are doing it now.
This is related to graph views and the way UI toolkit is setup
You asked if it was a good way to make something. I simply stated that it is not for the given reason.
Yeah, im just saying that the message has context
Create a factory or wrapped it.
Alteranatively, look into if there is not already factory or constructor for the field.
I'm still having issues with this. I already modified the code but it only looks for the closets point but doesn't check the position of the other points
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
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;
}```
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
I want the camera to stay with in the polygoncollider and to find the closet y and x bounds and use that to restrict the camera from going out of bounds
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
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
So what would I need to do here as the camera has its own controls over the player
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
honestly I might do a spline though would that cause issues with my camera when its not touching the bounds?
how so? which bounds?
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?
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
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
Thats how the original worked. If he high enough he does appear on screen.
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
This is the example. And the bottom is what I donβt want
@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?
restrict? If you're talking about the camera I'd say no, otherwise sure some kind of invisible collider is fine
yea like a invisible collider. For example lets say I have two invisible colliders. These invisilbe colliders doesn't allow the camera to not go outside where those colliders are located.
like it won't allow the camera to go passed this collider
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
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?|
? Camera follows player. Limit min y of camera pos based on spline. Simple as that
oh
ok I guess thats really it then
@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
assuming you're using Unity's spline package, look at the docs: https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineUtility.html
and specifically https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineUtility.GetNearestPoint.html#UnityEngine_Splines_SplineUtility_GetNearestPoint__1___0_Unity_Mathematics_float3_Unity_Mathematics_float3__System_Single__System_Int32_System_Int32_
You probably just want to evaluate the spline based on t though, no?
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
asmdef?
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
yes? fix your syntax error
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
still a syntax error. You need to provide a spline, not a spline container
ops
T needs to be a type that implements ISpline
I didn't realize i put the container
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
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
Preferences -external tools - check all of the package boxes and regenerate project files
i did this π and it works like a charm imo. Do you mind checking my code if i handle things correctly and efficient? The script contains 2 Jobs.. 1 for spawning enemies from an objectpool and one for let all the enemies chase the player.. https://gdl.space/ipodepaduq.cs would really appreciate this β€οΈ
@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
how many enemies are there? I'd be shocked if this is outperforming the non-job version unless there are thousands
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..
there could be like 10-20k
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
in editor with ~13k enemies around 40fps .. in build like ~100fps
is this too low? π
for a bursted job, it's low. For your implementation, it's much higher than I would have thought tbh
Hi, does someone know how to play the audio data from one audio source to another (or multiple other) audio source(s)?
you can freely assign audio clips to audio sources and/or use PlayOneShot from them
There's also AudioSource.PlayClipAtPoint
yea but i need it to work for 'live' clips
so for audio where i don't have the audio clip file
that doesn't make a difference
everything I said still applies
You will need to create an AudioClip regardless (that doesn't need you need a "file" per se)
is it then just as simple as doing targetAudioSource.clip = sourceAudioSource.clip?
what does playoneshot mean
Or AudioSource.PlayClipAtPoint(source.clip, position);
what if the source audio source's clip is looped?
clips don't have a loop property
that's part of the source
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
So it's printing "planet.getparentsystem is null" right?
or is it printing "Planet is null"?
i think you need to show the code in GetParentSystem too
so then the parent system is null
you really should turn off Collapse on your console window
the logs are all out of order
That is the problem , they aint null.
not on that instance
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?
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
You may have another PLanet where it's not set
Debug.log has a overload that takes second parameter
also consider log when setting parent system
and learn c# property
other than the one you showed
I checked all planets , they are all set
Also you are setting the parent in this code
WHy not just print the name of the one where it's null
you don't need to check them all
Let me do that quickly hold on
when does the generator run? is it during the game or an editor tool?
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?
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I 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 β€οΈ
whast this do?
read the bot message
It tells you how to post code in this discord
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
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
Depends on the input. But it can be as simple as doing a Depth First Search.
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)
that seems not easy - do the graph points have to be in some initial order rather than a random list of connections? If I add a 14th point it does not quite work
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
not
vertices set is unordered (without edge)
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
i didnt check the algorithm
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
Do the edges overlap?
If so, the problem gets significantly harder.
no there is no overlap - it is all neat & tidy!
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
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
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.
they're being pushed around by the fact that they're occupying the same physical space as another object and getting depenetrated
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
Thanks for helping ! I have my character (kinematic rb) and a moving platform (non-kinematic rb). The platform can't be kinematic because it is moving. The platform must have a rigidbody because KCC forces moving platforms to have a rigibody in order to be detected by the character.
As is, the character pushes the platform instead of standing on it.
My guess is that a non-kinematic rigidbody will always be pushed by a kinematic rigidbody, no matter their respective masses...
The platform can't be kinematic because it is moving.
This isn't true
you can move kinematic things
you just can't move them with forces
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
would you mind teaching me a little how to do things better? Or give further hints what i can improve.. the problem overall i have is that everything i learned until today is self tought and sometimes i have the feeling i lack in understanding basic principles of coding π
- create your TAA once and add/remove to it as needed
- eliminate the ToArray as mentioned
- 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
- 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
- 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
- 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
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;
}
}
it doesn't work because the download never ends. The file keeps getting larger and larger, so it never finishes downloading it
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?
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();
}
}
}
}
hi i have this problem:
GPU went kaboom! That's the only thing clear from that error message.
okey
i will refactor my code and will get back in touch π thanks for your help REALLY appreciate it π
Hey i have this issue with WebGL:
You keep posting that to everywhere except where it actually belongs. Post the browser console output to #πβweb
Posted it in 2 channels bc idk where to post, but thanks
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?
The most important thing is setting up Smart Merge to reduce the amount of YAML merge conflicts in the first place
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
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
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
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;
}
Probably gives you the rigidbody?
Your collider is likely turned into a compound collider for performance reasons
more likely it's not hittable by default, needs Physics.queriesHitTriggers set true or use the overload that lets you specify trigger interaction
Oh right, I was thinking about the wrong thing π
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
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
That is I think exactly what is happening
but why is it ignoring the layer ?
ignoring what layer? Your snippet doesn't specify one
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?
that's the collider, what is ledgeLayerMask set to?
ledgeLayerMask = 1 << LayerMask.NameToLayer("Interactables");
if I understand you correctly
are you sure the truck isn't also on Interactables?
tag != layer
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
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
Ya, for sure
welp....
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
Why not just LayerMask.GetMask("Interactables") π€
I mean, I tried that. π . Kinda at a loss , so I am trying a few thigns
They Ray is shooting strainght through
From your code before I didn't see you even using a LayerMask
Here
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
Ok so what's it hitting now
Also this DrawRay is very inaccurate
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
ohhhh
So if the start of your sphere cast is hitting that thing, it's going to ignore it
please explain this quick ?
SOrry I did not tag the message
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
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
Alright. let me give this a try. I'll fix a few thigns
@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.
- done
- done
- done
- done (ignore the spawning part i will refactor that aswell)
- done
- for now they don't have a collision detection. this is the next thing aswell as animations i want to implement π
with ~16,5k enemies in editor ~50 fps ingame ~250 fps --> https://gdl.space/yanutusaze.cs any further improvements? or is there something done wrong? π really appreciate your help
this is showing exactly that it WON'T see it
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
Let me give that a go. Thanks a bunch
looks good to me, but prototype out the animations and collision asap because those might need their own jobified/custom solutions too with the number of enemies you have
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;
}
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
wdym by "visible" and "hidden"?
hidden are for example all of the scripts of the "input system" package by unity, you can't see them in your project window
That's a good thing
However, if you download an asset pack of medieval prefabs for example, they are all shown in the project window
you can see packages in the project window just fine
there's a whole section for it
See at the bottom left?
Yes, Packages
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
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
they're visible in the packages folder, why does it matter which folder?
ah there's the misommunication
packages are IMMUTABLE
on purpose
Read the section on "Registry" packages https://docs.unity3d.com/Manual/upm-concepts.html#:~:text=The Unity Package Manager downloads,or change their package manifests.
if a user wants to edit a prefab btw, they can copy and paste it into the assets folder
and edit the copy
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).
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.
assets from the asset store get dumped into the Asset folder
they are not UPM packages
I found this, maybe it's helpful: https://github.com/needle-tools/hybrid-packages
Ok, that helps me understand it better, one thing I'm describing is a UPM package and the other one is?
thanks for this π
Asset store asset.
Oh, I found in the link you provided:
- .unitypackage
- UPM package
are the two types
Thanks a lot guys, I figured it out
Is this official from unity?
Hello guys i have a question what is better to achive ground check on 2D OnCollisionEnter2D or OverlapCircle()?
don't crosspost. There's no reason to post in all the channels at once
ok
i will have a look into it.. my idea was to use spatial partitioning to check for nearby enemies but i have to figure out a way to handle this.. with animation i do not have any idea how to solve this but there is a ijobforanimation smth like that if i remember correctly.. will have a look into this aswell.. thanks for helping π
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
should work I believe...
I guess they're not actually transitive: https://forum.unity.com/threads/assembly-definition-and-transitive-dependencies.570853/
If that's the case, I feel like Unity needs to add a checkbox or something for automatically adding packages to custom assemblies.
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
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
something deep in the burst compiler Β―_(γ)_/Β―
it didn't expect to see an ILGenericParameter somewhere, whatever that means
maybe trying to call an unsupported C# method from burst code?
In theory not, but i will check again
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
Definitely seems like you hit a rate limit. Are you deleting players one by one? Is there a batch endpoint you could use instead?
I might be dumb here, but how can I create a bool Field with UI Toolkit??
You mean a toggle?
Aaaaah toggle that's the one!
Also, how can I make a field be clamped between two values? A Visual Element, FloatField for example
Something like this? https://forum.unity.com/threads/how-to-set-minimum-or-maximum-value-for-number-fields.1299195/#post-8230356
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
Is this for runtime?
this looks like a factory job to me, maybe not less code but more maintainable imo
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
how can i detect variables changing in inspector for non monobehavior classes ?
OnValidation should be called if the class is serialized. You'd need to keep track of it's previous value to see what exactly changed though.
NaughtyAttributes OnValueChange
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?
The standard solution is to create a custom drawer
What do you want to fix?
Nop, editor
Yeah, i know that with generics it gets "better"
Then why not just use a PropertyField?
But what I said hede
Are those available with Ui Toolkit?
Yes
Wow, thank god I'm new to Ui Toolkit, otherwise this would be unforgivable
I'm gonna check it, if that's the case, well, it solves everything
Ah, but I need a serialzied property
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 ?
ah no, i dont
well, Thank you!
maaaaaan this helps so much lol, saving so much time now
can have all the attributes directly
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
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
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
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
Why are the public fields Pascal case but the properties are not?
And why all the numbered suffixes
they are sample fields for easier understand when use this script from library
i commented it on header
this is the setupdata like player's health, damage , etc.., so i dont want to set it up in scripts.
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
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.
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
https://docs.unity3d.com/2023.2/Documentation/Manual/roslyn-analyzers.html
i'm currently following that to try out something
they are asking in step 7 Go to Asset Labels and open the Asset Labels sub-menu.
Were is that menu ?
Is it me or that doc is outdated ?
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 ?
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
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))
i don't think so, effectively nothing about the object changes until the end of the frame so if you really need it to stop existing immediately, you have to either SetActive(false) it at that point or use DestroyImmediate
Ugh. I was optimistic there was some trick I didn't know about :). Thanks
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
That's ... insanely difficult.
Going to contact every developer everywhere and ask them to set your flag?
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?
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 :))
disabling the object should also work
I guess the case I've seen many many time is ... when an object is destroyed, one or more of the invariatns it expects to be true is no longer true - e.g. it won't have a parent - and 99% of unity code doesn't check every possible thing on every line of code before exectuting it
Off the top of my head: OnDisable executes instantaneously - and OnTrigger isn't delivered to disabled objects - so yeah that would work?
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
i'm having a hard time imagining a case where that would be different using Destroy vs DestroyImmediate but disabling is the safer way if you're worried there's bugs in the third party code
(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)
it is i think, but normally it'd happen at the point it's actually destroyed, at the end of the frame
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.
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!
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)
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?
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
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?
Is there a way to change this value automatically before I build? So the built game has the correct version number while it runs.
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
ye I know about those two, but I don't think I can access PlayerSettings.bundleVersion inside a build to check the version since it's from the UnityEditor namespace
Is there a way to remove specific listeners from a UnityEvent via script?
You can use Application.version, which should contain the value of PlayerSettings.bundleVersion when the build is created.
If you have a reference to the listener you can remove it. It is however against the idea of the event pattern to unsubscribe outside the scope of the subscribing object. You may want to wrap such behavior in an type that provides explicit notifications of such changes.
only for listeners add via code, permanent listeners cannot be unsubscribed
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.
Thatβs a valid use case for reflection. Which allows you to do whatever you want.
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.
Is it possible to use System.Drawing.Common In unity?
afaik it's a WinForms only dll
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
not really, it should be possible but you would probably need to use reflection and dive into the Windows internals
