#archived-code-advanced

1 messages · Page 82 of 1

light falcon
#

I found RenamedFrom, but can't get it to work

regal lava
#

oh, yeah I think I remember seeing something like that

austere jewel
#

It works on fields. Renaming classes just works, because the meta file hasn't changed.
If you're using SerializeReference then there's some stuff if you moved namespaces/assemblies.

light falcon
#

sometimes if I rename a class and a file's name from inside visual studio, all gameobjects that had the file attached give a missing reference warning

austere jewel
#

Sounds like an issue with VS then

#

A functioning IDE should know you're working in Unity, and when you refactor a file or class name it should rename the associated meta file to match

light falcon
#

i think vs deletes/recreates the file

#

sometimes it works fine, sometimes it doesn't

#

it's 50/50

#

guess I'll manually fix it

#

is there a way to find all missing references in a project?

thin mesa
#
  1. this is not advanced. this is #💻┃code-beginner level at best
  2. see how to correctly share !code below
  3. and finally, where do you call start? because that isn't the same as Start which is what Unity will call automatically
thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

elder arrow
#

ok thanks

#

but there is no error in my code, it just doesn't replicate

sly grove
tiny pewter
#

then there are bugs on your code
btw code-beginner

elder arrow
#

Well, when I wrote it there, I posted it here because it didn't help. Thank you for warning me.

sly grove
elder arrow
#

Why

#

ı sent

sly grove
#

Only you can tell us why you didn't post your code properly

#

Stubbornness I guess?

elder arrow
#

I explained why the code did not work, I sent the picture, I wrote the code, what is the stubbornness in this?

#

If I make a mistake, you can give me advice to fix it.

tiny pewter
#

we can easily read the code blocks if your code is colored and indented

elder arrow
#

Okay, I'll post it properly to the beginner section again, then have a good day.

fresh goblet
#

Hi all. I want to check for inappropriate images within unity. Is there any sdk available for this?

tiny pewter
#

dont cross post and what are "inappropriate images"

dusty wigeon
fresh goblet
dusty wigeon
tiny pewter
#

you may need to learn how to send http request to google in c#
and it could be doen without unity

elder arrow
elder arrow
#

ok tanks

tough summit
#

Silly question. I have a private attribute of type Queue<T> named myparam in class A that I want to get updated by a public method member of class A when it is called by another class like Class B. When I pass the Queue<T> as an parameter from class B to the public method in class A that will then update the class A Queue<T> attribute, I found that I have to use Enqueue with a loop on the queue to properly pass the Queue values so they stay in memory. Otherwise just assigning the value such as this.myparam = param doesn't update the class A private attribute myparam when I check the queue with myparam.Count in the Update method of class A and myparam.Count returns 0. Is this expected with Queue<T> types and Enqueue is the only way to deal with this?

dusty wigeon
# tough summit Silly question. I have a private attribute of type Queue<T> named myparam in cla...

Your issue is not singular to Queue. It will happens with any type. Whenever you assign something for reference type variable, it changes what it points. All other reference to the same object will still points to the old object.

To solve the issue, you can wrap it in a container such as:

public class MyWrapper<T> 
{
  public Queue<T> MyQueue { get;set; }
}

However, ideally, you never want to pass Queue from a class to an other class. This is bad practice. You should encapsulate the Queue completly in the class and use the class. By example, adding function such as Clear or Reset. I suggest you read on encapsulation. https://www.sumologic.com/glossary/encapsulation/

ornate lance
#

This is a very specific question, and I'm not sure if this is the right place to ask it, but I have a problem with my game. I have designed a way to turn pixels into game objects so I can just create pixel art and turn it into a level, but the problem with this is that I can have thousands of game objects in one level, which makes the game run very slow. I spent the last couple of days learning how to use meshes, and I thought that I would be able to combine all of them together, but I got an error when I tried to run the coding stating: "ArgumentException: The number of vertices in the combined mesh (92424) exceeds the maximum supported vertex count (65535) of the UInt16 index format. Consider using the UInt32 IndexFormat for the combined mesh to increase the max vertex count." I am sure I could figure out how to use UInt32 like the error reccomends, but this made me realize that the mesh isn't just an outline of my level, it also has hundreds of lines between the blocks where the player could never reach. I am wondering if there is a way to to combine all these game objects into one, combine any that are directly touching, or even just combine any large squares into one game object. I am okay with using external tools, like Blender, provided I am able to do everything on runtime. If I need to write logic to procedurally check for objects that could be turned in to larger game objects, that's fine as well. I am relatively new to Unity, but I am willing to invest as much time and effort into this project as is needed. Any solutions, or even other avenues I could explore, would be incredible helpful.

dusty wigeon
# ornate lance This is a very specific question, and I'm not sure if this is the right place to...

What do you mean by:

I have designed a way to turn pixels into game objects so I can just create pixel art and turn it into a level

Also, what you seem to describe is static bashing. Usually, using 65535 vertices is more than enough because you would cull part of it anyway. However, if you want more you can simply increase the size of the index buffer. https://docs.unity3d.com/ScriptReference/Mesh-indexFormat.html

ornate lance
# dusty wigeon What do you mean by: > I have designed a way to turn pixels into game objects s...

Static batching seems to be exactly what I'm looking for. My script takes a specified png file and scans the image pixel-by-pixel, using the RGB value of the pixel to add a game object in that position. Here is the level I used that gave me this error, where black is the ground (each pixel is a game object) and green is where the player spawns (the resolution is low because its only 128 x 72 pixels):

dusty wigeon
ornate lance
# dusty wigeon I am going to ask if it is really necessary to have to make your level from a PN...

I feel like it's the most practical solution, but correct me if I'm wrong. I want to be able to make at least 100 levels, looking something like what I've drawn above. That picture took me 5 minutes to make and allowed me to play it instantly. Instead, if I had made the level in the unity editor, that level may have taken me at lest 20 minutes to make. In addition, the game objects would likely take up more space than a small png file, and the png allows me to easily change things like the size of the tiles and the player's starting location. Also, any details such as that stalactite would be very tedious to make using game objects, and I am planning on drawing over the level anyways, this map is only needed for collision. My game is a platformer with a pixelated feel, and I feel like this is the best way to be able to effeciently make new levels. Aside from the time and effort required to write the function to take the image and convert it to a level, this feel like the objectively better solution. If you disagree, could you let me know why? This is based off my opinion as a gamer and coding with little experience in Unity, so I'd love to know if there is a better way.

#

Also, thanks for letting me know about static batching. I just got it to work with my game, and my stress test that would have been almost 40,000 game objects before is now running with 2 batches and >150fps. (Edit: actually I zoomed the camera out and it dropped to 20fps, but compared to crashing unity before it's still an improvement.)
I also forgot to mention, I gave my computer to my friends who want to help me with development and they were able to make and play their own levels in under 20 minutes. Neither of them have any gaming, coding, or game development experience, but now they can just send me an image and play their level.

dusty wigeon
# ornate lance I feel like it's the most practical solution, but correct me if I'm wrong. I wan...
  • You already experiencing issue that you wouldn't experience if you follow a standard workflow. (It also required a parser which could be a source of potential bugs)
  • You are under utilizing the engine performance and ease of use (Tilemap by example).
  • You are increasing the burden/increasing complexity of the designer/coder by adding additional conversion between the game and the designed level. This will impact the maintainability of the game as it grows.
  • You are increasing the potential load time of your game by a decent factor. If you ever want to make your game supported on mobile, that could actually be a real issue.
  • You will have a harder time to implement GPI in the future. By example, defining the damage of your trap or the timing of those.
  • You might not reallize, but the usage of such technique will undermine the artistic capacity of your team as they will not see exactly what they are doing.
#

You should really stick to a more standard workflow. The issue might not be obvious to you, but as you develop you might find yourself in situation where the choice you did really hurts. Even more if you are just starting. You havent even see what Unity as to offer and you already discard half of it.

#

One of the absolute force of Unity is its capacity to create tools and design level. You have a whole array of editor tools you can do and utilize to make the whole process of designing your level as painless as possible.

ornate lance
#

I will keep this in mind, and I will probably end up switching, but I have a few problems with it. First, I am the only person working on the game with any coding, composing, or gaming experience. I don't have a team, and I don't expect to have one. This is mostly just a personal project that others may assist with, but one that I want to get to a game that I'd be happy playing personally and one that I expect could grow to be a popular indie game in the future. I am trying to make everything as easy as possible to create, as adding 20 minutes to every level creation could easily add up to a few months in the long run. My original intent with this program was to allow me to utilize Unity's level design capabilities through a program so specific that it would likely only work on my game with my knowledge, but that would speed up an aspect of the game substantially. I admit that I may have lost that after being forced to compromise by having each pixel be an individual block rather than having the entire level be one object, so I may use the program as a blueprint that I can then create objects over, rather than the level itself. You brought up some great points that really made me realize how inherently convoluted this system is, so thanks.

dusty wigeon
# ornate lance I will keep this in mind, and I will probably end up switching, but I have a few...

I am happy that you are able to think rationally about it. It is rare to see people being able to make part of things. That being said, I believe that the current way you are handling things would actually be worst whenever your game start to take depth. If you have not explore the Tilemap, I highly recommend to look at it because it is the suggested way of doing 2D pixel art platform games. There is even things such as https://learn.unity.com/tutorial/using-rule-tiles that enable you to quickly create a level without needing to deal with corner and other special case tiles yourself.

#

If you want to delves into generative content, you could also look at Wave Collapse Function which enable you to automatically generate content for your game. The background/art could be generate with this while only the core of your game is being done by your designer. Saving an enormous amount of time. https://robertheaton.com/2018/12/17/wavefunction-collapse-algorithm/

Robert Heaton

The Wavefunction Collapse Algorithm teaches your computer how to riff. The algorithm takes in an archetypical input, and produces procedurally-generated outputs that look like it.

ornate lance
next marsh
#

What would be a best-practice setup for handling multiple variables in a burst job? I was thinking of using a persistent nativearray of structs that contains all my relevant values (position, velocity, forces, mass), but then I remembered it's bad practice to make structs mutable. What's the best approach here?

#

How does burst handle reads and writes at the low level? In this particular use case, wouldn't the fields just be offsets to the index lookup in the NativeArray?

sly grove
next marsh
#

I've just heard people recommend against it in C# (largely in newer versions), so I wasn't sure how much of that carried over to Unity and Burst

sly grove
#

Whatever you're describing I'd wrap all that data up in one blittable struct and use a Native array of them

next marsh
#

Awesome that's what I was thinking but I wasn't sure

sly grove
#

There's nothing wrong with mutable structs in this context and that's pretty much the main tool for manipulating data in jobs

next marsh
#

That's a relief-- and just just to confirm Unity.Mathematics' types are blittable right? (float2, bool2, etc)

sly grove
#

Yes

next marsh
#

Are NativeArrays safe to write in parallel?

#

I.e. If I have a parallel job that reads the struct in each index through some var myValue = array[index], performs an operation with the data in said struct, then writes the updated fields back to the array array[index] = myValue, will that piss the bed?

austere jewel
next marsh
#

Awesome, cheers

#

Is there anything to look out for in particular when choosing a specific inner loop batch count for a parallel job?

#

Like some power of 2 etc

#

Something that cleanly divides the array

clever urchin
#

Depends on how you're working with the data

#

Thread count, accessing patterns, etc

#

Benchmark it and see

#

But if you're iterating over the array, performing some operation and then updating that same value, theres a high chance doing it in parallel would thrash your performance

#

Because you'd potentially be jumping around and invaliding cache lines

scenic forge
#

From my understanding, it's pretty much a magic parameter depending on what the job is actually doing, that you need to tweak by trial and error.

steel snow
#

any one good at math? My rotation function seems to not do what i was hoping it would do.

I am trying to rotate a point to the nearest X degrees relative to a directional vector.. this is what i tried:

/// <summary>
/// Rotate a point in discrete amounts relative to "axis"
/// eg: if axis is (0,0,1) (xz plane) and discreteAngle amount: 90, the point will be rotated in 90 degree increments (90,180,270..etc)
/// </summary>
public static void SnapToTangent(ref float3 pt, in float3 axis, float discreteAngle)
{
    // use radians
    discreteAngle = math.radians(discreteAngle);
    //get the signed angle between the point and the tangent vector (radians)
    var angle = signedAngle(pt, axis);
    //round the angle to the nearest discrete angle
    angle = math.round(angle / discreteAngle) * discreteAngle;

    // no rotation applied - skip the rest
    if (angle == 0)
        return;

    //rotate pt by angle
    pt = rotate(pt, angle);
    
    //using xz plane
    float signedAngle(in float3 a, in float3 b) => math.atan2(b.z, b.x) - math.atan2(a.z, a.x);
    float3 rotate(float3 a, float radians)
    {
        var sin = math.sin(radians);
        var cos = math.cos(radians);
        var x = a.x;
        var y = a.z; //i use xz plane
        a.x = x * cos - y * sin;
        a.z = x * sin + y * cos;
        return a;
    }
}

At the moment it doesn't snap at all

#

this gif shows it not snapping i used 90 degree angle with axis as (1,0,0)

fresh goblet
#

I want to refresh token for Cloud Vision API in Unity using api key or OAuth 2.0. Can we use Firebase for this or is it completely outside of Firebase? Need guidance.

steel snow
#

Did you read my code your example doesn't do anything related to my code

#

Also can quaternions be used in burst compiler?

#

I'm use the mathematics api

ivory notch
#

I made a mistake, I need to rewrite the code again.

sage radish
steel snow
#

I'll look into it though is my math even wrong to start with

sage radish
#

I just use quaternions to do my rotational math for me.

steel snow
#

Lol fair enough

dusty wigeon
#

Also, Unity code is:

// Returns the angle in degrees between /from/ and /to/. This is always the smallest
        [MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
        public static float Angle(Vector3 from, Vector3 to)
        {
            // sqrt(a) * sqrt(b) = sqrt(a * b) -- valid for real numbers
            float denominator = (float)Math.Sqrt(from.sqrMagnitude * to.sqrMagnitude);
            if (denominator < kEpsilonNormalSqrt)
                return 0F;

            float dot = Mathf.Clamp(Dot(from, to) / denominator, -1F, 1F);
            return ((float)Math.Acos(dot)) * Mathf.Rad2Deg;
        }

        // The smaller of the two possible angles between the two vectors is returned, therefore the result will never be greater than 180 degrees or smaller than -180 degrees.
        // If you imagine the from and to vectors as lines on a piece of paper, both originating from the same point, then the /axis/ vector would point up out of the paper.
        // The measured angle between the two vectors would be positive in a clockwise direction and negative in an anti-clockwise direction.
        [MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
        public static float SignedAngle(Vector3 from, Vector3 to, Vector3 axis)
        {
            float unsignedAngle = Angle(from, to);

            float cross_x = from.y * to.z - from.z * to.y;
            float cross_y = from.z * to.x - from.x * to.z;
            float cross_z = from.x * to.y - from.y * to.x;
            float sign = Mathf.Sign(axis.x * cross_x + axis.y * cross_y + axis.z * cross_z);
            return unsignedAngle * sign;
        }

https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector3.cs

steel snow
#

It works so I just find it way more performant over the fresh hell attempt unity chose lol

dusty wigeon
#

You need 3 points

steel snow
#

Have you tried it

dusty wigeon
#

I've done it multiple time. It never stick with me though always need to do some trial and error.

steel snow
#

I'm not at the pc to show it in action at the moment but when I tested it returns signed angle betwen 0 and pi

dusty wigeon
steel snow
#

Nor me but my math on paper led me to that solution

dusty wigeon
#

Did you logs the result or just assuming ?

steel snow
#

Yeh I was logging at the time

#

I'll test again when I'm home

#

Just to be extra sure

#

I didn't like the messy solution unity came up with

dusty wigeon
#

Because I am like 95% sure that you want only a single math.tan2 and 3 points.

steel snow
#

Why 3

#

What would the third point be

dusty wigeon
#

Because you need to have both vector ?

steel snow
#

You mean pt-origin and the axis vector

dusty wigeon
steel snow
#

I'll retest when I'm home

dusty wigeon
#

I see how the formula could work to find the angle. However, I still fail to find the required component (3 points or vector).

steel snow
#

@dusty wigeon

#

i got it working

#

was passing in the wrong vector to the rotate function

#

the signed angle function works fine though

tulip stump
#

Hello everyone, I'm trying to make a pipe system for my 2D game, and I have the following problem: What is the best way to find if an object is connected to a specific object.

regal lava
#

Each object can contain a list of each connected object, and having that reference to that exact object you can then check if the list is empty or not.

tulip stump
#

wouldn't that be extremely slow?

#

I'm making this for a large scale multiplayer game, so performance would be good

tiny pewter
#

graph problem
you need a sparse set for storing the children

regal lava
#

Eh, I mean if you just need to know all parts of a single object, I don't see why it would.

#

It also depends how much would be contained in that list, and seeing your graph you seem to have a total of 4

tiny pewter
#

oh you may need a disjoint set

tulip stump
#

I see

tiny pewter
#

but disjoint set not support disconnect, not work if the pipe can be removed

regal lava
#

What you should be asking is what search algorithm you should be using to determine if a pipe is fully connected to the end

tulip stump
#

Yeah that's what I meant by that

tiny pewter
#

run bfs

regal lava
#

Like some sort of binary search, but really the best way to tackle this problem is to cache your positions

#

I guess it depends on how you want to design it. Now I'm kinda interested in making a pipe game haha

tulip stump
tiny pewter
#

you may run a star on it btw, it maybe faster than bfs, but heuristic is quite difficuly to define since you dont know how many gameobjects left (it can be treated as a graph of gameobject connects to other) to reach the target

tulip stump
#

I thought about A star, but that might break if there are many sources closer to the start than the actual source it's conected to, but I don't know

#

I'll try Bfs first

regal lava
#

Also that flood fill alg if you want to keep with the theme of plumbing ;)

#

bfs is honestly fine though, you're only checking this once per part placed

tiny pewter
#

or bfs from target and source, slightly faster than one way bfs

white pulsar
#

i really dont want to cross post since that goes against the rules, so might as well link it here since i think what i'm asking over at #archived-code-general message is too advanced for the people who regularly check there

#

nevermind, i got it to work, posting result on the channel

white pulsar
#

nevermind to my nevermind, it still doesnt work isaac_tired

tough summit
tiny pewter
#

Attribute should be used by reflection?

honest hull
#

Hey can traceinline for unity raytracing only do simple visability tests or can it return shading data?

proven storm
#

Is there a way to not get reload script assemblies when I go from VSStudio to Unity? It does it even if I change a space in my code. I disabvled reload scene so it's only when I switch over and it takes like a minute each time

upbeat path
versed coyote
#

Is there a debugging feature/method where I can see what scripts are mutating the transform of a selected game object? I have an issue where I can't figure out what script is actually resetting the GameObject's position

novel stump
#

Hey can anyone help me with a rigidbody problem? I’m new to unity and I’m trying to make my rigidbody physics on my player work in the air so that they can maintain velocity and change the direction without accelerating. I can basically simplify the problem to this: The player is moving with a velocity with 0 drag and 0 friction, so they will just keep going if they don’t press anything. Assume the player already has velocity so they can’t speed up at all, just move around and maintain their current velocity (or stop if they wanted to). If they look in the direction of their velocity and A/D, they should turn, but maintain the same velocity. I also need to do this without manually setting the velocity, because that messes up other stuff, I just want to work with forces. The result should be that if the player is travelling forward, and presses D, they would slowly move right, making a curve until eventually they were travelling right with the same velocity as before.

#

here's an example, this is what would happen if the player is travelling forwards (north) and pressed D to go left (east)

flint sage
#

Add torque?

novel stump
#

oh ill take a look at that

#

could I use torque along with the player's current forces? @flint sage

flint sage
#

Yeah\

novel stump
#

Wouldn't that rotate the player as well? I just want to change their velocity. Like in the picture I sent, the player would still be looking north at the end if they hadn't moved their mouse

flint sage
#

Oh

obsidian glade
novel stump
#

like

#

across the sun

#

tangential

tiny pewter
#

circular motion

novel stump
#

but that relies on gravity from the sun, which in my scenario would mean gravity around an object to the right of the player, but depending on their input, which doesn't really make sense

obsidian glade
#

it doesn't quite, but the premise isn't too far off - the only direction you can apply force to turn without changing the velocity magnitude of velocity is perpendicular to your current motion vector

#

like a planet orbiting, the force is applied directly towards the point it's rotating around

novel stump
#

Basically I know that any force I add will need to be balanced, otherwise the player can accelerate which is not supposed to happen. I just cant find a way to balance the forces properly

novel stump
#

which I don't want. They should just maintain current velocity

obsidian glade
#

exactly - you need to apply the force perpendicular to the current direction of motion, at each point in time

tiny pewter
#

actually your velocity is changed that means there is some acceleration

#

ie dv

novel stump
#

yeah true I meant the magnitude increasing i suppose

tiny pewter
#

btw adding acceleration adding perpendicular to v have no work done iirc

novel stump
tiny pewter
#

that mean ||v|| will not increase

obsidian glade
novel stump
obsidian glade
#

(or add a check to stop adding the force when you're moving right already)

obsidian glade
novel stump
#

so you are saying that I don't need to add any force that acts against the player? I thought if I only add forces it will increase speed

novel stump
#

just realised

novel stump
tiny pewter
#

so you add acceleration perpendicular to v

novel stump
#

and then what if the player was holding A and D instead of just D?

#

still perpendicular? and just less force

tiny pewter
#

input handling is question for you

novel stump
#

so the force should stop when the player's velocity = their desired velocity depending on input

novel stump
#

if the player pressed S then of course they should slow down and stop basically. but if my forces are only perpendicular to current vector of motion how is that possible

#

I'm not talking about input handling but like their desired velocity basically (which is based on their inputs)

#

thanks for the help btw everyone

tiny pewter
#

actually if the ||v|| downs then the acceleration have to be decreased too to maintain the original radius

novel stump
#

this has had me busy for 2 days with 0 progress

#

i'm confused on how that would work in other situations tho

obsidian glade
#

intuitively I think something like forceFactor = 1 - dot([velocity vector you want to end up with], [current velocity vector]) would work reasonably well

#

(normalised vectors)

#

or simply a check to skip applying force when the dot is approximately 1

novel stump
#

what does the dot mean? sry

tiny pewter
#

i think you have to keep the acceleration vector magnitude until v dot original v is 0, otherwise the dv will keep decreasing in your case and it cannot maintain constant radius

obsidian glade
#

yeah, it depends what kind of turning motion is desired, I think gradually decreasing it might feel more natural, but either works

smoky glade
#

Hi all
I'm getting errors only in builds. It's from a pool system complaining about invalid cast

                    ret = (T)Instantiate(prefab);
                }
                catch(Exception e)
                {
                    Debug.Log($"{prefab.name} {prefab.GetType()} cast invalid? {e.Message}");
                }```
Logs out `WingTip_L UnityEngine.GameObject cast invalid? Specified cast is not valid.`
Which is weird since i call it like so:
`ModelPrefab go = obj.PoolTake<ModelPrefab>(prefab);`

Again this is only in builds. Maybe someone can also explain why some things behave differently in builds?
novel stump
#

I still don't understand what direction to apply the force in different scenarios @obsidian glade

#

maybe when the player presses S it just adds a backwards force? along with the perpendicular for side to side

obsidian glade
upbeat path
novel stump
#

Okay I'm gonna give that all a try. Thanks so much for the help @obsidian glade and the other dude I dont know how to @ you but thanks

smoky glade
#

ModelPrefab MakeModel(ModelPrefab prefab, Transform location, Vector3 size)

upbeat path
smoky glade
#

That's why that log doesn't make sense

#

It doesn't complain anything in editor

novel stump
#

@obsidian glade I'm just starting to test this by adding a force perpendicular to current velocity to see how it looks and make sure it doesn't increase speed, and it's not working, do you know why? I'll send my code

#

It's just supposed to be perpendicular in any direction to test if it increases speed, so it's not important which way it actually is, I'll do that after

novel stump
#

got it nvm

smoky glade
#

How is this not a bug?

        {
            Debug.Log($"Make body model {bodyInfo.defaultItem.name} {bodyInfo.defaultItem.GetType()} {targetSlot}");
            ModelPrefab et = MakeModel(bodyInfo.defaultItem, info.location, part.scaleBody);```
Logs
`Make body model WingTip_L UnityEngine.GameObject 33`
How come in builds, GameObject gets confused with a MB/Component?
real blaze
#

hi. I think my Android build caches (or temp files) are corrupted. how can I remove the appropriate cache (or temp file)?

  • it's taking tens of minutes for every Android IL2CPP build. this used to be way less than that, but today suddenly it started getting slow. The majority of this duration (~90%) is taken by NdkObjCopy
sage radish
real blaze
#

yup, just checked, 504GB free

#

Unity Editor, project and build path are all in this SSD (nvme)

#

I remember neither CPU nor Disk utilization in task manager would appear anywhere near 100%. something else appears to be the bottleneck

edgy sphinx
#

question, with a NativeArray<T>, it's possible to retrieve element references through ref UnsafeUtility.ArrayElementAsRef<T>(array.GetUnsafePtr(), index). is there a way to do the same with NativeHashMap<int, T> instead of NativeArray<T>?

fickle tinsel
#

Nice. I think I've figured out how to write an automated test for shader code.

❤️ automated testing in video games

rough sky
#

Does anyone know why the GPU might take 60ms on the graph, but only display 7ms on the hierarchy view?

#

Where would the other 50ms go?

steel snow
#

does any one know what Instantiate(meshObj) does under the hood? im hoping unity is smart enough that it just a nice memory copy but i have no way to know

livid kraken
#

What does a “nice memory copy” mean

untold moth
#

Using platform deticated GPU profiling tools might provide better info.

untold moth
steel snow
#

ignore the word nice

#

some people copy a mesh by grabbing the arrays which is very allocy

#

so im curious if unity does a mem copy or not

untold moth
#

You can't copy something without mem copy or similar low level command. When people are "grabbing the arrays" they are doing a mem copy as well somewhere on the low level.

tiny pewter
#

Memcpy?

untold moth
#

Besides, you can just copy the whole thing in one go if you're dealing with contiguous memory block, but most objects are not a contiguous memory block, so you can't just copy them in one go.

livid kraken
livid kraken
#

Usually I get hit with the old failed to present swapchain

steel snow
livid kraken
#

Well if you have to make copies they are going to take up memory. Usually I find that memory optimisation is the very very last step I do since modern systems have an abundance of memory.

sand crescent
#

Hello. Is there a way to hide codes in the shader just like putting #region in C# script?

untold moth
stuck plinth
untold moth
solar condor
#

About the URP Sample Buffer - I'm trying to make my own post processing thing by following this tutorial: (it's timestamped to where he adds in the URP Sample Buffer)
https://youtu.be/9fa4uFm1eCE?si=ecwRgXs94eIy9LWs&t=1000

And I can see the logic in his shader setup, you want to add the values from the bloomed render texture into the "scene render texture" or whatever it's called at the time - but... I noticed I get a fully black screen when I try to visualize the URP Sample Buffer by itself - which points to... "Well, why does my node not give me the current texture?"

If anyone would know how to fix this, I'd greatly appreciate the help :v
Image
Image
Note - this isn't only a fullscreen pass - this stuff involved a lot of blit operations managed by code, and i don't fully understand those, so that could be where the problem lies at

(Deleting the duplicate from #archived-shaders, I didn't realize which channel I was at, initially, lol)

#

tldr; My URP sample buffer node is outputting full black, when I believe it shouldn't - how can I find my mistake?

solar condor
#

Swapped out URP Sample Buffer to Scene Colour and... that's almost what I expected - but its ignoring several blit operations I made by code prior to applying my ben day dots

solar condor
#

I ended up using a completely different shader setup, skipped the blur pass and worked it all through HLSL

rough sky
#

Thank you

rough sky
#

But also, why would the tri count spike so randomly?

#

It's so still at 10 triangles the rest of the time

rough sky
#

Ok so I've been trawling the forums and I found out that multiple cameras in URP have a huge memory problem due to constant releasing of render textures

#

Does anyone else have this bug?

sage radish
# rough sky Does anyone else have this bug?

I haven't had this issue but I've googled it a bit, and it looks like Unity has a texture pool to avoid allocation, but it defaults to a max size of 32 textures that can be "stale" at a time, as in unused but kept in memory. After this, it starts deallocating the textures, so they will need to be allocated again next frame.

Luckily, you can easily change this limit with the RenderingUtils.SetMaxRTHandlePoolCapacity(int capacity) method. It doesn't appear to be used by anything, like a setting in the URP asset which would be ideal, but it's easy enough to make a script that sets this value at startup.

#

Changing the value will deallocate the whole pool and reallocate everything next frame, so you should only set it at startup or between loading.

#

You'll want to raise this number until you see the allocations stop.

#

But obviously more video memory will be in use as a consequence.

sonic forge
#

hello guys, I'd like to create a procedural spawning system for a large terrain. I need to place objects on textures, but wonder how should I approach it.
First I created noise on texture then colored it above some threshold to green. Then I done such thing:
int textureWidth = textureToSpawnOn.width;
int textureHeight = textureToSpawnOn.height;
for (int x = 0; x < textureWidth; x++)
{
for (int y = 0; y < textureHeight; y++)
{
Color pixelColor = textureToSpawnOn.GetPixel(x, y);
// Check if the pixel color is green
if (pixelColor == Color.green)
{
// TODO: Find each pixel in worldspace (or localspace)
Vector3 spawnPosition =
}
}
}
...but can't find a way to locate green pixels in this approach. After I thought about it, maybe I could do that on a plane, but not a real terrain with a heightmap and so variable height I guess.
How should I do it efficiently? What I mean is having a texture mask with some colors (rgba) that would define areas to spawn specific objects

next marsh
#

You can potentially cut out the texture middle-man depending on how you're generating it

#

How are you generating noise?

fallow valve
#

otherwise just pour around 5 gallons of pepsi inside of your pc or ontop of whatever you're using

upbeat path
#

<@&502884371011731486> Shitposting

fallow valve
upbeat path
#

Actually swearing is allowed on this server as long as it is not gratuitous, which in your case it most definitely isn't

fallow valve
#

my views are to do as i earlier said

#

its only my opinion and i am not a proffesional

#

if what i said was in any way false or offended anyone i deeply apologize

humble leaf
#

@fallow valve Stop posting nonsense, thanks.

fallow valve
#

fr fr

sonic forge
hazy epoch
#

Can anybody offer some insight on this one. I'm using Cinemachine. In the following code snippet, I want the fade camera to take priority, fade out, then set the next camera to have the best priority (once the fade camera is back to 0). The problem I'm having is that the currentCamera and cameraToSwitchTo don't do their blend, before the FadeIn task starts. The blend doesn't happen until after FadeIn is complete, despite the fact that the "old" currentCamera IsLive.

public async Task SwitchToCamera(CinemachineVirtualCamera cameraToSwitchTo)
{
    currentCamera.Priority = 0;

    await FadeOut();

    cameraToSwitchTo.Priority = 1;

    do
    {
        await Task.Yield();
    }
    while (CinemachineCore.Instance.IsLive(currentCamera));


    currentCamera = cameraToSwitchTo;

    await FadeIn();
}

public async Task FadeOut()
{
    fadeCamera.Priority = 10;

    elapsedFadeTime = 0.0f;

    do
    {
        elapsedFadeTime += Time.deltaTime;
        fadeStoryboard.m_Alpha = Mathf.Clamp01(elapsedFadeTime / fadeDuration);

        await Task.Yield();
    }
    while (elapsedFadeTime < fadeDuration);
}
public async Task FadeIn()
{
    elapsedFadeTime = 0.0f;

    do
    {
        elapsedFadeTime += Time.deltaTime;
        fadeStoryboard.m_Alpha = 1.0f - Mathf.Clamp01(elapsedFadeTime / fadeDuration);

        await Task.Yield();
    }
    while (elapsedFadeTime < fadeDuration);

    fadeCamera.Priority = 0;
}
vague quail
#

Hello guys, I have a question about code efficiency:
in this example I'm listing a dictionary of periodic table's elements, all 118.
someone knows a better way to create this kind of database?

A less expensive in reading and access?

#
public class ElementsManager : MonoBehaviour
{
    Dictionary<string, BaseElement> BaseElements = new Dictionary<string, BaseElement>
    {
        ["H"] = new BaseElement(1, 0.1f, 14f, 0.09f, 75f),   // Hydrogen
        ["He"] = new BaseElement(2, 0.2f, 10f, 0.08f, 85f),  // Elium
       
    };

    // other methods and logics
}
thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

tiny pewter
#

there is no way except you hard code all the names of each element (since i think there is no function that given the atomic number it returns the name of the element), perhap you can have file io (read from json) but you still have to hard "code" the names

vague quail
#

it's not a problem hard coding all, my question is related on readability from machine and time expenses

#

i will hard code all the informations and then commenting with human details

#

so is the dictionary the best way to do this?

tiny pewter
#

if your game use atomic number then i think you can use array, but no one (at least from those who are not chemistry major) will remember atomic number<->element number name conversion so use dictionary is fine

wraith storm
vague quail
#

I hardcoded all infos in public static readonly

#

the CSV is more slowly compared to hardcoded

#

thanks anyway, this will be useful for some reference for electrons etc

wraith storm
vague quail
#

I'm creating a RTS based on periodic table, time to turn the table on RTS gaming 😄

wraith storm
#

Sounds fun 🙂

strange ice
#

So I've created this ability where the player can change the direction of their gravity to whichever way they face when the button is pressed

#

That part works fine. But I want to make it so it will rotate the player so the bottom is pointing in the direction of the gravity so they can walk on the walls and ceilings.

I've tried a few things already but haven't gotten it working well

#

I have a Vector3 that is what sets the global direction of the gravity. I just need to know how to point the feet of the player in that direction. Also I plan on having it smoothly lerp the rotation after I get the basic thing working

umbral trail
#

Using TestRunnerApi in 2021, registering some ICallbacks but they don't seem to be getting called even though it's an edit mode test run, what else could be the problem? I can see the tests have run in the test runner window.

umbral trail
#

Ah, what the docs neglect to mention is it's completely asynchronous so tearing it down immediately after means I get no callbacks 🤦‍♂️

raw locust
#

Hey, quick question that's very important right now.

While using compute shaders with render texture 24bit depth, RFloat format it works flawlessly on android api level 28 (android 9), but on api 24 (adnroid 7) it does not work. Both devices with supported GLES 3. Any change in format or depth results in rendering fragment of screen instead. Compute uses RWTexture2D<float>. Output written to RWTexture in my case is in range of float 0~1

What can i change to make it run?

tall ferry
honest hull
#

Hey so is there any way I can either compress or emulate compression of a rendertexture? I need it because I have to be able to create a 16k atlas on the fly on the GPU, which means I need to use a compute shader to create it, but even at rgba32 that rendertexture is 1 gig, which is just too much... I know they cant really be compressed in the sense texture2ds can be, so do I have any other options?(This is all because unity doesnt support bindless, so my only way of sending an unknown amount of texture to a compute shader at once is to pack them into a single huge atlas)

untold moth
honest hull
#

I need to be able to do it frequently, without causing a massive stutter
And yeah the amount of vram

untold moth
honest hull
#

Whenever an object is removed or added from the scene I need to add its textures to the atlas

#

So that I can render it from the compute shader, which means I need it’s texture

untold moth
#

Why not load it at the game/level load time?

#

Also, if it's one object, surely you don't need to upload the whole 16k atlas again?

#

Not to mention that I'm a bit sceptical about rendering from the compute shader🤔

#

Donno your use case though.

honest hull
# untold moth Donno your use case though.

Pathtracing in shader, I need to remake the atlas to include the new texture
And it can’t be constant as I don’t know what objects may be added or removed over the lifetime of the scene

untold moth
honest hull
#

So I am trying to find another way that doesn’t require cpu side to reduce vram

untold moth
#

So it is a matter of vram consumption after all?
I'm not sure if there are ways to compress the texture on the GPU. And there's probably no way to compress a render texture either, so you'll probably need to think of something else.

honest hull
#

Hmmmmm

untold moth
#

Maybe someone else has a better idea. What you do requires some intimate knowledge of graphics API.
There are probably more options with low level API.

honest hull
#

Uuggghhh ok
There’s not really any way to compress it tho

#

Yeah I know, but unity doesn’t expose most of the really useful things you only sometimes need

rough sky
#

As a way of optimising my three camera set up, I am using one camera, and every frame setting the culling masks and target texture by code and calling Camera.Render() to invoke the effect manually for each of the two extra cameras.

However, camera.render() seems to have more attached to it than just rendering, for instance it invokes all the attached render functions. Is there a more optimised Camera.render() that bypasses the extra things like this?

sly palm
#

Ok here's a thing. I have a project in which I use Addressables to load content scenes into my main application. The content scenes contain slideshows and videos. Now, I want to reference these slides and videos by URL. To make it easier for content creators to place the videos and slides in the scene, I created a proxy component that just takes an array of Texture2D or Video files.

I then have an editor script that takes the arrays and uploads the videos from the Unity project onto the data server.

BUT as the proxy component still references the array, the Addressable bundle also contains these videos.

Does anyone have any tips how I can keep that UX for the content creators to just drag and drop their textures into a proxy component in the scene?

#

Here's an example of my proxy component. It sits on a scaled Quad positioned in the scene where the slideshow should be.

earnest heron
#

Hey guys,
I have a question about VContainer.

How can I have LifetimeScope on a prefab when using IObjectResolver.Instantiate ?
Looks like when I use this method, actually it registers LifetimeScope component too (Because of registering the root gameObject and all the descendents) and it makes an error on the parent which calls instantiating.

#

The error:

VContainerException: Failed to resolve System.Object : No such registration of type: Character.CharacterContext
VContainer.Internal.ReflectionInjector.InjectMethods (System.Object obj, VContainer.IObjectResolver resolver, System.Collections.Generic.IReadOnlyList`1[T] parameters) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Internal/ReflectionInjector.cs:106)
VContainer.Internal.ReflectionInjector.Inject (System.Object instance, VContainer.IObjectResolver resolver, System.Collections.Generic.IReadOnlyList`1[T] parameters) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Internal/ReflectionInjector.cs:28)
VContainer.Container.Inject (System.Object instance) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Container.cs:220)
VContainer.Unity.ObjectResolverUnityExtensions.<InjectGameObject>g__InjectGameObjectRecursive|0_0 (UnityEngine.GameObject current, VContainer.Unity.ObjectResolverUnityExtensions+<>c__DisplayClass0_0& ) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Unity/ObjectResolverUnityExtensions.cs:21)
VContainer.Unity.ObjectResolverUnityExtensions.InjectGameObject (VContainer.IObjectResolver resolver, UnityEngine.GameObject gameObject) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Unity/ObjectResolverUnityExtensions.cs:34)
VContainer.Unity.ObjectResolverUnityExtensions.InjectUnityEngineObject[T] (VContainer.IObjectResolver resolver, T instance) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Unity/ObjectResolverUnityExtensions.cs:130)
VContainer.Unity.ObjectResolverUnityExtensions.Instantiate[T] (VContainer.IObjectResolver resolver, T prefab, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation, UnityEngine.Transform parent) (at ./Library/PackageCache/jp.hadashikick.vcontainer@af7bd4ecab/Runtime/Unity/ObjectResolverUnityExtensions.cs:117)
narrow coral
#

I am going to reask a question here because I realize it's more advanced then general. How can I do mesh subtraction during runtime?

earnest heron
#

This is a partial screenshot from the prefab I'm talking about. (Gameobjects children are not included):

sage radish
stuck plinth
narrow coral
compact ingot
earnest heron
compact ingot
# earnest heron Actually I had a hard time since I've been trying to convert Zenject to VContain...

Need to think about it. At a Minimum it adds complexity due to nesting, and while that may not be a problem in some cases it could be very confusing in others, especially absent clear documentation in the codebase how they are to be handled. Containers in unity typically get very dangerous in teams where not everyone is an expert in keeping things simple and the benefits of DI. So if you extrapolate what you try to do to a team situation, you will probably find reasons for VContainers opinions. I think by and large DI with vcontainer is easiest if you avoid MonoBehaviour controlled lifetime scopes as much as possible.

#

Anyway, nested scopes shouldn’t cause issues.

#

Resolving dependencies by directly accessing the container would be quite wrong (in principle) and vc doesn’t like it.

midnight terrace
#

So i am learning python# ++ what do you think of my code?

#

It IS spelled corecctly👍

half swan
#

Ah, trollin got me lol. That's what happens when I look at only one line barely

tawny stag
#

I have a project I am building for webgl. I have a struct for my UserData I am converting to a JSON and sending out via the JavasScript external interaface. Thing thing is with UnityEngine.JsonUtility.ToJson(data); it creates a json for the enitre structure. I already wrote using reflection a utility to create Dictionary<string, object> that includes only the changed values. But unity cannot serialize that to a JSON. I tried using this NewtonSoft jsonConvert.SerializeObject() but that library added like 2MB + to my builds. Does anyone know of any alternatives that are much lighter? or a simpler solution.

earnest heron
# compact ingot Need to think about it. At a Minimum it adds complexity due to nesting, and whil...

Thanks.
In my case it doesn't look very complicated. Each player (2 players in total as a local coop game) and each has 2 characters. Characters have DI for own components and their children. Just instead of creating them in facade class I inject them by VContainer.
Also no direct resolving.
Probably I should check non-MonoBehaviour LifetimeScope. But I don't get why gameObject injection doesn't ignore LifetimeScope. I think the issue I have is because of that.

stuck plinth
compact ingot
# earnest heron Thanks. In my case it doesn't look very complicated. Each player (2 players in t...

Well, a DI container only really works well if it handles all instantiating statically (I.e. all dependencies can be resolved at any time without any late registration once the composition root was built). This means no object can be allowed to survive its parent scope or init/install before it’s parent has finished installation. Manually instantiated objects (like you often have in a game) aren’t it’s forte.

tawny stag
honest hull
#

is there any way to make it so I keep the sampling speed of a texture2d but in a rendertexture? I REALLY dont want the extra 2 gigs of VRAM/RAM from the 16k texture2d atlas, and the amount of time it takes for creating that new texture, and then doing Graphics.CopyTexture from the rendertexture to the texture2d(I make the atlas on the GPU because its MUCH faster)

west scarab
honest hull
#

in a compute shader, incoherently

west scarab
#

I'm surprised it's 4 faster

honest hull
#

mhmmmm

#

it succkkksss

#

means I need to still do the render texture things, copy to a texture2d(which means its now a 2 gig texture) and then release the rendertexture

honest hull
#

anything I can really do?

west scarab
honest hull
#

rgba32, so 8 bytes per component

#

thats the smallest I could go for an albedo tex

west scarab
#

Does your texture2d have mipmaps?

honest hull
#

no

west scarab
#

Is it compressed?

honest hull
#

cant compress it
not only would that cause a large stutter whenever I need to remake the atlas, I need the data thats on the GPU (from using Graphics.CopyTexture from rendertexture to texture2d) to be on the CPU otherwise it clears it

west scarab
#

I'm just trying to figure out where the performance difference is coming from

honest hull
#

ohhhhh for that

#

idk
I think its just in general incoherency
neighboring pixels have basically no chance of sampling nearby pixels on the texture

#

and its a 16k texture

west scarab
#

Are your rendertexture and texture2d the same memory size overall? I assume they have the same resolution

honest hull
#

yes
both are 1 gig in inspector

#

yes theres a lot of empty space there but thats mostly cuz I dont have enough textures in current scene to fully fill it, but in most scenes this is not the case

west scarab
#

No idea what the issue is. Only thing I can imagine is they are stored differently in memory somehow making it slower to read from a rendertexture than a texture2d due to cache misses

honest hull
#

yeah 99% sure they are...

west scarab
#

Then there's probably not much you can do. RTs are probably optimized for writing, not for reading

honest hull
#

uuuuggghhh ok
guess I have to eat the huge ass RAM/VRAM cost for the texture2d then since I dont think I can compact it any smaller?

dusty wigeon
honest hull
#

yes as its an atlas that contains all textures in the scene, as thats the ONLY way to send an unknown amount of textures to a compute shader at once

#

I hate it but its the workaround I know of for no bindless

dusty wigeon
#

Does not really seem viable

honest hull
#

no other option

dusty wigeon
#

You could try to descrribe what you are trying to do.

#

Maybe someone has an idea

honest hull
#

ok
Basically what I do is I take all the albedo textures of all objects in the scene and aggregate them into a single atlas(theres a bunch of other stuff I do to allow me to access them nicely, but thats not important to this I dont think), as this is the only way to send an unknown amount of textures to a compute shader at once in unity
This single atlas needs to be able to be completely remade in a single frame without massive stuttering so I build the atlas on the GPU with a compute shader
Thus that means that it needs to be a rendertexture, however rendertextures of these sizes are horribly slow to sample for me, so I need to turn it into a texture2D which I do
So my resulting issues at this point is that this resulting texture2D takes up 1 gigabyte on the GPU and 1 gigabyte on the CPU, which I really really dont like...

dusty wigeon
#

Basically what I do is I take all the albedo textures of all objects in the scene and aggregate them into a single atlas

This is not scalable in any way. You are going to hit a wall really fast.

honest hull
#

oh believe me I already have

dusty wigeon
#

Why you want to do that ?

honest hull
#

because there is no other option
no bindless
texture arrays are out because they only allow same sized textures
etc.

dusty wigeon
#

What is the requirement that force you to do that ?

#

There is a reason why you want to do that.

honest hull
#

that I need ALLL these textures in a compute shader

dusty wigeon
#

Why ?

#

What you are doing in the compute shader

honest hull
#

beacuse what I am making is a renderer that runs in a compute shader

#

full pathtracing

dusty wigeon
#

I have no knowledge of how pathtracing should work. However, base on the fact that HDRP does pathtracing, I am pretty sure there is other alternative.

honest hull
#

not for what im doing

#

a pathtracer that doesnt use RT cores that runs in builtin, hdrp, urp, etc.

honest hull
#

yes I know about this

misty glade
#

I have an AudioSource that I'm playing a "combo" sound effect on. Since I'm orchestrating it outside of my audio service, I have a delay on it with a DOVirtual tween:

        public static void PlayComboClip(AudioClip clip, float delay) => Instance.PlayComboClipInternal(clip, delay);
        private void PlayComboClipInternal(AudioClip clip, float delay)
        {
            _comboClipTween?.Kill();
            _comboClipTween = DOVirtual.DelayedCall(delay, () => PlayComboClipImmediate(clip)).Play();
        }

        private void PlayComboClipImmediate(AudioClip clip)
        {
            if (_comboSfxSource.isPlaying) _comboSfxSource.Stop();
            _comboSfxSource.PlayOneShot(clip);
        }

It works fine but it's a little abrupt - I'm thinking maybe I want to fade it for a tiny amount of time if it's already playing before playing the next one?

Is there something in UnityEngine.AudioSource that could maybe assist with this? I can't really easily insert a new callback into the tween (since it's already playing)..

#

the combo sounds can be 2-3 sec long, but moves can be done pretty rapidly - like 0.5sec - so they overlap in a kind of nasty way (without the above)

dusty wigeon
misty glade
#

Also a lot of legwork for this.. feels like something should be in AudioSource but I didn't see anything

#

I could maybe also create audio sources for these SFX at runtime and just tell themselves to fade and destroy themselves after playing, but I think that's probably going to incur other problems

#

seems like it works well enough?

sly grove
misty glade
#

I'm not familiar with that.. that's an out of the box component?

#

Hm.. this is a lot of knobs and dials, but maybe "ducking" is what I want

dusty wigeon
misty glade
#

Well see that's where you got me.. none of my games are respectable. 😛

dusty wigeon
#

😦

misty glade
#

But I'll read through this.. it might be just what I need since I rolled my own for the past few projects

honest hull
polar orchid
#

Anyone know how I would go about calling a function from an instantiated component in unity from a script outside unity?

sly grove
#

I don't see how "from a script outside unity" is really relevant to the question

#

to call a function from an instantiated component, simply save a reference to it and call the function on the reference

#

for example:

public MyScript myPrefab; // assign in the inspector
MyScript theInstance;

void SpawnTheThing() {
  theInstance = Instantiate(myPrefab);
}

void DoTheThing() {
  theInstance.Whatever();
}```
polar orchid
#

I have a process running outside of unity that'l need to call specific functions within the unity process

sly grove
#

I know that

#

you said that

#

That part isn't relevant to the "function from an instantiated component in unity" part though

polar orchid
#

Well I cant just call instantiate in another process can I?

sly grove
#

No but I didn't know which part of the problem you solved

#

and which part you wanted help with

#

I assumed the "call a function from another process" was the part you already knew how to do

#

and you didn't know how to call a function on an instantiated object

polar orchid
#

Oh, no lmao the opposite, that's the hard part for me calling a function from a different process

sly grove
#

Ok, your extraneous details confused me.
Your options depend on what platform you're on

polar orchid
#

Preferably desktop, WebGL can also work as I'm pretty sure it has a JS hook api

scenic forge
#

You need to establish some sort of interprocess communication, doesn't matter what.

sly grove
polar orchid
#

Yeah ideally on desktop I can get some sort of interprocess communication, do you have any idea on how I can achieve this?

polar orchid
#

?

sly grove
#

TCP is one pretty universal option

polar orchid
#

as in establish some sort of websocket connection?

sly grove
#

not websockets

#

just a TCP connection

#

websockets implies web browsers

polar orchid
#

ahh, didn't know, had a multiplayer game that used websockets as a transport but it worked both in webgl and in a desktop build. But yeah the TCP connection seems like a good idea

#

Thanks :)

sly grove
#

websockets is HTTP based which adds a lot of complexity

#

TCP is a lot simpler

polar orchid
#

Ahh great, would you happen to be able to point to where I can find out more about tcp connections in unity, or would just googling "Unity tcp connection" suffice

sly grove
#

Unity is basically not relevant

#

more like

#

C# tcp listener

#

just run one of those in a background thread from unity

#

and make sure you understand multithreaded programming enough to have that background thread interact with the main thread as needed.

scenic forge
#

(I've also seen terribly written software that don't know how to do IPC properly, so they use a temporary file and read/write to it to communicate... Please don't do this, but if you must, that's an option 😅 )

polar orchid
#

Does it necessarily need to run on different threads? This won't be client facing so some lag would be fine

sly grove
#

lest you block the main thread and therefore tank the framerate

#

You can't use tcp listener in the unity main thread unless you don't care if there are literally no frames drawn

polar orchid
#

Ok cool makes sense thanks a lot for the help!

hushed fable
hushed fable
upbeat path
#

There is a C# solution specifically for interprocess communication namely Pipes (either named or anonymous). Not tried it with WebGl but works for desktop @polar orchid

strange ice
#

I plan on having playtests for my game soon. And since it's open world I'd like to see where the testers are attracted to more.

Is there a way for me to track the movement of a player and then have them send me that data in like the form of a line? Then I could put it over a map of the world to see where they were the most? Kind of like the hero's journey thing in breath of the wild

strange ice
#

Classic unity server being very helpful

fresh salmon
#

Any collection of Vector3 (or Vector2 if you don't care about altitude) will do, for recording movements regularly. Then this can be serialized to JSON and sent to a server using a UnityWebRequest

dusty wigeon
# strange ice Classic unity server being very helpful

I mean, this is definitely the best way to achieve whatever you want. I really doubt that you are going to find what you want out of the box. If you really want to search and see what solution are available, then you can look up "analytics" solution for Unity. If you have any question on how to do it, feel free to ask it.

strange ice
strange ice
dusty wigeon
strange ice
#

Still if you didn't have anything useful to say at first you could've just ignored my message

#

But it's whatever I got what I need

thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

regal olive
#

Does anyone have a script for a 2d.mobile game that lets you move side to side

bleak citrus
#

not a #archived-code-advanced question. and, no, this is not a place where people will just give you all of your game's code

fresh salmon
#

Also posting the same question in 4 channels is not something we do here

next marsh
# dusty wigeon Code

Just for the record I don't think being an ass fixed anything. Fen said it best

dusty wigeon
distant kernel
#

hello friends. i am trying to sync indices of a List of objects and a sphere array[] from the CullingGroup API. i can remove elements from the list, but i cant remove elements the same way from the array. so as elements are being added and removed at random orders in the List, the array index doesnt stay in sequence to the object index, i cant seem to wrap my head around keeping them in tandem. im trying to make it dynamically adaptable without breaking the order. any ideas would be appreciated.

jolly vine
#

Anyone have an idea whats wrong with this compute shader? ```
Shader error in 'GenerateMapData': syntax error: unexpected token 'point' at kernel CSMain at GenerateMapData.compute(20) (on d3d11)

(I'm getting this error for every line that references "point" in the code)
```glsl
#pragma kernel CSMain

struct Point
{
    float3 color;
    float height;
    float isSpawnPoint;
};

RWStructuredBuffer<Point> points;

float chunkWidth;
float chunkPosition;
float chunkResolution;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    Point point;

    point.color = float3(54.0f, 2.0f, 234.0f);
    point.height = 5.0f;
    point.isSpawnPoint = 1;


    uint index = id.y * chunkWidth + id.x;

    points[index] = point;
}

Thanks!

sly grove
#

Can't use it as your variable name

jolly vine
rugged radish
#

is there an interface that would allow writing generics for both c# array and NativeArray ?

tiny pewter
#

cant understand, native array doesnt allow reference type (idk if it is allowed in ecs)

rugged radish
#
void Func(float3[] verts);
void Func(NativeArray<float3> verts);

I have to write overloads like that that do the same thing
functions only read/write by index and have exact same text, I'm asking if there's an interface that is shared between both arrays and allows to read/write by index
I tried IList, but it didn't work for NativeArray

tiny pewter
#

idk if indexer has interface to define it

public struct NativeArray<T>:IDisposable, IEnumerable<T>, IEnumerable, IEquatable<NativeArray<T>> where T : struct 
```what my vs gets, if there is not interface defines the indexer then you can use c style function
```cs
void Func(float3* arr,int count)
sage radish
# distant kernel hello friends. i am trying to sync indices of a List of objects and a sphere arr...

You can remove elements by swapping them with the last element in the list. Then you only need to update one element in the array to keep things in sync.

For example, if you have a list of integers: 1, 2, 3, 4, 5, and you want to remove number 3, you swap number 5 in its place: 1, 2, 5, 4. You did mention you didn't want to break the order, but you didn't explain why that's important. I can't see why that would matter here.

sage radish
rugged radish
#

or I can just convert before the calls 🤔

sage radish
indigo citrus
#

How can I create this splash effect in the background? (The juice of the food in the background and disappearing with time). What technology should I use? The particle system? A gameobject with a sprite that just changes the opacity from 1 to 0 with different dimensions every time?

west scarab
#

Since you asked, both a particle system or sprite should be fine, particle system could be faster, depends on how many decals you want.

#

I would just benchmark it if you are concerned

indigo citrus
#

So how would I do the different splash every time with the particle system? With sprites I would just have 9 different sprites or something... But what about the particle system?

west scarab
#

You mean how you would use different textures in the particle system?

indigo citrus
#

Yeah

west scarab
#

You can use a spritesheet, and then set an index

indigo citrus
#

For example a random one from this list

west scarab
#

You just have to make the texture one sprite wide, and then set the rowIndex

indigo citrus
west scarab
sleek wedge
#

I don't exactly know which channel this would fit best in, but it seems like it would fit in here more than anywhere else.

I a perfect 1-to-1 copy of the Unity.random.value function in JavaScript, along with the seeding ability. Please ping or dm me if there is one publically available,

fresh salmon
thin mesa
#

unity's Random class is just a xorshift 128, should be fairly easy to replicate for just getting a float value from 0 to 1

bleak citrus
#

yeah

#

it's just a matter of following the spec exactly

#

I had some trouble correctly implementing the Mersenne twister..

sleek wedge
#

i got that far, the only issue is slight errors

bleak citrus
#

Does it produce correct random integers?

#

Those sound easier to start with

novel plinth
#

thats floating point for you

sleek wedge
#

I am recreating a feature of a unity game into a website.

bleak citrus
#

If there were more digits, I'd wonder if this was because of your rounding mode

sleek wedge
bleak citrus
#

But these seem small enough for that to not be the cause

#

I guess I'd check that anyway.

#

actually, only six digits? these are probably rounded

#

Definitely check that.

sleek wedge
#

Kay i just tested my code with the game. i am accurate down to the 6th digit

#

C#: 0.976958990097046
JS: 0.9769588711152223

indigo citrus
west scarab
indigo citrus
#

Ehm yeah sorry

#

Appear in the mouse position

west scarab
#

Use EmitParams

distant kernel
bleak citrus
#

Are you explicitly doing 32-bit float math?

#

It's been a hot minute for me, but I know math.js offers BigNumber support. I wonder if it can also do 32-bit software floats (assuming you can't convince JS to do 32-bit float math normally)

sleek wedge
#

im working on making this a unity WebGl application instead of pure js

flint geyser
#

Can I make a class become another class when it's compiled to another platform? For instance if I want all instances of a class to be replaced by string when they are compiled to ios

graceful widget
#

Hi, I've actually been struggling for another week, but do you have any ideas/materials on how to create a relatively generic ability/skill system?

I've already tried adding it entirely to my character's FSM, but it doesn't seem like a good solution to me (unless I'm mistaken), and it has grown too much.

#

And this is only just for the first attack (in the chain attack).
The only somewhat reasonable thing I found in the internet was this:

#

I was never exposed to properly architectured ability system, thats why im asking, if you were working on / using in production something interesting

#

concepts / links / talks / books are welcome

#

My character FSM is based on daivsky contribution in open proiect (RIP)

dusty wigeon
# graceful widget Hi, I've actually been struggling for another week, but do you have any ideas/ma...

You are struggling at the moment because you are trying to come up with a system before having defining the specifics. The easiest way, is to implement a few abilities then compare whatever they have in common. With experience, you would be able to reduce this step.

That being said, there is something important that I learnt from experience which is the distinction between an instance and the concept. It is similar to the difference between an instance and a class. An example, would be that if you to a market to buy a fish, there is actual two distinct type of fish. The fish that you intended to buy (the concept, price - name - brand), and the actual fish (the instance, weight - smell - look). This directly relate to what you should do with your ability. In my project, I use "Definition" of diverse object to represent the concept. The actual instance is being created in runtime whenever needed either with C# object or GameObject.

I took an hour to make something that represent what I meant by definition (Implementing a Fireball ability in a "generic" way). (Not tested) At the end, this is only an example of what it could looks like. You need to acquire experience and the ability to quickly pivot from one architecture to an other. As your game evolve, your architecture needs to evolve as well. To come back to what I said at the beginning, you should start by implementing a few ability then look what is coming back often. From there, this is a question of applying what you know about design pattern and programming principle.

wide bolt
dusty wigeon
wide bolt
dusty wigeon
#

@wide bolt
You need 1 precompile on the actual class. You can then use reflection if you want afterwards for the "injection" or an other preprocessor directive. Dependency injection is definitely a way, however you absolutely need preprocessor directives.

gloomy mica
#

Hi guys what does 'RunCachedOperation' mean in SBP's buildlogtep file?

#

does this mean I failed to connect to cache server?

#

occasionally my build is very very slow. I think RunCachedOperation is the step that unity stuck

fresh basalt
#

Anyone experienced with webrtc could help?

fresh basalt
#
    Debug.Log(candidate);
    if (candidate == null) {
        Debug.Log("ICE gathering complete");
        iceGatheringTcs.SetResult(true);
    }
    else {
        //Debug.Log("ice candidate received:" + candidate);
        // Add the candidate to the list
        iceCandidates.Add(candidate);
    }
};``` Anyone? I get a total of 3 ice candidates and then it just halts without receiving any new ones/null value to identify end
sly grove
#

No idea what an ice candidate is though

fresh basalt
#

its not. It awaits at the end for the gathering to be complete

#

im definitely doing something wrong with establishing the webrtc connection, and there's basically 0 people who know how to do it and can help

honest hull
#

is there ANY way for me to change a #define in a cginc file from C#?(or even recreate the cginc file from scratch with the changed #define?)
I cant use shadervariants or multicompile or anything really because its a mess of nested compute shaders that these #defines influence

dusty wigeon
sage radish
honest hull
#

not very easily no

fresh basalt
dusty wigeon
fresh basalt
#

i think there's no initialization right now at all

#

you just create the peer connections

fresh basalt
#

@dusty wigeon any ideas how to serialize a list of RTCIceCandidate to send through signaling server?

#

seems like im getting the wrong objects, not as they were before

austere niche
#

Anyone know how to make an infinite terrain generator with biomes using only code?

compact ingot
#

ofc people know, but this is just too much to answer

austere niche
#

and get it flattened out a little

austere niche
#

Is that possible?

lavish lotus
# austere niche Is that possible?

Sure it’s possible. You’d have to find a suitable approach though. First game that comes to mind is Minecraft. Check out how they made biomes and work off of that.

#

From what I understand you’d already need extensive knowledge about terrain generation in the first place. I’m sure there’s videos and tutorials out there about this specific topic!

thin mesa
hidden onyx
#

my bad

#

didnt see that

#

srry

undone coral
fresh basalt
#

a budget?

undone coral
fresh basalt
#

setting up multiplayer for my game

#

i have the lobby system/servers, everythings done

#

bit struggling with the webrtc part

undone coral
fresh basalt
#

I need a simple and lightweight way of sending data between players. The other solutions are very chunky ar hard to operate

#

simple text based data exchanged between players

#

no object syncing and all the other bullshit

undone coral
#

got it. what platform is your game intended to be played on? WebGL?

fresh basalt
#

android/desktop

undone coral
#

hmm

fresh basalt
#

but i think i figured out what the problem was, so dont worry for now 🙂

#

imma go to sleep and fix it tomorrow

undone coral
#

you probably want to use playfab

fresh basalt
#

ICE candidates werent serialized properly for the signaling server

undone coral
#

for whose signaling server? the one that is written as a bunch of javascript scripts, in the render streaming repo?

fresh basalt
#

nah man, i want my own soliution. Everything stands on my servers/database

#

i like to be in control of these

undone coral
#

so one that you authored?

undone coral
#

hmm

fresh basalt
#

webrtc is the way to go for me

undone coral
#

i think you are at the start of a very long journey

fresh basalt
#

im halfway done with the webrtc part

#

that's all that's left ;D what are you talking about

undone coral
#

you are like 5% done with the webrtc part lol

fresh basalt
#

everything else is written

#

even if so, i'd like to learn that stuff aswell

undone coral
#

you can even use PUN 2, a legacy product, which has essentially "simple" and "text based" pretty much flawlessly

#

your android users, will they primarily be US based or international?

fresh basalt
#

if i really cant figure it out myself ill do it with pun, had that in mind before, but dont like that it's legacy

#

international

undone coral
#

okay, and you want this work over a cell connection?

#

if you see only local addresses and an srflx ipv6 address, you are going to have a very bad time @fresh basalt webrtc is anything but simple or lightweight

fresh basalt
#

ill try, thanks

austere niche
untold moth
austere niche
#

how would one place objects in a world(trees, rocks, grass, spawn locations for animals, towns)

gloomy mica
# dusty wigeon Did you profile ?

the screenshot is my profile result according to the buildlogstep file. RunCachedOperation take 90% build time, I'm not sure what exactly it is doing

tough summit
#

I asked about serializing a Dictionary<T> here some time ago, and someone suggested creating my own class with a struct that could be serializable. After implementation, I noticed that any addition of a struct field or a name change of a field, I have to populate the fields with their corresponding values of what I'm serializing. Is there some way to deal with this so I don't have to redo all my work again? JSON?

regal olive
clever urchin
#

Actually they have a serializable dict in their example

fickle kelp
#

Hi, can someone quick help me with the event system and raycaster ?
I need to "control" a raycaster so it send event the position I want, I tried do it manually, by calling raycaster.Raycast or EventSystem.current.RaycastAll() , the raycast are well done (I think), but the event is not send
I want to trigger an IPointerEnter by this way
Tried to implement BaseRaycaster

    raycaster = screenCamera.GetOrAddComponent<PhysicsRaycaster>(); // stuff in awake
    // The implementation should send back resultAppendList with the good items to the event system
    public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
    {
        raycastResultList.Clear();
        pointerEventData.position = myposition;
        raycaster.Raycast(pointerEventData, resultAppendList); 
    }
#

I'm trying to implement physic raycast throught a RenderTexture

dusty wigeon
# gloomy mica the screenshot is my profile result according to the buildlogstep file. RunCache...

Did you use the profiler ? You might be able to see additional information then the build file. The other alternative would be to delete part of the project one by one to see what is the cause of the slow build. It might also be totally normal depending on what you are building. Finally, if you havent or have updated, you could try to change Unity version between 2022 and 2021. There is a lot of additional performance optimization in 2022 that might be the cause or that could help.

fickle kelp
austere niche
#

Does anyone know how to spawn objects when making terrain?

worldly imp
austere niche
#

yes please, like trees, grass, rocks, and buildings

#

if it helps it is a mesh terrain

worldly imp
austere niche
#

this is an infinite terrain system tho

worldly imp
austere niche
#

here is the code for the terrain generator

urban warren
#

Hey, this doesn't really fit anywhere. But this seems like the best place.
I am trying to create some dlls from my assembly references. I get the .csproj file, and use the dotnet build system to build it so I can get the dll. But when I try it for a editor only assembly it says that it cannot find the .csproj file even though it is clearly right there.
Any ideas why this might be?

stuck onyx
#

This target 'GameAssembly'.... has been there always? its the first time i notice it... upgraded from 2021 to 2022 not long ago, is that a new thing ?

mellow plinth
#

¿Is possible to get all the StateMachineBehaviour of an animator? (I'm aware that Unity shares some behaviours between animators and I don't mind) It's for a debugging tool.

mellow plinth
#

I just realized there is also a Animator.GetBehaviours, are they equivalent?

sly grove
#

oh yeah

#

you can use that

mellow plinth
#

Great, thanks

honest hull
#

what transforms do I need to apply to a skinned meshes vertex buffer to fully put it into world space?

sly grove
honest hull
#

holy heck I think I figured it out
after 2 years

honest hull
#

Theres no way to remake or modify a .cginc file to change #defines from C# right?
This cginc is included in all my compute shaders and I would like to connect the #defines to toggles accessable in an editorwindow so I dont ahve to go in and modify the code every time(its a very rare thing to do but still)

#

I cant really do multicompile

hazy epoch
#
private async Task OnClick()
{
    battleButtonsPanel.SetActive(false);

    await cameraManager.SwitchToCamera(battleCamera);

    battlePanel.Init(convention, conBattle);
}

battleButtonsPanel is the parent GameObject of the UI Button this MonoBehaviour is attached to. Why would this OnClick() get called again, the next time battleButtonsPanel is SetActive(true)?

little cargo
#

Hello everyone, have you encountered this problem? I didn’t do anything special, an error appeared in Unity and in GitHub Desktop (Unknown Error). An empty project also has an error and does not go away. I reinstalled both the editor and GitHub Desktop, nothing helps

hazy epoch
#

By the way...the way I allow an async Task to be called on a UI Button is by...

private void OnEnable()
{
    button.onClick.AddListener(async () => await OnClick());
}
mellow sail
#

excuse me, did anybody here ever make a mortar like canon that could rotate automatically based on targets position in unity 2D? i want for the mortar to rotate based on trahectory line

#

any resource maybe to achieve this?

dusty wigeon
# mellow sail excuse me, did anybody here ever make a mortar like canon that could rotate auto...

Visit http://ilectureonline.com for more math and science lectures!

In this video I will find the angle=? of a projectile fired at an angle at h=0 with initial velocity v0 traveling a distance x.

Next video in this series can be found at:
https://youtu.be/4JsoRFlHJnE

▶ Play video
mellow sail
#

okay, i might have to watch it first

dusty wigeon
#

Function for considering wind. Base on https://www.youtube.com/watch?v=aKd32I0uwAQ&t=228s

whether it's recess basketball, captain blubber's shenanigans or the alien kangaroo invasion, having an aimbot is always useful

0:00 Intro
0:21 Basketball
1:20 Basketball Maths
1:54 Captain Blubber
3:41 Captain Blubber Maths
4:06 Captain Blubber Part 2
4:49 Space Kangaroos
5:24 Space Kangaroos Math
6:05 Root Finding Algorithm
7:28 Finale

White...

▶ Play video
mellow sail
#

thanks a lot, there will be no wind. Since its only a 2d game

dusty wigeon
#

You can still have wind O.o

#

Everything is in 3D, but it works in 2D.

mellow sail
#

damn, i hate phyisics hahahaha

vital nacelle
#

So i have a little spider that i'm trying to animate procedurally. But when it starts moving, the little targets are getting huge a offset on the Z axis. The spider still walks, but with the legs in this position.

I think its coming from the line 75 of this script : https://gdl.space/nogagabiki.cs
Because when i try to remove the offset, it aligns way better. But still not good because its adjusted manually

If anyone has an idea, or tips. Its a code i tried to reproduce from a work online but ended up copy pasting it coz of this bug i thought was coming from my version.

#

maybe this will better fit here

austere niche
#

Anyone know how to make objects get spawned in an infinite terrain

untold moth
frank bobcat
#

Hey, what should I use to make a multiplayer game which has a hosted server by me?
A server I can purchase somewhere, I think it's called dedicated server?
So people have to connect to my server instead of playing through IP/hosting their own.
Ideally I'd like a tutorial on how to do that.
This is meant to be for a battle areana style of game with more than 10 people playing at the same time.
I understand this won't be easy, but I need something to get me started.

hushed fable
dusty wigeon
untold moth
austere niche
#

ok

signal sluice
#

anyone have an idea as to what channel I can ask for help in relating to the camera/skybox

#

i have a retro pixel canvas filter thing going on, so whenever I set my cam to solid color the skybox shits itself with whatever it was last looking at

#

doesnt overlap over objects though

#

if theres a gud channel ill post a pic there

untold moth
clever widget
#

I'm trying to use the null comparison operator on a singleton object like this:

WeaponManager.instance.myWeapon?.gameObject.SetActive(true)

But VSCode is showing a warning that "Unity objects should not use null propagation." What does it mean?
https://github.com/microsoft/Microsoft.Unity.Analyzers/blob/main/doc/UNT0008.md

GitHub

Roslyn analyzers for Unity game developers. Contribute to microsoft/Microsoft.Unity.Analyzers development by creating an account on GitHub.

upbeat path
vague quail
#

Someone is experienced in rts game terrain generation and performance?

clever widget
upbeat path
floral flower
#

Hey guys, i have removed component via PrefabUtility.GetRemovedComponents();

Is there built in way to show a popup if i want to apply this removed component to the prefab?

dusty wigeon
floral flower
#

Thank you for reply 🙂

olive cipher
stiff widget
#

I am trying to write some code that can be called to return a list of tiles on my map when they player needs to target an ability. I need there to be functionality for the game to continuously highlight tiles that the player mouses over but only return the tiles when the player clicks, obviously this while loop is problematic and I was wondering if this is a case where I should be using an async await implementation, is that the case and if so does anyone have any pointers on how to achieve that?

public Tile[] TargetTileSquare(int size)
    {
        targetTiles = null;
        playerInputState = InputState.Target;
        while (targetTiles == null)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                Tile temp = hit.transform.GetComponentInParent<Tile>();
                if (Input.GetMouseButtonDown(0) && temp != null)
                {
                    targetTiles = new Tile[] {temp};
                }
            }
        }
        playerInputState = InputState.Inspect;
        targetTiles[0].Highlight();
        return targetTiles;
    }
neon wraith
#

I'm trying to have a stack where my Unity client is authenticated by my .NET Core server which retrieves auth tokens from Azure AD. Has anyone ever done this before?

#

Like is it possible to have a server middle man which authenticates my Unity client, and is able to get resources on behalf of the Unity client from Azure thereafter? I'm thinking:

  1. Unity hits server with a login/register request.
  2. Server authenticates with Azure AD, and then returns token to Unity client.
  3. Unity client sends subsequent requests with the token to the server.
dusty wigeon
bleak citrus
#

the problem is that they want TargetTileSquare to return a list of tiles

#

meaning that it would have to block until the player actually picks the tiles

dusty wigeon
#

I mean, the mouse cant move in a while loop not threaded,

bleak citrus
#

I suppose you could do something with async here (maybe using Awaitable to check the currently-hovered tiles every frame on the main thread)

dusty wigeon
#

Isnt the best to have a picking up state ?

#

With an update loop.

bleak citrus
bleak citrus
#

the ability would not be waiting for the player to pick a target

#

picking a target would signal the ability to start

#

that's how I handled this in an RTS

dusty wigeon
#
private Tile[] targetTiles;
private bool tryingToPickup;
private boo hasPickUp;

public void Update()
{
  if(tryingToPickup)
  {
      targetTiles = null;
      playerInputState = InputState.Target;
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      if (Physics.Raycast(ray, out RaycastHit hit))
      {
          Tile temp = hit.transform.GetComponentInParent<Tile>();
          if (Input.GetMouseButtonDown(0) && temp != null)
          {
              targetTiles = new Tile[] {temp};
              hasPickUp = true;
          }
      }
      
      playerInputState = InputState.Inspect;
      targetTiles[0].Highlight();
  }
  else
  {
    //Handle other state such as choosing the ability to cast
  }
}
stiff widget
#

I should have explained a bit more, this is a card based game so this implementation is for the logic for a card being played and then the player selecting targets based on what card was played

stiff widget
#

your solution could work where the function just flags the tryingToPickup bool

dusty wigeon
stiff widget
#

I think i was struggling to visualize how the functions would control the code in update but seeing your visualization i think that would work

#

do you think that this would run in to issues if for example a script to play a card that had multiple targets had to call the target function more than once and then perform an operation with the results of both functions? (basically do i need to do these things using async?)

tough summit
tough summit
# regal olive I'd like to expand on <@307360612403642370> 's answer. It seems like you are try...

What if one of the types I want to reference is a prefab? I'm currently using the struct that I later on serialize so that I can drag a prefab into a struct field and use it to instantiate objects from a factory. Could I perhaps use Unity Editor to drag the prefabs into a List<T> and then use Bakingsheet to serialize the records into a JSON that I can import to the unity editor and also use during gameplay once the game is built?

weak monolith
#

Does anybody know if there is any significant overhead in using scriptable objects as global variables that other scripts modify through unity actions?

#

for example, multiple scripts having a copy of the SO listening for a unity action/event that passes variables from a boradcaster > channel > listener chain type of thing?

sly grove
weak monolith
#

It's more a general question about if there are any issues doing it that way since SO's can act a bit strange sometimes (for example, storing info only during run time but not being able to write to the SO).
So basically there is an SO that waits for someUnityAction?.Invoke(params). If there are say 50 objects with that SO "listening" for that event, does it cause any issues? Haven't profiled it because in terms of perfromance, HDRP takes up the lion's share of ms. It's more that I don't want to start implementing it only to find out it has a huge footprint in memory or it isn't garbage collected etc.

sly grove
#

I'm not even sure I understand what you're describing with 50 objects having the SO listen to an event

#

Show an example perhaps?

#

As for strangeness, there's not a lot of strangeness with SOs, they pretty much behave exactly like any other Unity asset

#

Don't change serialized data on assets in the editor or it will be permanently changed

weak monolith
#

public class NPCChannel : ScriptableObject{

public UnityAction<NPCEvent> npc_event;

public void RaiseEvent(NPCEvent _event) {
    npc_event?.Invoke(_event);
}

}//EO NPC channel

sly grove
#

So that's a regular delegate, not a UnityEvent

#

It works like a normal C# delegate, because it is one

untold moth
#

It would work exactly the same as a plain C# class in terms of performance.

weak monolith
#

awesome. Is there any real benefit to having it in an SO?

untold moth
#

You can drag it around in the editor.

sly grove
#

You can reference the SO as an asset

#

That's the point of SOs

weak monolith
#

would it be better as just a C# class that other scripts reference?

sly grove
#

If you don't care about referencing it in the editor

untold moth
#

If you don't need to reference it in the inspector, sure.

weak monolith
#

haha, thanks!

sly grove
#

Unless it's intentional that you can invoke the delegate from outside that one function

#

You can also just use System.Action

#

UnityAction doesn't buy you anything

weak monolith
#

yeah I'm not sure what that means but the RaiseEvent is called by multiple scripts, but the action itself is only in this script

sly grove
#

Right so

#

Putting event on the delegate will ensure that it can only be invoked by calling that function

weak monolith
#

like public event UnityAction, or in the method RaiseEvent? I never studied coding, self taught.

sly grove
#

The first

weak monolith
#

Thanks for the info 🙂

untold moth
#

If anything, programming is all about self teaching.

weak monolith
#

Hahaha, I'm an "old fella". There's not as much room in my brain as there used to be, but I get by. Moving through different paradigms is hard though - like data oriented design. Can't wrap my head around that yet 😄

untold moth
#

Nvm. Misread the message 😅

light falcon
#

what would be a good way of decoupling code? I was thinking of using a system with a general 'events container' script, example: Script A wants to trigger an event, so it calls the event in the events container (script B), which script C is subscribed to. Is this a good approach? I like to hear your opinions!

untold moth
#

It depends on the situation. You don't always need to decouple code entirely. Sometimes one way dependency is what you want.

light falcon
#

in what cases would you want dependancy?

flint sage
#

Indirection makes things slower and more confusing to read

tall ferry
# light falcon what would be a good way of decoupling code? I was thinking of using a system wi...

What you are describing somewhat sounds like just moving events from one script to another. Theres no real change happening, except now its actually harder to setup things.
Let's say you have a bunch of buttons and a bunch of doors in game. Each button opens 1 door, this is very easy to setup with unity event and a public method on the door.
Now if you change this to go through your events container, you'll need to find a new way to link these objects so that 1 button event doesnt trigger every single door. You could do it based on ID but now this introduces more work for the same outcome

light falcon
#

i see. But for static events this would be a good choice?

vale basin
#

(I don't know if this belongs to "code advanced", sorry in advance)
I generate frames and store them in individual interleaved byte arrays where each byte is a color channel (3 bytes / pixel), how can i use GetRawTextureData and write to it in this case?
My current approach is to use LoadRawTextureData and provide it my byte array

drifting hawk
#

anyone else experiencing Resources.Load returning null if called during initial asset import in Unity 2022?

eternal vine
#

i got the grass to spawn at the top but now the ores just spawns everywhere

#

nvm, got it to work

tiny pewter
#

you should store the value of random.value, otherwise it will be called multiple times in else if()

upbeat path
#

but that is what he needs to resample after every failed if

floral flower
#

hey, any idea how PrefabUtility.ApplyObjectOverride() works? it seems that i aply correct component, i do PrefabUtility.GetPropertyModifications() and indeed there are these modifications that i want to apply but it doesnt want to work. Also i tried PrefabUtility.SetPropertyModifications(); and that also didnt work 😦

obtuse arch
floral flower
eternal vine
#

something messed up is happening here

{
    for (int x = 0; x < worldSize; x++)
    {
        float height = Mathf.PerlinNoise((x + seed) * terrainFreq, seed * terrainFreq) * heightMultiplier + heightAddition;

        Sprite tileSprite;

        for (int y = 0; y < height; y++)
        {
            if (y < height - 1)
            {
                if (Random.value < ores[0].spreadTexture)
                    tileSprite = tileAtlas.coal.tileSprite;
                else if (Random.value < ores[1].spreadTexture)
                    tileSprite = tileAtlas.iron.tileSprite;
                else if (Random.value < ores[2].spreadTexture)
                    tileSprite = tileAtlas.gold.tileSprite;
                else if (Random.value < ores[3].spreadTexture)
                    tileSprite = tileAtlas.diamond.tileSprite;
                else
                    tileSprite = tileAtlas.dirt.tileSprite;
            }
            else
            {
                tileSprite = tileAtlas.grass.tileSprite;
            }

            PlaceTile(tileSprite, x, y);
        }
    }
}```
sly grove
vivid vapor
#

redirected issue from #🏃┃animation since i was advised to come here:
i've been trying to make a tool to convert animations from one reference position/rotation to another, so i can make my process of making third person animations way faster. in idea, it's simple. get rotation/position values from an animation, subtract them by one reference position/rotation (or in the case of quaternions, multiply the inverse), add another reference position (aka multiplication with quaternions)

however, in practice what happens is gimbal lock. what i'm doing is getting the euler rotation values from the animation curve keyframes, assembling them into a euler vector3, then when i need to edit them i convert them to quaternions, convert the clip reference rotation and the new reference rotation to quaternions, then do my calculations with quaternions. then, when i create the new keyframes for the output animation, i convert them back to euler. i am doing no calculations with eulers, only using them to get and add values to an animation.

despite this, i encounter gimbal lock. i do not know how to circumvent this and would like to know what i'm doing wrong. also, i tried setting interpolation to quaternion on the animation and it resulted in this weirdness:

austere niche
#

Anyone got a fix for this
NullReferenceException: Object reference not set to an instance of an object

regal lava
austere niche
#

do you know how i would fix this

half swan
# austere niche do you know how i would fix this

Impossible without seeing your code inspectors and more. You didn't even give the whole error. It will tell you where it happens in code

Also, just read the link I sent which describes the error and how to fix it.

Lastly, this is not advanced. It belongs in beginner.

sage birch
#

Trying to create a procedural mesh for a fibonacci sphere is a pain, but UV mapping it correctly seems flipping impossible

#

I always end up with this weird pinching effect along a seam. I thought it was because I had triangles passing over the seam, and yeah the "u" value on the triangles with that messed up UV also have an average U value of around 5 if you average its 3 points

#

I'm using this method to make a procedural rock. Fibonacci spheres seemed like a good idea because of how they generate evenly distributed points which would be good for applying noise. But once I got to actually using a spherical projection for UV, I can not for the life of me get rid of this artifact

#

public static Vector2[] GenerateUVs(Vector3[] vertices)
        {
            Vector2[] uvs = new Vector2[vertices.Length];

            for (int i = 0; i < vertices.Length; i++)
            {
                Vector3 vertex = vertices[i].normalized;

                // Compute the azimuthal angle (theta)
                float theta = Mathf.Atan2(vertex.z, vertex.x);
                if (theta < 0.0f)
                    theta += 2.0f * Mathf.PI;

                // Compute the polar angle (phi)
                float phi = Mathf.Acos(vertex.y);

                // Convert spherical coordinates to UV coordinates
                float u = theta / (2.0f * Mathf.PI);
                float v = phi / Mathf.PI;
                uvs[i] = new Vector2(u, v);
            }

            return uvs;
        }```

Heres my UV code
#

I use a convexHull library to create the mesh from points


        public static Mesh GenerateMesh(int samples, float radius)
        {
            // Generate sphere points
            var vertices = GeneratePoints(samples, radius);
            var uvs = GenerateUVs(vertices);
            var convexHull = GetConvexHullFromPoints(vertices);

            var mesh = MeshFromConvexHull(convexHull);
            mesh.vertices = vertices;
            mesh.uv = uvs;

            return mesh;
        }
#

I might cut my losses and use an Icosphere PepeDepression

tough summit
# jolly token <https://github.com/cathei/BakingSheet> 😄

Are you the same cathei who is the creator of this tool? I'm very interested, but if you had a video tutorial on how to install it and implement it in a simple project, it would be awesome. As an example, I had never used Dependency Injection, but I was very interested in using it with unity. The creator of AlchemyBow (https://www.alchemybow.com/) made documentation available as well as a very short series of videos on his YouTube channel. He made it incredibly easy to visually follow with explanations, and within 2 weeks of refactoring my code, I am fully using his DI framework in Unity and loving it instead of using singletons. The documentation is still 100% the source of truth, but simple video guides go a long way in promoting adoption of a new tool. Thank you if you are the same creator who posted in the Unity Forum and Reddit in the past 2 years.

steel snow
#

Can any one explain why this gives me an array larger than the the total assets in the file:

        void LoadMeshAssets()
        {
            _meshes.Clear();
            var objs = AssetDatabase.LoadAllAssetsAtPath(_meshAssetPath);
            Debug.Log(objs.Length);
            foreach (var obj in objs)
            {
                if (obj is Mesh)
                    _meshes.Add(obj as Mesh);
                Debug.Log(obj.name);
            }
        }

it returns 12 for length and seems to load the same mesh file multiple times

#

there isnt 12 assets in the file

scenic forge
#

Side note, you can write:

if (obj is Mesh mesh)
    _meshes.Add(mesh);
steel snow
#

yeh i know ill clean the code later

rugged radish
#

It says "Buffers and textures are set per-kernel." for ComputeShader.SetBuffer
does that mean that every SetBuffer will create a new buffer for each kernel even if I use the same ComputeBuffer object every time ?

#

just trying to come up with the optimal way of managing data between multiple kernels
there's a big chunk of data that is common between all of the kernels, and smaller chunks of kernel-specific data
if SetBuffer is smart enough to create one instance of a buffer and just grant read access to multple kernels, I'll keep that static data separated
and if not, I want to just piggyback kernel-specific data with the static data

dusty wigeon
# vivid vapor redirected issue from <#502171313201479681> since i was advised to come here: i'...

What are you trying to do ?

  • You want to add an offset to an animation ?
  • You want to add IK to an animation ?
  • You want to add an animation on the already defined animation ? (Additive)

Also, by the documentation:

Quaternion interpolation rotates the GameObject across the shortest distance to a particular orientation. For example, regardless of whether the rotation value is 5 degrees or 365 degrees, the GameObject rotates 5 degrees.

Which could definitely be what is happening.

cunning citrus
#

Heey, is there any way to detect sunset in real life and make something happen in the game?

tiny pewter
#

i am not sure but you can find whether your country meteorological observatory has provide api so that you can send an http request to get data

#

or predict the time by the time zone and historical data

compact ingot
cunning citrus
#

@compact ingot And how could I applicate it on unity?

rugged radish
#

looks like SetBuffer grants access to other kernels on subsequent calls with the same buffer, it doesn't copy cpu side data into vram on repeated calls
just if anyone was wondering

icy owl
#

Hey everyone, probably a stupid question but.

I am currently trying to integrate the Nuget package Rystem.OpenAi into my unity package, on install I get an error stating that my project targets .netframework 4.7 instead of .net standard 2.1. However when I go to Edit->Project Settings -> Player -> API ref I find the project targets .net standard 2.1.

I searched the entire solution for references for .netframework 4.7.1 and couldn't find any references.

What am I missing here?

left timber
#

Not sure if this is the appropriate place but I had a question maybe someone can answer?I am trying to publish an asset on the unity asset store and I don't know how to include dependencies such as the new Unity input system and cinemachine? My system: Unity Pixel Engine is like a game engine inside unity and uses cinemachine and the new Unity input system. Any help on how I can include those as required dependencies??

upbeat path
cunning citrus
#

Does anyone know how to solve this problem with the API?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class NightBackground : MonoBehaviour
{
    [SerializeField] private float latitude;
    [SerializeField] private float longitude;

    private string url = "https://api.sunrisesunset.io/json?";

    private void Start()
    {
        StartCoroutine(GetSunriseSunsetData());
    }
    IEnumerator GetSunriseSunsetData()
    {
        string requestURL = url + "lat=" + latitude.ToString() + "&lng=" + longitude.ToString();

        UnityWebRequest www = UnityWebRequest.Get(requestURL);
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.Log("Error: " + www.error);
        }
        else
        {
            // Procesa la respuesta JSON aquí
            string jsonResponse = www.downloadHandler.text;
            Debug.Log(jsonResponse);
        }
    }
}```This is the code that controll the API, and I know that it works cause when i paste the API link in google it works correctly: ```https://api.sunrisesunset.io/json?lat=38.907192&lng=-77.036873``` and it respond me with the information that the API should give me: ```{
    "results": {
        "sunrise": "7:17:19 AM",
        "sunset": "6:33:22 PM",
        "first_light": "5:48:45 AM",
        "last_light": "8:01:56 PM",
        "dawn": "6:50:31 AM",
        "dusk": "7:00:10 PM",
        "solar_noon": "12:55:21 PM",
        "golden_hour": "5:57:22 PM",
        "day_length": "11:16:03",
        "timezone": "America/New_York",
        "utc_offset": -240
    },
    "status": "OK"
}```
upbeat path
cunning citrus
#

is that?

upbeat path
#

not what I asked for

#

Did I say jsonResponse ?

cunning citrus
#

oh, i think its not there

#

so thats missing

upbeat path
#

exactly, so how do you know what is being passed to the WebRequesst?

cunning citrus
#

I don't understand it

#

The same code works for another person

upbeat path
#

you are making an assumption on the output of

string requestURL = url + "lat=" + latitude.ToString() + "&lng=" + longitude.ToString();

without actually checking it

cunning citrus
#

thats the strange thing

upbeat path
#

I know but that does not mean he used EXACTLY the same data as you

cunning citrus
#

how would be the fixed code?

upbeat path
#

?

cunning citrus
#

I'm completly lost

#

Could you guide me a bit about what is happening?

upbeat path
#

No, not until you show me what I asked for

thin mesa
cunning citrus
upbeat path
#

I want to see a screenshot from the console

cunning citrus
thin mesa
#

then show the log

thin mesa
#

it's like you're not even reading what anyone is telling you

upbeat path
#

Still no Debug.Log of requestURL

cunning citrus
thin mesa
#

then why are you in the advanced channel

cunning citrus
sly grove
#

if this is not a server/api that you own or control, you should be asking whoever runs this API about it.

upbeat path
#

And I bet it's a parsing error on the URL

cunning citrus
#

is that the log you want?

thin mesa
#

literally just Debug.Log(requestURL)

upbeat path
#

Still no Debug.Log on requestURL. At this point I give up

cunning citrus
#

here is your log

tiny pewter
#

when someone ask you to debug some variable, they want you to debug.log("variable is "+variable) and show the screenshot
. becomes ,

cunning citrus
tiny pewter
#

ofc, this is what you passed into web request

upbeat path
thin mesa
# cunning citrus

there's the issue. you've got commas instead of periods for the decimal point. you'll need to specify a number decimal separator in your ToString call

upbeat path
#

or use InvarientCulture

#

@cunning citrus Now do you understand why you need to check not just assume?

cunning citrus
upbeat path
#

If you had done this when @warm mica first asked you to do it this problem would have been solved long ago

cunning citrus
#

yeah, but i didn't have much clear wich log was he asking me to add... the same with you... Thank you all again @upbeat path @warm mica @thin mesa @tiny pewter

glossy cargo
#

Ok so Im trying to make a system where these "obstacles" spawn along a road at random points on that road. For some reason when I run this script on an empty object (properly assigning the public variables), the obstacles only spawn on one point.

#

Note: i used a sprite (which is a long rectangle) as the road, assuming that the objects spawn along that road

#

i even tried this simplified version but it didnt work

half swan
#

@glossy cargo Throw a debug.log, or better yet, a breakpoint in there and read the values at runtime

tiny pewter
#

dont cross post

pure dock
obtuse arch
# graceful widget Hi, I've actually been struggling for another week, but do you have any ideas/ma...

I sugges you go over the Charaction Action series by Tara Doak.
'https://www.youtube.com/@TaraRaeDev/search?query=character action'
Before starting I suggest going over the entire series and taking notes from each video.
Initially you will feel overwhelmed but repeat and try to understand what problem each design decision solves.
If you have any alternate ideas which you think would solve the understood problem well, try it first and then continue. That will give you nuanced ideas regarding implementation details which @dusty wigeon also suggests. I highly suggest not copy pasting. Hope this helps.

rugged radish
#

can anyone recommend a site with common terrain noise functions ?
some sort of height function database or cheatsheet ?

compact ingot
rugged radish
#

so I don't start from scratch

compact ingot
#

you should maybe download gaea and world machine demos and play around with them

#

just to get a feel for the functions

rugged radish
#

thank you, I'll have a look

compact ingot
#

you can waste a lot of time with terrain generation, its a rabbit hole

rugged radish
#

yeah, I understand that 😄

#

it's also pretty fun

regal lava
#

fastnoise is life

compact ingot
#

a productive approach is to make yourself some custom stamps with those generator apps and then use something like microverse or your own tool to build your actual game terrain with them

#

procedurally generating a full terrain with various landforms and biomes that look interesting is extremely difficult and time consuming

rugged radish
#

right, you reminded me of terrain stamping, I should add it to my to-research list

compact ingot
#

also you need a beast of a CPU to actually make such a terrain at a usable resolution

#

also consider that unity is terrible for world streaming

rugged radish
compact ingot
#

basically you can't make large maps in unity without a lot of pain and suffering in terms of workflow/design/authoring-experience

rugged radish
#

I made a basic scrolling terrain "engine" and now in a process of writing the lanscape compute shaders

#

so far I'm only generating a 1.5km by 1.5km "window" on the fly at high resolution, with the rest of the world being pregenerated at a 1:16 resolution (for the lowest lods)

compact ingot
#

that sounds like a reasonable size in unity

regal lava
#

I was writing some terrain generation in OpenGL, but the problem with doing it like that is having to develop the UI, so I had to keep recompiling the damn thing every time I wanted to change up the noise map. Unity is a godsend for this type of stuff, being able to compile it on the fly while sliding the settings.

#

Still, I'd spend hours trying to get it looking semi-decent looking

compact ingot
#

you can take a look at world creator (standalone app) that does terrain entirely on the GPU

#

from what i've seen GPU approaches so far generally fail to produce interesting landforms (those can't easily be implemented as pipes&filters) , but are great at generating local details quickly

rugged radish
#

yeah, I moved everything on the GPU, tried generating in unity jobs first, but it was slower than I hoped

compact ingot
#

GPU is very limited in what it can do, even though its fast, you are constrained to using closed functions (if you want to retain the parallelization advantage)

#

unfortunately, interesting terrain can't be generated that way

#

you can however use the GPU to put details on a landform you've generated by other means

rugged radish
#

so far the plan is to pregenerate the "skeleton" on the world creation step on the cpu, and use gpu to evaluate it at play time

regal lava
#

I'd just do everything in a vertex shader and just bake the colliders after. GPU is just too good to pass up for a job like generating the thousand of verts and normals.

rugged radish
#

it's not an infinite terrain, so I can construct a graph and mark up the map
but it remains to be seen how good the end result can be

compact ingot
#

how expressive do you want the terrain to be?

#

just some random hills or do you want actually impressive scenery?

rugged radish
#

good question, I don't plan for realism, so it can be less strict overall, but ofc I want scenery to look exciting to explore

#

"just hills" won't cut it 😄

compact ingot
#

thats probably going to not happen

#

^something like this is never going to come out of a proc-gen terrain

rugged radish
#

oh, for sure, I don't plan to compete with hand-crafted terrains, I understand the limitations
it has to be decent enough, and since my intention is stylised look it should make things a little easier, I think

compact ingot
#

for sure

regal lava
#

Just keep throwing noise maps at it

#

eventually it'll look good (or worse)

#

good read

compact ingot
#

to make actually interesting terrain procedurally you need to actually simulate the tectonic-folding/volcanism/glaciation that forms mountains/hills

#

the trickery you can do with fluvial/sedimentation sim and noise can never really get there

#

they are stochastic, so you'll always get something thats is "meh", i.e. it hints at what it could be, but it will never produce these show-stopping artefacts you get in real life

#

a stochastic neighbourhood will always be similar to all other neighbourhoods, so no surprises, and those are what makes exciting terrain

haughty skiff
rugged radish
#

I do intend to use the pregenerated world graph to define the irregular shaped domains for different types of landscape

like separating mountain ranges, riverbeds, different types of "flat biomes" etc, so I hope it won't be boring, but yeah, I will only see how it works once it works

regal lava
haughty skiff
compact ingot
regal lava
#

I think instead of all this

 _enemyMovement = new EnemyMovement(transform, _navMeshAgent, enemyConfig, _enemyAnimator);
            _enemyAttack = new EnemyAttack(_bombController, _enemyAnimator);
            _enemyDeathController = new EnemyDeathController(_navMeshAgent, _enemyCounter, _ragdollController, _colliderController, _coroutineRunner, enemyConfig);

            _enemyStateMachine = new EnemyStateMachine();
            _enemyStateFactory = new EnemyStateFactory(_enemyStateMachine, _enemyMovement, _enemyAttack, _enemyDeathController);```
Perhaps just make like an Assign(); function. But otherwise doesn't seem like that big of a deal if it works ;p
compact ingot
#

unless you have a reason for abstracting object creation into a separate class (i.e. because it needs to be an open design space that is very likely to change on the authority of another team) you are overdoing it.

#

if you are doing it because of dependency injection / IoC, do what Mao says, make a Inject/Assign/Configure method

#

if you are doing it because you are using a DI container, try to use one that allows you to create ad-hoc factories with delegates in the composition root

plucky trellis
# rugged radish I do intend to use the pregenerated world graph to define the irregular shaped d...

Minecraft is actually a good base for how to generate pretty expressive and varied terrain. Their aproach is rather interesting, and its definitely worth giving this talk a watch. In essence though. it's always going to be about how good at manipulating noise you are. https://youtu.be/ob3VwY4JyzE?si=Z457DZ9PvppdNiiW

The past year and a half I've worked almost full time with Minecraft world generation. We've radically changed how the world is generated, to enable dramatic new caves, massive mountains ranges and overall more natural-looking terrain.

In this talk we'll geek out on the gory details of this. How does Minecraft procedural world generation actual...

▶ Play video
#

There are minecraft specific details that are irrelevant to you, but the overall structure of their system is useful

rugged radish
royal raft
#

Does anyone know how to go about using a different thread than the main one and use marching cubes to create terrain. so far i am creating terrain with maching cubes and noise but i want to move that process off the main thread so i am creating triangles, vertices, uvs and then passing the data back to the main thread but when i do everything is messed up. also if i run the same code only using the main thread everything is fine

flint sage
#

That looks like multiple threads are appending to the same collection at the same time

#

So the order is all messed up

#

You need proper locking for that or give each thread a section to work on and a section that it's allowed to write to

#

So that nothing overlaps

royal raft
#

thanks if you mind what is locking ive never heard about that before?

tiny pewter
#

i remember c# collections will throw exception when >= 2 threads try to write at the same time

flint sage
#

Just look up C# locking

royal raft
#

ok thanks!

flint sage
#

Basically says that no other thread is allowed to access the same object at once

royal raft
#

i just want one thread to do all the generation just not the main one

rugged radish
#

might want to take a look at Unity jobs system

#

that's what I use for parallel mesh generation off the main thread

royal raft
#

ok ill take a look thanks for the suggestion

rugged radish
#

its limitations also pretty much guarantee that you can't write a code that corrupts the data because of parallel writes

#

so no locks are required

royal raft
#

ok thats good then i realy appreciate this since im new to jobs and multithreading

tiny pewter
#

they implement locks but hidden, and no lock in unsafe collection

rugged radish
#

you'll have to use async or unity's specific async surrogate thing, forgot how it's called 😄
to check up on your job, so that main thread can continue

#

coroutine

livid kraken
#

So I currently have an audio system where you can fire off audio events with strings like Wood:HeavyBoot:Footstep and it will go trough the sound banks until it finds a match. If no match is found it removes a decorator and tries again. Im wondering how I can keep this behaviour but eliminate the use of strings. I was thinking of creating a bit set class with a uint[] and set the bits for that, but that leads to way more boilerplate code, cause now I also need a mapping of what index is wood heavyboot and footstep.

tiny pewter
#

so eg A:B:C, if A:B:C not found->search for B:C->still not found->search for C?

#

it looks like trie (prefix tree)?

#

but i dont prefer trie, this tree uses lots of memory for connecting children

livid kraken
#

I haven’t heard of trie, I will have to research it. I was more looking for a solution that would use something like a enum. Obviously a normal enum doesn’t work here

tiny pewter
#

eg if you have following sounds and their decorator (the last character is sound)
1.abcd
2.ace
3.de
4.ad
you will start search from sound then decorator (ie in reverse order)
now you want to play:
bcd-> "whole" sound exists
bd->stop at d, so play d
bce-> stop at ce
xrcd->stop at cd
trie is basically a tree that provides you a faster search function

#

you can turn the sound and decorator to int (btw you will still need string to int hash table to make your coding easier) then construct a trie based on sounds in sound bank

#

or you can have a set of predefined enum, to show you the name instead of an array of int that hardly to understand and waste much time to decode it

tiny pewter
#

there is other way to do that search by maintain a sorted sound bank (same as trie, the format of sound should be: sound->decorator) and use linear scan (or binary search) to find the bound and current position
a bit difficult to tell (this is leetcode question but i forgot what is the name)

scenic forge
#

If there’s a known and reasonable max limit, you can also consider just have a bunch of overloads, each argument is an enum.

livid kraken
#

I dont have a problem with the search time. I just want to avoid the garbage being generated by strings

cunning citrus
#

I've got a problem with my code, its supposted to ask for permissions and to extract latitude and longitude coordinates, but it just work when i restate the game, i mean, it shows me the location permission window the first time, but the first time the rest of the code doesn't work, and when i restart the game the rest of the code stars working```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Globalization;
using JetBrains.Annotations;
using System;
using UnityEngine.Android;
using TMPro;

public class NightBackground : MonoBehaviour
{
[Header("Latitud y longitud")]
[SerializeField] private float latitude;
[SerializeField] private float longitude;

[Header("Sundata API response")]
[SerializeField] private SunData data;

[Header("TMP")]
[SerializeField] private TMP_Text sunsetText;

private string url = "https://api.sunrisesunset.io/json?";

private void Awake()
{
    // Solicitar permisos de ubicación (puede personalizar este mensaje)
    if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation))
    {
        Permission.RequestUserPermission(Permission.FineLocation);
    }

    // Comprobar si se tienen permisos de ubicación
    if (Permission.HasUserAuthorizedPermission(Permission.FineLocation))
    {
        StartCoroutine(GetLocationData());
    }
    else
    {
        Debug.Log("No se otorgaron permisos de ubicación.");
    }
}```
#
    IEnumerator GetLocationData()
    {
        // Comprobar si la ubicación está habilitada en el dispositivo
        if (Input.location.isEnabledByUser)
        {
            // Iniciar servicio de ubicación
            Input.location.Start();

            // Esperar hasta que se obtenga una ubicación válida
            while (Input.location.status == LocationServiceStatus.Initializing)
            {
                yield return new WaitForSeconds(0);
            }

            if (Input.location.status == LocationServiceStatus.Running)
            {
                // Obtener latitud y longitud
                latitude = Input.location.lastData.latitude;
                longitude = Input.location.lastData.longitude;

                Debug.Log("Tu posición es: " + latitude + ", " + longitude);

                // Detener el servicio de ubicación
                Input.location.Stop();

                // Llamar a la función para obtener los datos de la puesta de sol
                StartCoroutine(GetSunriseSunsetData());
            }
            else
            {
                Debug.Log("Error en la obtención de la ubicación.");
            }
        }
        else
        {
            Debug.Log("La ubicación no está habilitada en el dispositivo.");
        }
    }```The code continues with this corrutine: ```cs
StartCoroutine(GetSunriseSunsetData());```
tiny pewter
#

i just realize that i didnt answer to that question directly, yes use enum for query

SoundBank.SearchSound("name")&&SoundBank.SearchDecorator(enum)&&SoundBand.SearchDecorator(enum)......
sound=soundbank.Result();
SoundBank.Reset();
#

SearchXX will return bool so if soundbank.search return false the first line will stop executes (short circuit evaluation) and you can ask for search result in second line, then reset the pointer (or what ever) in third line

#

You dont need brunch of overloaded methods here but it needs memory

sly grove
cunning citrus
sly grove
#

You pass a callback into that second parameter

#

the doc page has an example

cunning citrus
#

oh, sure

#

thanks

royal raft
#

Ive switched my code over to jobs but it seams to still be running everything on the main thread this is what ive got

public void March(int chunkSize, int chunkPosX, int chunkPosZ)
{
CreateMeshData job = new CreateMeshData
{
};

    JobHandle jobHandle = job.Schedule();
    jobHandle.Complete();

    List<Vector3> verticesList = new List<Vector3>();
    foreach (var vertex in job.vertices)
    {
        verticesList.Add(vertex);
    }

    List<int> trianglesList = new List<int>();
    foreach (var triangle in job.triangles)
    {
        trianglesList.Add(triangle);
    }

    List<Vector2> uvsList = new List<Vector2>();
    foreach (var uv in job.uvs)
    {
        uvsList.Add(uv);
    }

    MeshData meshData = new MeshData(verticesList, trianglesList, uvsList);

    job.vertices.Dispose();
    job.triangles.Dispose();
    job.uvs.Dispose();

    chunkGenerator.CreateChunk(new Vector2(chunkPosX, chunkPosZ), meshData);
}
untold moth
#

Which would block the main thread.

sly grove
royal raft
#

oh okay i understand what should i do to fix this i want the main thread to run like normal and no massive fps stop

#

couroutine?

untold moth
#

If you don't care about when the job would complete, you could check if it's complete in update, and only call Complete and use it's results then.

royal raft
#

alright in the game the player wont be able to move very fast so the amout of time it takes is no issue i just dont want the game pausing

#

thank you very much for the help!

sly grove
#

you could also use a coroutine and yield return WaitUntil(() => handle.IsCompleted);

royal raft
#

ill try both and see what works best

sly grove
#

your current code is looping through vertices and triangles etc in the main thread after the job is done which itself may be slow

royal raft
#

ill check it out thanks!

stiff widget
#

Does anyone know why my code might be freezing when i try to run this async function? I have tried to follow as many async await resources to figure out how to do this properly but my entire editor freezes when i press space. The intended behaviour is for the function to look for player left click and shoot a ray out to see if the player clicked on a Tile on the map, and then return the tile that was clicked.

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        Debug.Log("start");
        Tile tile = TargetTileAsync().Result;
        Debug.Log(tile.name);
    }
}

public async Task<Tile> TargetTileAsync(TargetType tt = TargetType.All)
{
    targetTile = null;
    playerInputState = InputState.Target;
    targetState = tt;
    while (targetTile == null)
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                Tile temp = hit.transform.GetComponentInParent<Tile>();
                if (temp != null)
                {
                    targetTile = temp;
                }
            }
        }
        await Task.Yield();
    }
    return targetTile;
}
untold moth
#

So since you're blocking the main thread, the next frame never comes, but it keeps on waiting for it.

stiff widget
#

my understanding was await Task.Yield() would ensure that it only ran once per frame, so this is actually blocking me from reaching the return?

#

in that case, is there a need to ensure that the loop only runs once a frame, and if so is there a better way to do that?

untold moth
stiff widget
#

yea i dont know why i missed that, so i could just return inside of the loop and it would work right?

untold moth
#

Mmm... I'm not sure what you're trying to do there. Returning in the loop would just quit the async function.

stiff widget
#

the purpose of the async function is to wait for the player to click on a valid spot on the map

#

and when they do that i want to return where they clicked

untold moth
#

That feels like a vary bad use case for async.
Why not just check what the player clicks in update?

stiff widget
#

I needed to call this function from a script that needed multiple different targets and i wasnt able to figure out how i would return that information from update

untold moth
#

Well, you could raise an event when a player clicks a tile. In your script that needs that info, subscribe to that event when you want to know that and each time the event is triggered, add a tile to a list. When you have enough info, unsubscribe from it.