#archived-code-advanced
1 messages · Page 82 of 1
oh, yeah I think I remember seeing something like that
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.
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
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
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?
- this is not advanced. this is #💻┃code-beginner level at best
- see how to correctly share !code below
- and finally, where do you call
start? because that isn't the same asStartwhich is what Unity will call automatically
📃 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.
There are many errors in your code. Compile errors are only one type of error.
then there are bugs on your code
btw code-beginner
Well, when I wrote it there, I posted it here because it didn't help. Thank you for warning me.
Because you didn't post your code properly there, nor here.
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.
we can easily read the code blocks if your code is colored and indented
Okay, I'll post it properly to the beginner section again, then have a good day.
Hi all. I want to check for inappropriate images within unity. Is there any sdk available for this?
dont cross post and what are "inappropriate images"
You do not want a "Unity" approach. Most approach will be Unity agnostic, you can simply use whatever you want.
I've been searching since morning. All I got was Google Cloud Vision. Nothing else. Can you direct me a bit about what to search for exactly regarding this?
Google Cloud Vision is one.
Amazon Rekognition would be an other.
Looks like a fine approach https://cloud.google.com/vision/docs/detecting-safe-search
you may need to learn how to send http request to google in c#
and it could be doen without unity
So what exactly should I do?
ok tanks
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?
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/
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.
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
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):
I am going to ask if it is really necessary to have to make your level from a PNG files. That would be really, really, really, constraining and unpractical.
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.
- 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.
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.
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/
Alright, I'll check these out. Thanks so much for your help.
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?
Sorry what's wrong with mutable structs exactly?
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
Whatever you're describing I'd wrap all that data up in one blittable struct and use a Native array of them
Awesome that's what I was thinking but I wasn't sure
There's nothing wrong with mutable structs in this context and that's pretty much the main tool for manipulating data in jobs
That's a relief-- and just just to confirm Unity.Mathematics' types are blittable right? (float2, bool2, etc)
Yes
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?
Yes, as long as the indices are not colliding, it's totally safe
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
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
Yeah that's why batch size for those kind of jobs need to be high.
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.
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)
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.
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
I made a mistake, I need to rewrite the code again.
Mathematics has its own quaternion type. "quaternion" lowercase.
I'll look into it though is my math even wrong to start with
I don't remember my trigonometry well enough to tell.
I just use quaternions to do my rotational math for me.
Lol fair enough
Where did you find that equation ? Pretty sure it is wrong. (You need 3 points and you do not want twice the math.atan2)
float signedAngle(in float3 a, in float3 b) => math.atan2(b.z, b.x) - math.atan2(a.z, a.x);
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
I worked it out on paper
It works so I just find it way more performant over the fresh hell attempt unity chose lol
I don't even know how it can work, you do not even have enough data.
You need 3 points
Have you tried it
I've done it multiple time. It never stick with me though always need to do some trial and error.
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
If it works then correct, it really isnt how I'm expecting it to work though.
Nor me but my math on paper led me to that solution
Did you logs the result or just assuming ?
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
Because I am like 95% sure that you want only a single math.tan2 and 3 points.
Because you need to have both vector ?
You mean pt-origin and the axis vector
I'll retest when I'm home
I see how the formula could work to find the angle. However, I still fail to find the required component (3 points or vector).
@dusty wigeon
i got it working
was passing in the wrong vector to the rotate function
the signed angle function works fine though
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.
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.
wouldn't that be extremely slow?
I'm making this for a large scale multiplayer game, so performance would be good
graph problem
you need a sparse set for storing the children
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
oh you may need a disjoint set
I see
but disjoint set not support disconnect, not work if the pipe can be removed
What you should be asking is what search algorithm you should be using to determine if a pipe is fully connected to the end
Yeah that's what I meant by that
run bfs
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
I'll try that
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
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
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
or bfs from target and source, slightly faster than one way bfs
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
nevermind to my nevermind, it still doesnt work 
Thanks Simferoce. So if using encapsulation, I would have to Enqueue from Class B using Class A attributes being called frmo class B right?
Attribute should be used by reflection?
Hey can traceinline for unity raytracing only do simple visability tests or can it return shading data?
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
try this
using UnityEditor;
[InitializeOnLoad]
public static class Reload
{
[MenuItem("Reload/Off")]
public static void Off()
{
EditorApplication.LockReloadAssemblies();
}
[MenuItem("Reload/On")]
public static void On()
{
EditorApplication.UnlockReloadAssemblies();
}
}
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
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)
Add torque?
oh ill take a look at that
could I use torque along with the player's current forces? @flint sage
Yeah\
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
Oh
suppose you had a planet orbiting a sun, what direction is the force applied to make your planet turn around the sun?
circular motion
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
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
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
ah ok. But in the example I sent, if I add force to the right, it will make the player's speed increase
which I don't want. They should just maintain current velocity
exactly - you need to apply the force perpendicular to the current direction of motion, at each point in time
yeah true I meant the magnitude increasing i suppose
btw adding acceleration adding perpendicular to v have no work done iirc
so you mean in the diagram I sent, to apply a force to the right of the player constantly? But then at the end they would continue in the same green line and make a circle
that mean ||v|| will not increase
yeah, but if you wanted it to eventually only move right then the amount of force you apply would change over time too
okay. so it would be related to the player's transform.right?
(or add a check to stop adding the force when you're moving right already)
it would be related to the current vector of motion
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
sorry yeah my bad
just realised
I mean depending on direction of course but in that scenario I thought it would increase speed
so you add acceleration perpendicular to v
and then what if the player was holding A and D instead of just D?
still perpendicular? and just less force
input handling is question for you
so the force should stop when the player's velocity = their desired velocity depending on input
yeah but how would the same physics handling work if the player was moving in a different direction
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
actually if the ||v|| downs then the acceleration have to be decreased too to maintain the original radius
this has had me busy for 2 days with 0 progress
i'm confused on how that would work in other situations tho
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
what does the dot mean? sry
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
yeah, it depends what kind of turning motion is desired, I think gradually decreasing it might feel more natural, but either works
ok i like this
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?
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
that would make sense to me
prefab is obviously a GameObject which cannot be cast to type ModelPrefab
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
But why is it only complaining in builds?
Prefab is not gameobject, it's a custom MB class
ModelPrefab MakeModel(ModelPrefab prefab, Transform location, Vector3 size)
not according to this it is not
WingTip_L UnityEngine.GameObject
@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
got it nvm
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?
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
How's your disk space doing? If it's close to full, then large copies can take longer.
I think it had a good 500GB free. SSD, that is
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
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>?
Nice. I think I've figured out how to write an automated test for shader code.
❤️ automated testing in video games
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?
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
What do you mean? What is your concern?
What does a “nice memory copy” mean
GPU profiling is not very reliable in general. It could be that the graph is showing the total GPU usage(including compute shaders and/or os usage), while the hierarchy only shows rendering related calls. Hard to say.
Using platform deticated GPU profiling tools might provide better info.
As opposed to a "nasty memory copy" I guess.😂
you have heard of memcopy right?
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
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.
Memcpy?
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.
I believe instantiate would be just as allocy
I dont think unity has SEGFAULTED on me even once haha.
Usually I get hit with the old failed to present swapchain
Yeah true which is a pain since I have to make multiple copies to modify each one
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.
Hello. Is there a way to hide codes in the shader just like putting #region in C# script?
Using value types might help if you experience performance issues due to instantiation.
Or it might make it worse...🤷♂️
For unity meshes how?
if the file is getting unwieldy you might consider separating it into different files and using #include
Ah, if it's a unity object there's not much you can do. Aside from maybe messing with the low level native buffers.
Oh yeah. Thanks!
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?
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
finally:
I ended up using a completely different shader setup, skipped the blur pass and worked it all through HLSL
yeah I think you're right
Thank you
But also, why would the tri count spike so randomly?
It's so still at 10 triangles the rest of the time
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?
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.
You can see them explain their default value of 32 here as:
// Store max 32 rtHandles
// 1080p * 32bpp * 32 = 265.4mb
https://github.com/Unity-Technologies/Graphics/blob/d9de9c24bce4757cd3ffd65f7ffeeb49fe6196a2/Packages/com.unity.render-pipelines.universal/Runtime/RTHandleUtils.cs#L25
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
You can potentially cut out the texture middle-man depending on how you're generating it
How are you generating noise?
i think they added a new feature that if you deleted system 32 on your computer you get all of the required code
otherwise just pour around 5 gallons of pepsi inside of your pc or ontop of whatever you're using
<@&502884371011731486> Shitposting
no swearing pls 😭
Actually swearing is allowed on this server as long as it is not gratuitous, which in your case it most definitely isn't
in the #📖┃code-of-conduct it says to respect each other and not dismiss other people views
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
@fallow valve Stop posting nonsense, thanks.
fr fr
guess you really tried hard to be funny. To no avail. I've heard if don't have anything useful or witty to say, you shouldn't.
Meanwhile, I'm already writing this in compute shaders
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;
}
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
}
📃 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.
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
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?
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
You can download all that data in a csv file : https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee
It is only a few lines of code to then load and read that csv file in your code.
You can have a TextAsset public variable that you can drop the .csv file into.
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
Good to hear you found a solution 🙂
I'm creating a RTS based on periodic table, time to turn the table on RTS gaming 😄
Sounds fun 🙂
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
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.
Ah, what the docs neglect to mention is it's completely asynchronous so tearing it down immediately after means I get no callbacks 🤦♂️
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?
Would setting the transform.up to be the negative of gravity work in your case? Iirc when I did this, you'll also need to adjust the camera separately if using cinemachine through its WorldUpTransform, I think that's the name at least. Then to keep movement the same, you might need a change of basis
No that hasn't worked
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)
Are you worried about the amount of Vram it takes or the time it takes to upload it? Also how often do you need to do that?
I need to be able to do it frequently, without causing a massive stutter
And yeah the amount of vram
You need to send data from CPU to GPU frequently? Why?
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
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.
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
Can't all the possible textures be loaded into it at start?
Also, if you need to write a texture to the atlas, just do it in a compute shader. You don't need to move the atlas between CPU and GPU for that. In fact it would be super inefficient imho.
I know it is
And that’s what I do
But I wanted to compress it which requires cpu side texture2d(and texture2d is faster to sample than rendertexture at these sizes) which I don’t want to do
So I am trying to find another way that doesn’t require cpu side to reduce vram
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.
Hmmmmm
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.
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
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?
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.
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)
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?
This is a partial screenshot from the prefab I'm talking about. (Gameobjects children are not included):
That's a very broad question. Unity lets you do mesh modification at runtime through various APIs. Unity doesn't care what modifications you're making.
there are csg libraries for C# like this, no idea if it works with unity out of the box but it's a start maybe https://github.com/praeclarum/Csg
But how would I go about doing it with code? I've found packages but they don't support runtime editing
Typically when vcontainer gives you a hard time you’re probably trying to do something that it thinks of as a bad idea. It’s very particular about what good use of a DI container looks like. In that regard it is very much not like zenject.
Actually I had a hard time since I've been trying to convert Zenject to VContainer but figured out things step by step and by so many tests and reading docs precisely (There are so many hidden things).
Could you tell me what's wrong with injection on instantiated child which has its own LifetimeScope ?
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.
So i am learning python# ++ what do you think of my code?
It IS spelled corecctly👍
Ah, trollin got me lol. That's what happens when I look at only one line barely
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.
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.
if it's just for this one object and bringing in a library would add too much, maybe just roll your own JSON with a StringBuilder?
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.
yeah that was basically my plan when i have more time now write something custom. Just thought maybe someone knew of a simple tool. For now i basically sent the whole JSON , along with a list of changed keys to JavaScript and pruned out the keys I didn't want to save there. But seems wrong heh
so I Underestimated how MUCH LONGER it takes to sample a rendertexture vs a texture2d
as in
its gone from 1.2ms in this kernel that samples it
to 4.8ms
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)
How are you reading the texture?
in a compute shader, incoherently
I'm surprised it's 4 faster
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
anything I can really do?
What format is your rendertexture in?
Does your texture2d have mipmaps?
no
Is it compressed?
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
I'm just trying to figure out where the performance difference is coming from
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
Are your rendertexture and texture2d the same memory size overall? I assume they have the same resolution
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
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
yeah 99% sure they are...
Then there's probably not much you can do. RTs are probably optimized for writing, not for reading
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?
Do you really need a 16kx16k texture ...
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
Does not really seem viable
no other option
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...
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.
oh believe me I already have
Why you want to do that ?
because there is no other option
no bindless
texture arrays are out because they only allow same sized textures
etc.
What is the requirement that force you to do that ?
There is a reason why you want to do that.
that I need ALLL these textures in a compute shader
beacuse what I am making is a renderer that runs in a compute shader
full pathtracing
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.
not for what im doing
a pathtracer that doesnt use RT cores that runs in builtin, hdrp, urp, etc.
yes I know about this
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)
I usually have a wrapper(AudioObject) around AudioSource that handles FadeIn/FadeOut.
https://pastebin.com/6Y6uSF2i this was/is my solution.. it works but feels smelly, I dunno 🤷♂️
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
Starting at 0:32
seems like it works well enough?
You could explore some of the effects in audio mixer perhaps?
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
If you are not familiar with AudioMixer you definitely want to learn how to work with it. It enables you to easily manage sound categories and balance sound. in my opinion, it is a must for any game that respect itself.
Well see that's where you got me.. none of my games are respectable. 😛
😦
But I'll read through this.. it might be just what I need since I rolled my own for the past few projects
IF ANYONE HAS A SIMILAR ISSUE
ARAS_P HAS A WAY TO DO THIS!!
https://github.com/aras-p/UnityGPUTexCompression/tree/main
Anyone know how I would go about calling a function from an instantiated component in unity from a script outside unity?
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();
}```
I have a process running outside of unity that'l need to call specific functions within the unity process
I know that
you said that
That part isn't relevant to the "function from an instantiated component in unity" part though
Well I cant just call instantiate in another process can I?
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
Oh, no lmao the opposite, that's the hard part for me calling a function from a different process
Ok, your extraneous details confused me.
Your options depend on what platform you're on
Preferably desktop, WebGL can also work as I'm pretty sure it has a JS hook api
You need to establish some sort of interprocess communication, doesn't matter what.
Yes WebGL has the json api.
For desktop you need, yeah^
Yeah ideally on desktop I can get some sort of interprocess communication, do you have any idea on how I can achieve this?
Any idea how I can achieve this>
?
TCP is one pretty universal option
as in establish some sort of websocket connection?
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 :)
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
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.
(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 😅 )
Does it necessarily need to run on different threads? This won't be client facing so some lag would be fine
in the unity process it should
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
Ok cool makes sense thanks a lot for the help!
I don't think the underlying WebSocket implementation uses HTTP. HTTP is used to set things up and things like ports are reused, but I don't think you are paying the cost of HTTP to use WebSockets.
Not exactly sure what you mean by JS hook API. For a crossplatform (namely including WebGL) communication you need to use WebSockets instead of directly using TCP.
https://github.com/James-Frowen/SimpleWebTransport handles client, server and the JS bridge for Unity WebGL.
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
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
Code
Classic unity server being very helpful
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
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.
My point being obviously I would need to code something
This person above was actually helpful in pointing me in the right direction
From what you were saying, it seems like you were looking for a all of nothing solution. Hence why I answer Code.
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
📃 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.
Does anyone have a script for a 2d.mobile game that lets you move side to side
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
read #📖┃code-of-conduct and #854851968446365696
Also posting the same question in 4 channels is not something we do here
Just for the record I don't think being an ass fixed anything. Fen said it best
What do you mean ? Fen literally said nothing. I apology for coming out as an asshole. As I stated, it seem to me that the user was probing for a out of the box solution (3rd party). It seem to me that the best way to achieve what the user wanted was code.
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.
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!
point is a keyword in HLSL
Can't use it as your variable name
ah ok thank you
is there an interface that would allow writing generics for both c# array and NativeArray ?
cant understand, native array doesnt allow reference type (idk if it is allowed in ecs)
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
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)
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.
Both array and NativeArray can be converted to a Span without a copy.
thanks for the idea, I'll need to profile that (a lot of calls, so even a tiny overhead can compound)
or I can just convert before the calls 🤔
Sure
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?
These things are normally called decals. Rendering them in 3D is more complicated, I'm assuming Fruit Ninja fakes it since the game is basically 2D, so probably just a billboard rendered with decreasing opacity.
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
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?
You mean how you would use different textures in the particle system?
Yeah
You can use a spritesheet, and then set an index
For example a random one from this list
This might be a dumb question but where do I set the sprite?
It's set in the material assigned to the particle system renderer
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,
Random peeks into the C++ side of Unity, which you need to pay a license fee to access it
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
yeah
it's just a matter of following the spec exactly
I had some trouble correctly implementing the Mersenne twister..
thats floating point for you
I am recreating a feature of a unity game into a website.
If there were more digits, I'd wonder if this was because of your rounding mode
yes
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.
Kay i just tested my code with the game. i am accurate down to the 6th digit
C#: 0.976958990097046
JS: 0.9769588711152223
I wonder if it is possible to make the particle run in a specific position? (In this case in the place the mouse clicked)
What do you mean by run in? Appear in?
Thanks for reaching out. The api has a method for that already called EraseSwapBack. The problem i assume was the event is checking the ev.index against the objects in the list and its going completely out of order. Each sphere has a position and radius. So its index must be the order of the array. So even if 5 is put in place 2, its index will be 2 and not 5 right?
JS uses doubles everywhere. Perhaps that's your issue.
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)
im working on making this a unity WebGl application instead of pure js
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
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)
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.
Yes, this is possible. The best way (in my opinion) is to use dependency injection (just google it, it’s a big topic). The short explanation is that you should be using interfaces for everything that needs to behave differently on different platforms, and then have different implementing classes for each platform.
Pretty sure you want to use preprocessor directives for multi-platform ?
Preprocessor directives are how you would select which implementing class would be used for each platform. Dependency injection is how you avoid littering your code with preprocessor directives at every point that touches the class in question.
@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.
Never said you didn’t.
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
Did you profile ?
Anyone experienced with webrtc could help?
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
Without any context my guess is this callback is running on a background thread and you are accessing some Unity object from this code causing that thread to gracelessly die
No idea what an ice candidate is though
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
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
Did you use wireshark to see if any packet are being sent ? Also, did you read the tutorial ? It seem that you need to do some setup before end.
public class MyPlayerScript : MonoBehaviour
{
private void Awake()
{
// Initialize WebRTC
WebRTC.Initialize();
}
}
https://docs.unity3d.com/Packages/com.unity.webrtc@2.0/manual/en/tutorial.html
So you can't edit these compute shaders to use variants?
not very easily no
webrtc.initialize is deprecated in pre6
They might have change the procedure
i think there's no initialization right now at all
you just create the peer connections
@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
Anyone know how to make an infinite terrain generator with biomes using only code?
maybe scale down your question a bit
ofc people know, but this is just too much to answer
I have an infinite terrain generator here (https://github.com/SebLague/Procedural-Landmass-Generation/tree/master/Proc Gen E21), I just need to know how to make it have biomes
and get it flattened out a little
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!
what's your goal? do you have a budget?
a budget?
what are you trying to do? big picture
setting up multiplayer for my game
i have the lobby system/servers, everythings done
bit struggling with the webrtc part
hmm, why are you using webrtc for this? what is the idea?
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
got it. what platform is your game intended to be played on? WebGL?
android/desktop
hmm
but i think i figured out what the problem was, so dont worry for now 🙂
imma go to sleep and fix it tomorrow
you probably want to use playfab
ICE candidates werent serialized properly for the signaling server
for whose signaling server? the one that is written as a bunch of javascript scripts, in the render streaming repo?
nah man, i want my own soliution. Everything stands on my servers/database
i like to be in control of these
so one that you authored?
what?
hmm
webrtc is the way to go for me
i think you are at the start of a very long journey
im halfway done with the webrtc part
that's all that's left ;D what are you talking about
you are like 5% done with the webrtc part lol
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?
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
okay, and you want this work over a cell connection?
@fresh basalt are you located non-US? if so, disconnect your phone's Wi-Fi connection so that you're using your cell connection. then visit https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/ on your phone and tap Gather Candidates. Then take a screenshot of your results and post it here
WebRTC code samples
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
ill try, thanks
Yeah, that is what I am trying to figure out, also how to smooth the terrain out(it is only mountains)
I have an infinite terrain generator here (https://github.com/SebLague/Procedural-Landmass-Generation/tree/master/Proc Gen E21), I just need to know how to make it have biomes
and get it flattened out a little
Research how procedural terrain generation work. Usually it involves generating the terrain data(whether it's heightmaps or signed distance field) with different combinations of noise with different settings. You can use different noise settings at different areas to make bioms.
how would one place objects in a world(trees, rocks, grass, spawn locations for animals, towns)
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
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?
I'd like to expand on @jolly token 's answer. It seems like you are trying to define game parameters on a large scale (multiple monster, characters, abilities etc.). If so, Unity's UI is not the solution. All large game companies use those shits 😄 (Excel, Goolge sheets, CSV)
ISerializationCallbackReceiver
Actually they have a serializable dict in their example
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
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.
Finnally found my problem!! I had to clean the resultAppendList, only the first one is used in PointerInputModule.cs, and the first one in the list was the raw image of the texture renderer
Does anyone know how to spawn objects when making terrain?
What do you mean by spawn objects? Like adding trees and grass to the terrain?
yes please, like trees, grass, rocks, and buildings
if it helps it is a mesh terrain
Unity has a built in terrain editor that allows you to create trees, grass, etc, and paint them onto the terrain
this is an infinite terrain system tho
Oh I see, so you aren’t using the terrain system
Procedural Landmass Generation in Unity. Contribute to SebLague/Procedural-Landmass-Generation development by creating an account on GitHub.
here is the code for the terrain generator
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?
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 ?
¿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.
In the editor only, you can do this: https://docs.unity3d.com/ScriptReference/Animations.AnimatorController.GetBehaviours.html
I just realized there is also a Animator.GetBehaviours, are they equivalent?
Great, thanks
what transforms do I need to apply to a skinned meshes vertex buffer to fully put it into world space?
transform.TransformPoint does it, no?
no
I need the matrix chain so I can feed it to a compute shader
but what transform would that be from?
holy heck I think I figured it out
after 2 years
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
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)?
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
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());
}
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?
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
Function from the last case.
okay, i might have to watch it first
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...
thanks a lot, there will be no wind. Since its only a 2d game
damn, i hate phyisics hahahaha
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
Anyone know how to make objects get spawned in an infinite terrain
Spawn them as you go. You'd probably need to spawn new chunks anyway. That's a good timing to fill it with objects too.
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.
Look into Unity Relay
Ask in #archived-networking. I don't believe you would want a relay if you are planning to use dedicated servers.
how
I use https://aws.amazon.com/gamelift/ professionally. It works correctly. You have matchmaking function and scaling.
How to spawn objects? Instantiate() or use a pool or something.
ok
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
How is the effect implemented? Is it a postprocessing effect using a shader? If so #archived-shaders .
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
Unity has overrides for the null check so ? will not work correctly on any object inherited from UnityEngine.Object
Someone is experienced in rts game terrain generation and performance?
That means ? operator will always return "not null"?
no, it means it will not always be accurate. Specifically for Destroyed objects
oh ok, got it. Thanks!
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?
You would need to create your own pop-up at the moment you want. Maybe something like EditorUtility.DisplayDialog can do the jobs.
Thank you for reply 🙂
Please always ask your question directly, don't ask for someone to ask your question to
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;
}
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:
- Unity hits server with a login/register request.
- Server authenticates with Azure AD, and then returns token to Unity client.
- Unity client sends subsequent requests with the token to the server.
Why cant you just do it once per frame ?
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
I mean, the mouse cant move in a while loop not threaded,
I suppose you could do something with async here (maybe using Awaitable to check the currently-hovered tiles every frame on the main thread)
not sure what this means
Personally, I'd flip things around: when the player picks a target, you tell the ability system to activate an ability
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
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
}
}
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
I thought about including some of this in the update code but it felt clunky to have the function to wait for a tile to be selected in the update function and i couldnt think of a more clever solution
your solution could work where the function just flags the tryingToPickup bool
Not sure what you mean. What is wrong with using update ?
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?)
Thanks! I'm going over the documentation right now
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?
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?
What kind of overhead are you worried about?
Also copies, or references?
Have you profiled it?
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.
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
public class NPCChannel : ScriptableObject{
public UnityAction<NPCEvent> npc_event;
public void RaiseEvent(NPCEvent _event) {
npc_event?.Invoke(_event);
}
}//EO NPC channel
So that's a regular delegate, not a UnityEvent
It works like a normal C# delegate, because it is one
It would work exactly the same as a plain C# class in terms of performance.
awesome. Is there any real benefit to having it in an SO?
You can drag it around in the editor.
would it be better as just a C# class that other scripts reference?
If you don't care about referencing it in the editor
If you don't need to reference it in the inspector, sure.
haha, thanks!
This looks like you should be using event here rather than a raw delegate btw
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
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
Right so
Putting event on the delegate will ensure that it can only be invoked by calling that function
like public event UnityAction, or in the method RaiseEvent? I never studied coding, self taught.
The first
Thanks for the info 🙂
Most of us are self thought here, but that doesn't prevent you from getting to the "pro level". Just read the documentation and fill gaps in your understanding.
If anything, programming is all about self teaching.
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 😄
Nvm. Misread the message 😅
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!
It depends on the situation. You don't always need to decouple code entirely. Sometimes one way dependency is what you want.
in what cases would you want dependancy?
Indirection makes things slower and more confusing to read
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
i see. But for static events this would be a good choice?
(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
anyone else experiencing Resources.Load returning null if called during initial asset import in Unity 2022?
i got the grass to spawn at the top but now the ores just spawns everywhere
nvm, got it to work
you should store the value of random.value, otherwise it will be called multiple times in else if()
but that is what he needs to resample after every failed if
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 😦
Use prefab edit scope, I will enable you to change whatever you want to change in same way you edit a normal instance.
Nice, i did not know about this one, sadly i can check this solution at monday not now. Anyways, thank you, i will let you know if it worked 😄
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);
}
}
}```
you'll have to be more specific than that
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:
Anyone got a fix for this
NullReferenceException: Object reference not set to an instance of an object
set the object in your inspector or your scripts also #💻┃code-beginner
That is the most common error you will run into
https://unity.huh.how/runtime-exceptions/nullreferenceexception
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.
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 
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.
AlchemyBow official website
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
Side note, you can write:
if (obj is Mesh mesh)
_meshes.Add(mesh);
yeh i know ill clean the code later
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
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.
Heey, is there any way to detect sunset in real life and make something happen in the game?
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
There is a formula for that. https://en.m.wikipedia.org/wiki/Sunrise_equation
@compact ingot And how could I applicate it on unity?
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
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?
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??
I dont use dependencies but there are 2 places when you can define if dependencies are required. One when you upload your package to the publisher portal and one in the portal before you submit your asset
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"
}```
where is your Debug.Log of requestURL ?
exactly, so how do you know what is being passed to the WebRequesst?
you are making an assumption on the output of
string requestURL = url + "lat=" + latitude.ToString() + "&lng=" + longitude.ToString();
without actually checking it
I know but that does not mean he used EXACTLY the same data as you
how would be the fixed code?
?
No, not until you show me what I asked for
obviously you should be logging the actual URL you are sending the request to and ensure the parameters you are passing are actually valid instead of making assumptions
https://api.sunrisesunset.io/json?lat=38.907192&lng=-77.036873 Is the API url what you are asking me about?
I want to see a screenshot from the console
I've already tried it, and it works
then show the log
it's like you're not even reading what anyone is telling you
Still no Debug.Log of requestURL
I read evrything you tell me, its quite difficult to answer to people at the same time, im new at coding and my english level is not the best, so i say sorry
then why are you in the advanced channel
Oh, i got what you want
500 internal server error means it's an error within the server itself. You would have to look at the server logs and see what that says
if this is not a server/api that you own or control, you should be asking whoever runs this API about it.
And I bet it's a parsing error on the URL
literally just Debug.Log(requestURL)
Still no Debug.Log on requestURL. At this point I give up
when someone ask you to debug some variable, they want you to debug.log("variable is "+variable) and show the screenshot
. becomes ,
Is that the game is sending comas instead of points?
ofc, this is what you passed into web request
no, it is your OS regional settings
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
or use InvarientCulture
@cunning citrus Now do you understand why you need to check not just assume?
Yeah, thanks for your patience... I didnt understand really good what you were saying me
If you had done this when @warm mica first asked you to do it this problem would have been solved long ago
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
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
@glossy cargo Throw a debug.log, or better yet, a breakpoint in there and read the values at runtime
dont cross post
alr thx
yeah, that is a #💻┃code-beginner topic, not advanced . . .
Happy to help 😄
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.
Tutorials and Videos on the games I develop!
twitter - @TaraRaeDev
email - taradoak42@gmail.com
can anyone recommend a site with common terrain noise functions ?
some sort of height function database or cheatsheet ?
there is only really perlin- and worley(voronoi)-noise (including their variations) that has any relevance to terrain generation.
yep, I understand that, just that you can get really creative with those few noise functions to get vastly different end results
trying to find good starting points for different types of landscapes and go from there
so I don't start from scratch
you should maybe download gaea and world machine demos and play around with them
just to get a feel for the functions
thank you, I'll have a look
you can waste a lot of time with terrain generation, its a rabbit hole
fastnoise is life
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
right, you reminded me of terrain stamping, I should add it to my to-research list
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
it's a project for fun, so I don't mind researching and poking at it, I'm not in a "I need this working soon !" mindset
that is very helpful
basically you can't make large maps in unity without a lot of pain and suffering in terms of workflow/design/authoring-experience
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)
that sounds like a reasonable size in unity
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
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
yeah, I moved everything on the GPU, tried generating in unity jobs first, but it was slower than I hoped
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
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
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.
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
how expressive do you want the terrain to be?
just some random hills or do you want actually impressive scenery?
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 😄
thats probably going to not happen
^something like this is never going to come out of a proc-gen terrain
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
for sure
Just keep throwing noise maps at it
eventually it'll look good (or worse)
good read
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
Is there a point for the EnemyStateFactory or I'm overengineering?
It's almost the same as creating states in the enemy class.
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
Trying to understand the idea behind the class. Do these states differ from each type of enemy, or is this the same assignment throughout?
They are the same for all enemies, because theirs behavior is the same.
yes, you are overengineering
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
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
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...
There are minecraft specific details that are irrelevant to you, but the overall structure of their system is useful
thanks, sounds like a good watch indeed
I don't know how I didn't think of minecraft
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
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
thanks if you mind what is locking ive never heard about that before?
i remember c# collections will throw exception when >= 2 threads try to write at the same time
Just look up C# locking
ok thanks!
Basically says that no other thread is allowed to access the same object at once
i just want one thread to do all the generation just not the main one
might want to take a look at Unity jobs system
that's what I use for parallel mesh generation off the main thread
ok ill take a look thanks for the suggestion
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
ok thats good then i realy appreciate this since im new to jobs and multithreading
they implement locks but hidden, and no lock in unsafe collection
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
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.
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
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
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
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)
If there’s a known and reasonable max limit, you can also consider just have a bunch of overloads, each argument is an enum.
I dont have a problem with the search time. I just want to avoid the garbage being generated by strings
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());```
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
Use the version of RequestUserPermission that has the callback:
public static void RequestUserPermission(string permission, Android.PermissionCallbacks callbacks);
https://docs.unity3d.com/ScriptReference/Android.Permission.RequestUserPermission.html
And how the code would be?
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);
}
Completing a job, means that you wait for it to complete at that point.
Which would block the main thread.
- Only the CreateMeshData job itself will run in the job system here
- Since you are calling
Completeon the jobhandle right after you schedule it, your main thread will block until the job completes anyway
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?
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.
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!
you could also use a coroutine and yield return WaitUntil(() => handle.IsCompleted);
ill try both and see what works best
BTW if you're trying to generate a mesh in the job system your best bet is probably to use https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Mesh.MeshData.html
your current code is looping through vertices and triangles etc in the main thread after the job is done which itself may be slow
ill check it out thanks!
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;
}
Because you're yielding in it for the next frame, but trying to get results right away(basically defeating the point of it being an async function).
So since you're blocking the main thread, the next frame never comes, but it keeps on waiting for it.
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?
Task.Yield yields the execution for one frame, it's like yield return null in a coroutine.
yea i dont know why i missed that, so i could just return inside of the loop and it would work right?
Mmm... I'm not sure what you're trying to do there. Returning in the loop would just quit the async function.
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
That feels like a vary bad use case for async.
Why not just check what the player clicks in update?
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
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.