#archived-code-advanced
1 messages ยท Page 67 of 1
The first two dodges are going forward, the third is to the side
the first two dodges hit their target perfectly, however the third goes way off course
The third one ?
play the video
In the video, or always ?
What is different ?
Nothing as far as I can tell in my code
float deltaForward = this.rootMoveCurveForward.Evaluate(t) * this.rootMoveImpulse;
float deltaSides = this.rootMoveCurveSides.Evaluate(t) * this.rootMoveImpulse;
float deltaVertical = this.rootMoveCurveVertical.Evaluate(t) * this.rootMoveImpulse;
Vector3 movement = new Vector3(
deltaSides - this.rootMoveDeltaSides,
deltaVertical - this.rootMoveDeltaVertical,
deltaForward - this.rootMoveDeltaForward
);
movement += Time.deltaTime * rootMoveGravity * verticalMovement;
if (characterLocomotion.character.TryGetComponent(out PlayerCharacterNetworkTransform networkTransform))
{
// TODO make this not use the local player's rotation, but rotate to the target direction
//movement = characterLocomotion.character.transform.rotation * movement;
Vector3 direction = networkTransform.currentPosition - networkTransform.transform.position;
direction.y = 0;
direction.Normalize();
Quaternion viewDirection = Quaternion.LookRotation(direction);
movement = viewDirection * movement;
}
else
{
movement = characterLocomotion.character.transform.rotation * movement;
}
characterLocomotion.characterController.Move(movement);
rootMoveDeltaForward = deltaForward;
rootMoveDeltaSides = deltaSides;
rootMoveDeltaVertical = deltaVertical;```
Then, why 2 on 3 works ?
this is the whole function
I have no clue
Then, use my script.
And then adapt it.
But first, make it work.
Same if there is nothing else then a character an a target.
I'm adapting rn
This is a method of debugging. You start with what works and goes towards what you want.
same result still
protected void UpdateRootMovement(Vector3 verticalMovement)
{
float t = (Time.time - this.rootMoveStartTime) / this.rootMoveDuration;
float deltaForward = this.rootMoveCurveForward.Evaluate(t) * this.rootMoveImpulse;
float deltaSides = this.rootMoveCurveSides.Evaluate(t) * this.rootMoveImpulse;
float deltaVertical = this.rootMoveCurveVertical.Evaluate(t) * this.rootMoveImpulse;
Vector3 movement = new Vector3(
deltaSides - this.rootMoveDeltaSides,
deltaVertical - this.rootMoveDeltaVertical,
deltaForward - this.rootMoveDeltaForward
);
movement += Time.deltaTime * rootMoveGravity * verticalMovement;
characterLocomotion.character.TryGetComponent(out PlayerCharacterNetworkTransform networkTransform);
Vector3 direction = networkTransform.currentPosition - networkTransform.transform.position;
direction.y = 0;
direction.Normalize();
Quaternion viewDirection = Quaternion.LookRotation(direction);
movement = viewDirection * movement;
characterLocomotion.characterController.Move(movement);
rootMoveDeltaForward = deltaForward;
rootMoveDeltaSides = deltaSides;
rootMoveDeltaVertical = deltaVertical;
}
Alright, you need to start with what works.
Not from things that does not work.
Start a new scene.
Place a cube and a target.
Then try it.
It it works
Go next step
If it does not.
Maybe there is something I did not understand correctly.
I do not want see anything about PlayerCharacterNetworkTransform or characterLocomotion or rootMoveCurveForward.
I'm trying to get the position that unity cursor is at in this screenshot. The game object "k_u", like all the other keys, are from a keyboard model split in blender so they're all rendered at the same localposition (0,0,0), but display at the appropriate places because I think the meshes are offset off their original origin. I'm trying to place another object at this exact spot, but example.position + key.GetComponent<Renderer>().bounds.center + key.transform.position isn't it. Anything else I can try? (Also tried local position since the example transform is parented at the same parent)
why not just key.GetComponent<Renderer>().bounds.center?
Thank you! I was convinced bounds is in local space for some reason... still a tiny bit off but I can figure it out from here!
A quick saunter over to the docs could cure that ๐
Im trying to rotate my character and controls based on gravity, treating it kinda like the entire world rotates but am really stuck on the math. The player hips and camera is supposed to rotate so it aligns with the world after the gravity shift. The player is supposed to look where the camera does.
https://paste.ofcode.org/7ghK96TR8hXnjdjUtHsU6
For the code: GetRotation() is used to copy rotations from an animator to my joints and this works already. lines 28-32 arent important, its just for other body parts. I only need this extra gravity and camera rotation to apply to joints[0] which are the hips.
I know why this doesnt work, because i am using the Y rotation from the camera newRotation *= Quaternion.Euler(0, -input.LookRotation.y, 0); . When gravity shifts, the camera shifts, and Y no longer makes sense. When im sideways I assumed I could just use the X or Z rotation instead... but i have no idea how id actually calculate this based on gravity.
I did manually figure out that with gravity (-9.81, 0, 0) i could use
newRotation *= Quaternion.Euler(input.LookRotation.z + 90, 0, 0);
and (9.81, 0, 0) i could use
newRotation *= Quaternion.Euler(-input.LookRotation.z + 90, 0, 0);
but this doesnt allow me to apply gravity in any (x, y, z) like (-5, -5, 0) since I cant just precompute every combination. I also solved these rotations through brute force, so I dont fully understand them.
So my question is, how can I calculate what to rotate my players hips by so it looks based on the correct axis?
You want to change your coordinate system. Here some video that explain the topic. I tried my best, but could not come up with a good explication...
https://www.youtube.com/watch?v=P2LTAUO1TdA
https://www.khanacademy.org/math/linear-algebra/alternate-bases/change-of-basis/v/linear-algebra-change-of-basis-matrix
How do you translate back and forth between coordinate systems that use different basis vectors?
Help fund future projects: https://www.patreon.com/3blue1brown
An equally valuable form of support is to simply share some of the videos.
Home page: https://www.3blue1brown.com/
Future series like this are funded by the community, through Patreon, w...
In pratice, it just mean to use Transform.InversePoint or Matrix4x4.TRS(...).inverse.Multiply3x4(point);
ive studied change of basis in uni before, ill see if I can use this thanks
I guess it is changing the coordinate system, but i might just leave this feature to work upside down only because i didnt think this would be so math heavy :p
Then you should be able to navigate this pretty easily, I'm like 90% sure this is what you want.
Yeah, it might introduce a lot of issue as most code usually expect to use the standard coordinate system.
it does make sense to use this, i only need to use it to change which way the player is rotating and like which way I am limiting the players speed
Hello there, I am trying to learn how to use the MeshData API but can't find any good examples of it, so right now I am struggling with this, I am triying to set the position of the vertices on the variable TestVer but the array lenght is always 1 and not 4 as the vertex count so I can only accesstestVer[0]and not other values, am I missunderstanding how this works or am I missing something?
Here is my code
Mesh mesh = new Mesh();
mesh.name = "chunk";
vertexAttributes[0] = new VertexAttributeDescriptor(VertexAttribute.Position, dimension: 3);
vertexAttributes[1] = new VertexAttributeDescriptor(
VertexAttribute.Normal, dimension: 3, stream: 1
);
vertexAttributes[2] = new VertexAttributeDescriptor(
VertexAttribute.Tangent, dimension: 4, stream: 2
);
vertexAttributes[3] = new VertexAttributeDescriptor(
VertexAttribute.TexCoord0, dimension: 2, stream: 3
);
//Set vertex buffer
meshData.SetVertexBufferParams(vertexCount, vertexAttributes);
//Define a submesh
meshData.subMeshCount = 1;
meshData.SetSubMesh(0, new SubMeshDescriptor(0 , triangleIndexCount, MeshTopology.Triangles));
vertexAttributes.Dispose();
//Set vertex positions (should depend on vertex count) but lenght is always 1 (vertexCount variable is 4)
NativeArray<VertexData> testVer = new NativeArray<VertexData>(meshData.GetVertexData<VertexData>(), Allocator.TempJob);
var pos = testVer[0];
var pos1 = testVer[1];
var pos2 = testVer[2];
var pos3 = testVer[3];
pos.Position = 0;
pos1.Position = math.right();
pos2.Position = math.up();
pos3.Position = new float3(1f, 1f, 0f)
Seem like you might be missing the call to SetVertexBufferData
https://docs.unity3d.com/ScriptReference/Mesh.SetVertexBufferData.html
is there any sample from. unity about to use addressables + scriptable?
Mystery-Puzzle:
I got code running as a coroutine. It loads a scene called "Loading" directly, and then the actual target scene asynchronously.
The time to asynchronously load the scene increases from 0 seconds to roughly 15 seconds and more, by waiting BEFORE even starting the load.
can it be related to the lifetime of the object the coroutine is running on?
I think i found my answer: The 15 seconds i actually "forever until whatever" and its the while (!loadOperation.isDone) loop that never exceeds a progress of 0.9f because allowSceneActivation is not set. All that is according to documentation.
The yield return wait line seems to change how the async loading works and makes it synchronous., which is still a mystery but not one that keeps me from doing my job.
thank you very much! i was starting learning how is made this project
its a bit complex to start learning from there but well i will try it
There is Youtube Video on this project
because i was starting using scriptables in my project as a littel data container
In this second devlog, we look at how we employed ScriptableObjects to create a flexible and powerful game architecture for "Chop Chop", the first Unity Open Project.
๐ Get the demo used in this video on the Github branch:
https://github.com/UnityTechnologies/open-project-1/tree/devlogs/2-scriptable-objects
(compatible with Unity 2020.2b and la...
An example.
yes i was see this video yesterday
(Also, I am not a fan of what they are showing)
or maybe classes like that should be protected and not to be used on scriptable?
what do you mean?
Scriptable Object should be immutable.
well, im using on my projects to control the AI as does unity tanks with scriptables, and i never change is values
That sounds like a you thing. Plenty of good use cases for mutable ScriptableObjects
but i used also for unlock and modify values in some small scriptable and i think we can avoid to change or not each data container
dependency injection like zendesk vs sciptable, i cant find anything in google
Yes, but it should be noted that ScriptableObjects are technically assets, so the behaviour they show in editor does not match the behaviour they show in builts.
This is a "me" things as you stated. There is multiple advantage, there is also some disadvantages however nothing is clearly better or worse.
Making them immutable reduce the amount of issue due to different behavior in build and editor, prevents memory leak due to unloaded asset and reduce the complexity because they are simply data from my experience.
On the other hand, ScriptabeObject facilitate the implementation of things like Channel or Singleton by the fact that you can directly reference them. However, note that we can still have the same behavior without the usage of mutable ScriptableObject without extensive code by having a script that "consume" the ScriptableObject.
From my point view, ScriptableObject is the same as using Json to define the characteristics of your game. You do not have behavior associated to them.
Every dependency is also included in the Addressable.
once the object is loaded all direct references will also be loaded into memory
yes i know, im testing and works, so idk if its better to doing different
if you want dependencies not to be loaded in immediately, use AssetReferences
However, you should still try to keep things track correctly and organize. I do not know if duplicated asset is still an issue.
yes also i get a reference to the main object addresables that instantiate prefabs and when i move to menu i unload the object addressable, but will be removed also objects instantiated by the main addressable?
yes i know
so maybe is better to keep all items removed after move to menu, instead of add to my scene and addressable with all of his objects, to load an addressable scene in order to remove all items included when i remove the scene ?
Im trying to figure out whats the best way to store a ScriptableObject/Prefab Script pair. My goal is to have an in-game menu that lists selectable models but im not sure if it would be better to store the Prefab Script reference inside of the ScriptableObject so that the SO is what is pointed to by the menu, or have the ScriptableObject stored inside of the Prefab Script so that the Prefab Script is what is pointed to by the menu. Is either better than the other?
Functionally, it probably doesn't matter, but referencing a scriptable object is cleaner. Referencing them in something like a menu is the intended way to use them afaik
Usually, you have the ScriptableObject have the direct reference on the prefab as it is the one responsable to construct it. Then you have a reference on the ScriptableObject from the actual "main component" of the object.
in my situation both the prefab and the scriptableObject are resources for the assembly of a larger object. The prefab really only exists so I can set up animations.
In my case im trying to make a car, I could just set the whole thing up in the prefab I suppose, but that makes adjustments a lot more complex since when a change is made its a lot more roundabout to find out what the original values were. So I am trying to use the scriptableobject as a storage for constants that feed into the overall object setup process.
Where the prefab comes from then ?
for example using the scriptable to configure an scene instancing prefabs?
so if two scriptables objects has two times the same prefab are this loaded in the build two times?
or the system avoid duplicated resources?
they're references to the same asset it's only loaded once
also for the memory if i unload an scene addressable that got scriptable references to other addresasables that are instancing prefabs? lol i need a coffee
As far as I know, Asset Bundle will duplicate any asset that are not in an asset bundle itself if they are referenced.
Well I have values for the player to be able to adjust, like the spring stiffness, but I need to have that stored outside of the prefab obviously, so I need to deliver the prefab with its constants to the main object generator. The prefab only contians the mesh, armature, and animation data.
ok so can i make a build a check this really?
What is the relation between the SO and the Prfab ?
I do not understand what you just wrote.
The SO contains dimensional data related to the mesh, like the suspension position, track width, wheel dimensions, etc.
Does it contains the prefab or not ?
Is it a 1-1 relation between SO and Prefab ?
what do you mean by 1-1
For each SO, you have a unique Prefab.
thats what im having trouble deciding, because I suppose there would be an instance where two cars might share dimensional data, but then I wonder if they should behave more like "skins" for the same prefab.
sorry my english sux
If I understand correctly, you have a car that have multiple SO and base on that, it construct itself ?
Sort of, it would have an SO for the chassis, an SO for balancing (torque, grip, etc) and then tuning values which all get put together to build the actual completed vehicle. The prefab however, only has 1 SO associated with it.
What is The prefab... ?
Think of the prefab as the literal raw imported FBX, its like a cosmetic that has an SO to tell the car generator how to build its simulation elements.
How many The we are talking ?
?
I have a hard time understanding your structure. Maybe I can explain how I see things and you can take whatever fits you.
depends on your setup completely, i prefer to have SOs as the source, because i think of prefabs as views, temporary representations in scene
at runtime, i link the so to prefab, but i create the object from an so, in most cases SO is unaware about prefabs, those are handled by systems that contruct objects based on context
I do almost the same as @plucky laurel. My SO are usually Definition (WeaponDefinition, CharacterDefinition) which each of them are responsible to create an instance.
In your case, I would have WheelDefinition, EngineDefinition and ChassisDefinition and they would instantiate themselves at the given position/context on the car. The one actually triggering the instantiation would be the car. Something like a RefreshPart.
how would I do animation then though
do I just do the object setup entirely through script?
you can references those gfx/view prefabs in the scriptable
they are part of the whole, just a component
you can also pre setup the root prefab and create a variant with meshes and all
its just whats more convenient to the end user
ah, so I guess ill go with storing prefab in ScriptableObject then
could someone help me on how do disable list drag and drop add element on inspector using the odin but still could edit the element within it?
[InlineEditor]
[Title("Primary Missions")]
// Set a button in each list's elements so it could be removed by clicking the button (Call the removeButtonPrimary method)d
[ListDrawerSettings(IsReadOnly = true, DraggableItems = false, OnEndListElementGUI = "RemoveButtonPrimary")]
public List<Mission> primaryMissions;
```c
or any other way
Hi ppl, i need to make an Ability System that is Scallable with my A.I, so that, based on the skill the A.I know if he hasto get closest to the enemy to use, can someone give me a tip?
It really depends on what you want. The simplest, base on your description, would be to have a range attribute on each abilities and have the agent use the ability depending on the range he is from its target.
Alternatively, you could use Goal Oriented Action Planning: https://learn.unity.com/project/goal-driven-behaviour
In this project you will learn about the Goal-Orientated Action Planning (GOAP) architecture used to create intelligent agents that can set goals and plan at achieving them. Unlike Finite State Machines, actions and states are uncoupled, making for a very flexible system. You will build a GOAP system from the ground up and implement it in a si...
found it nvm
Thanks Sim
Hey all,
I am trying to figure out how to do something in an up coming game I am making for Uni.
I want to make a fence builder for a garden you be making in the game so would be like any free form builder that you place one point and have the prefab spawn from there and can stretch it a certain distance and then place the asset down and then repeat until you exit the building the fence section.
To the best of my thoughts I can only think of using a coroutine of placing a marker then place the prefab down and then be able to stretch the prefab on the X and Z axis for a certain distance using Mathf.clamp and then finish placing the fence asset in then place a new marker and repeat until you right side click to stop.
just sounds like a state machine
you have two primary states:
- WaitingToPlace (where you choose where the fence starts)
- Placing (where the initial point is chosen and you are drawing a preview showing the how the fence would look if you finished here)
WaitingToPlace transitions to Placing and vice versa, upon clicks/user inputs
You can do this any way you would normally implement a state machine. I wouldn't immediately reach for coroutines, no
Okay so if i were to implement a state machine in terms of the logic of actually placing the fence prefab in game. Would I be correct with my thoughts on it or is there a different way in placing the prefab to do what I want to implement. For reference for what I want to do think of The Sims and how the building fences and walls etc work on that game.
depending on complexity an FSM can be too simplistic, you need rulesets, which can have priority, weight, randomization
look at something like http://leahayes.co.uk/portfolio/rotorz-tile-system/
can i copy a gpu renderTexture to cpu/save to file without blocking the main thread?
i currently generate a dynamic texture in a compute shader onto a render texture.
i then want to save it to png. i currently only found Texture2D.readPixels. But this takes like 50ms.
Problem is that this cannot be done on another thread started with Task.Run. I also found a post saying that it is not possible to do this in the job system.
just using Graphics.CopyTexture does not create the cpu pixels correctly (they are just grey).
is there a way to do this without blocking the main thread?
you'll block the main thread at some point since you have to access the data, but it'll be pretty fast if you just immediately copy into a buffer and then launch a thread that writes to disk with that buffer
https://docs.unity3d.com/ScriptReference/Rendering.AsyncGPUReadback.Request.html
I have a string[] with 77k indices.
How can I return a string[max 10] that are a partial match to an input?
string[] values = string[77,000]
string[] GetPartialMatches(string input)
{
search values for partial match to input
return up to 10 partial matches
}
You iterate on your array till you get your partial match. Otherwise, you will need to define what is a partial match and organize your string in such a way that it can reduce the search area. You can also pretty easily parallelize the whole operation.
Yeah, I've come to grips with Tasks and async/await, so I can parallelize that.
Just wondering if anyone else has done something similar and what the solution looked like
You would be lucky to find someone that has done something as specific as this in this discord.
Fair enough
If you are doing a lot of GetPartialMatches, you will need to define a good data structure to hold your data base on what a partial match mean.
Because if the player types in "17", I'd like to return "17 Draconis", but also things like "Charlie's 17 Angels", so the match isn't always just what it begins with
You could, by example keep a dictionaries of index where each subset of 3-4 characters is found.
By example:
I love cat.
Dictionary:
"I" => [0]
" " => [1, 6]
...
"love" => [2]
This way you can pre-filter a huge amount of your text.
Could be memory intensive depending on the size of the text and the amount of subset character.
If this data is persistent, it would perhaps be effective to use a database where you can query "LIKE". Databases are optimised for this.
Could always use SQLite and see what it gives in term of performance.
Need the databases to run locally.
SQLite does that
Oh excellent.
It even runs in memory
This didn't come through until I mentioned locality. Thanks, Discord.
SQLite has been excellent in places where I didn't want to set up a whole database, like with Discord bots.
The performance aspect had never occured to me.
RaycastHit2D[] circleCast = Physics2D.CircleCastAll(origin, radius, Vector2.right, targetObjects);// Checks area for specified targets
float closestDetected = 100f;
GameObject closestTarget = null;
for (int i = 0; i < circleCast.Length; i++){
RaycastHit2D[] lineCast = Physics2D.LinecastAll(origin, circleCast[i].collider.transform.position, mask);// Draws ray between parent object and potential target
float distance = Vector2.Distance(origin, circleCast[i].collider.transform.position);// Gets distance between parent object and potential target
if (lineCast.Length == 0 /*Wall check*/&& distance < closestDetected /*Closer than previous check*/ && circleCast[i].collider != self/*Avoid own colllider*/){
closestTarget = circleCast[i].collider.gameObject;
closestDetected = distance;
}
Debug.Log(closestTarget.transform.position.ToString() + distance.ToString());
}
if (closestTarget != null){
return closestTarget;
}
else{
return null;
}
}``` For some reason this function keeps returning the object its attached to even though i explicitly tell it not to
You're checking a collider against a GameObject.
Also, you can do closestDetected = float.MaxValue; to avoid issues with your current maximum.
wdym
GameObject self
in the if statement
circleCast[i].collider != self
the collider counts as a GameObject so using collider.gameObject didn't change anything
what do u mean the collider counts as a gameobject, gameobject == collider wont be true
the collider does not count as a GameObject, it's just that any UnityEngine.Object can be compared against any other UnityEngine.Object
but if the collider is not on the same GameObject as this component/whatever was passed to the method and is perhaps on a parent/child object then that condition will be false anyway
passing in the collider instead of gameobject is probably more useful, it doesnt seem like this method has a need for the entire gameobject anyways
hey,
if (Application.internetReachability == NetworkReachability.NotReachable) does not working on standalone windows il2cpp build, correctly ...
any suggestions?
thanks.
https://docs.unity3d.com/ScriptReference/Application-internetReachability.html
Note: Do not use this property to determine the actual connectivity. E.g. the device can be connected to a hot spot, but not have the actual route to the network. Non-handhelds are considered to always be capable of NetworkReachability.ReachableViaLocalAreaNetwork.
so? suggestion?
Send a web request to google.com
if it responds, you're online
i want to check that connected to LAN only ... don't want to check internet
You could try pinging the gateway/modem
I don't know too much about home networks, but I assume the gateway is always generally the same local IP?
no offense, but if you wanted to check for a LAN connection why were you comparing against NetworkReachability.NotReachable rather than NetworkReachability.ReachableViaLocalAreaNetwork (which is still not quite the same as what you are trying to do, but is actually at least a bit closer)
does not working too on il2cpp windows build ๐
just working on Android devices (e.g. Oculus Quest 2 Headset)
i mean, i know it doesn't work for what you want. we've already established that. my question was why were you attempting to compare against the NotReachable enum instead of ReachableViaLocalAreaNetwork if you wanted to check if it was connected to a LocalAreaNetwork
@exotic gardenIf you're working with LAN, then you probably already know the address of the other device you're trying to communicate with. Right? Just send pings back and forth.
Unless I'm completely misunderstanding what you're trying to do here
because im checking chop chop project and i have to change the whole of my mind to remove all my singleton and start using event by SO
i got my AI working like Scriptable system from Unity Tank
I seem to have somehow set up a scriptable object so that Unity enters a stack overflow when... loading it? Not sure exactly what operation is triggering this:
StackOverflowException: The requested operation caused a stack overflow.
UnityEngine.Object.IsNativeObjectAlive (UnityEngine.Object o) (at <b0fc6facff52490f8c5788181f70c5cc>:0)
UnityEngine.Object.CompareBaseObjects (UnityEngine.Object lhs, UnityEngine.Object rhs) (at <b0fc6facff52490f8c5788181f70c5cc>:0)
UnityEngine.Object.op_Inequality (UnityEngine.Object x, UnityEngine.Object y) (at <b0fc6facff52490f8c5788181f70c5cc>:0)
EffortStar.WeaponConfig.get_IsPotent () (at Assets/_Game/Scripts/Config/WeaponConfig.cs:129)
EffortStar.WeaponConfig.get_Appearances () (at Assets/_Game/Scripts/Config/WeaponConfig.cs:135)
EffortStar.WeaponConfig.get_Appearances () (at Assets/_Game/Scripts/Config/WeaponConfig.cs:136)
EffortStar.WeaponConfig.get_Appearances () (at Assets/_Game/Scripts/Config/WeaponConfig.cs:136)
EffortStar.WeaponConfig.get_Appearances () (at Assets/_Game/Scripts/Config/WeaponConfig.cs:136)
nvm, worked it out. Was a circular reference being triggered by GetHashCode I think
for example: Addressables.Release(sceneHandle1);
Addressables.UnloadSceneAsync(sceneHandle1, true);
Hello guys! i am trying to implement a custom function to a script found in a unity package but everytime I save it, it reverts whatever I wrote
Does anyone know why this is and how to disable it?
Also i should mention the script seems to be outside of unity? as whenever I try to make a variable for a public class, it does not recognize it'
you can't modify packages unless you turn them into embedded/local packages
Can I ask why? and also how?
because if it's a normal package it's just a reference to the package which is not part of the project
naturally you can't make changes to assets that aren't part of the project and expect them to be... part of the project
this would break immediately once you share that project with another developer or another PC of course
I see, ok that makes sense
Is there any way around it considering I just want to add a single custom function?
I highly recommend avoiding trying to make changes to packages iin general unless there's really no other way to do it
it's almost certainly easier to simply add the function outside the package
no, there's no way around it other than making it an embedded package
or simply not trying to modify the package directly
perhaps you could explain what you're trying to do exactly and a workaround could be suggested?
Ok, thanks. I'm working with Yarn Spinner (v2.2) and trying to get the Line ID of whatever line is currently playing. The issue is that it's so abstracted to the point where I cant access this line id which you would think would be trivial
the only example I found online is in a youtube video where they edit the TextLineProvider directly
You could use reflection to access private member.
What you mean ?
I'm confused by it, but from what I understand the text script with all the narrative lines gets compiled by [something], then dialogue runner creates its own textlineprovider on runtime, which feeds off the compiled text script but I cant edit the textlineprovider and the dialogue runner uses an abstract line provider
and there are functions which when I try to view their definitions it only gives me an error
The developers seem to really want users to do commands in the narrative text script
I can hardly help you there given your explication. Just know that reflection can be used to access underlining structure and member that are private if there is no other way around. That being said, this is truly not a "good" approach the same way embedded package are and you should contact the developer himself.
Thanks for the help regardless ๐ I'll send an email and wait for a response
I managed to solve it! I feel a bit dumb lol but in the Dialogue Runner there is an option to use your own TextLineProvider, so I made my own and added my custom function and it works perfectly now
The confusion is why it's being called by an internal function.
Unity internal
The stack trace before that call. But I guess unity uses properties for object equality.
Getting an issue with SQLite. I know why it's happening, just not really sure how to proceed
SqliteException: SQLite error near "Bounty": syntax error
string value = Cleanup(factions[0]);
string sql = $"INSERT INTO factions (faction_name) VALUES ({value})";
private static string Cleanup(string v)
{
return v.Replace('"', '\"');
}
Trying to insert "Fearless" Bounty Hunters Corp.
Doesn't like the quotes, I imagine. But they are necessary.
You usually use binding in SQL to make a query to remove the possibility of SQL injection.
This is a local DB, only person they'd be screwing is themselves.
I guess, it might also prevent issue with quotes and other character that could be interpreted by the query*
I've attempted to insert an escape character wherever the quotes occur, but it doesn't seem to like that, either.
You should put quotes around each value
Yep, have done that
INSERT INTO factions (faction_name) VALUES ("\"Fearless\" Bounty Hunters Corp.")
near "Fearless": syntax error
Speech marks though, try quote marks '.
@dull kestrel @dusty wigeon thank you, chads
No problem, but would definitely look at "Prepared Statements" as it'll make your life easier.
Is this the binding that Sim mentioned?
Yeah, but from a non-security perspective it'll handle the quotes etc for you.
Not handling user input, actually, it's all just a list of strings in a text file.
I would write my own system to go through the strings myself, but there's 77k of them, and SQLite is probably better written than anything I can do
77k isn't much to be honest.
I do remember your question this morning.
With SQLite though, I'd have a look at LIKE as that's kind of what you were suggesting last night
That's what I'm hoping to use, yeah.
I have to leave for work. I'll get back on this tonight. Thank you for your help.
Hey everyone, so I understand the concept of using unity events and scriptable objects to tie things together while leaving things mostly decoupled. The part that comes after that is how do you manage the registration of those unity events? I could create something like a game manager that would instantiate everything and configure event registrations... but is that really the right way to go about it? Things start to get messy if I need to subscribe to an event with something completely unrelated, like I dunno, a projectile event that goes to the UI. Any examples or tutorials you recommend would be awesome.
Iโm not familiar with UnityEvents, usually stick to agnostic events, but there should be a null check operator
Where normally you would call the event
Events.someEvent();
But that can throw errors if thereโs nothing subscribed
So instead I use Events.someEvent?.Invoke();
Where itโll check to make sure someEvent isnโt null (it doesnโt have subscribers)
You still want to take care of unsubscribing burning their lifecycle management. I typically put subscriptions under Awake, so that the first calls can be made on Start, and I unsubscribe them on their last frame, such as under OnDestroy.
Iโve only ever used UnityEvents when referring to Button.onClick, but the subscriber is just a UI manager thatโs persistent.
I was more talking about managing the subscription references. In order for an object to subscribe to another object, something needs a reference to both in order for that to happen right?
Then you run into things that are deeply nested that require some registration to something it's parent's have no reference to
Use a singleton to manage it? Dependency injection?
Have a singular event hub that everything is registered to that has sole purpose of passing event registrations through events?
I have been wondering, despites the quality of the shadows and lightin, how would a graphic system be for meshes, like making them from the peak with ultra high graphics orto playdo with super-low?
If you use a ScriptableObject as an event type you don't need anything else, just register/deregister to it in your monobehaviour
@umbral trail The monobehavior still needs a reference to that ScriptableObject in order to register it right?
Yeah, you just assign it through the inspector in the behaviours that will listen or raise the event
And that's the problem, that seems clunky for larger or deeply nested objects that need to register with each other.
well you could pass it down from one monobehaviour to another if you really wanted, but you'd just be adding more dependencies to it
The advantage here is that only the things that use it know about it
Let's say I have a UI, and in that UI I have a bunch of elements and down a few layers is a UI element that displays.. a missiles distance traveled or something I also have a player object, with a weapon, that fires a missile that holds the traveled distance. How do I register that in a way that makes sense without having to daisy chain the registration.
This mostly comes into play when I need to add a new projectile type, that needs access to some other object, and neither of it's parents or factories have a reference or registration to each other. Maybe I'm just thinking about this all wrong, but it's kind of the trap I ran into last time when using events, and it just got worse over time, and I kind of want to avoid it.
guys I am working with a way of seperating a sprite into polygons:
as far as i know this methos https://github.com/mjholtzem/Unity-2D-Destruction/blob/master/unity2DDestruction/Assets/2D_Destruction/Scripts/ClipperHelper.cs handles the seperation into polygons, my problem now is that i need the polygons to be a minimum size, if they are below that they should be merged with the nearest bigger piece. I tried multiple ways of implementing that, all have failed. How would you do this?
I'm trying to render some textures procedurally using Graphics.Blit(renderTexture, renderTexture, material), but I don't get any output, everything is black / 0
as a test, i have a trivial fragment shader that just outputs 255 everywhere, and the render textures do use a supported format
Why this is not working ?
It works, but it also generates pieces that are too small for my purpose
What does not work in combining the small piece to the nerest polygone ?
Well thats the thing it seems to work on smaller objects, but fails at bigger ones beacause: ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Im also not as experienced with working with unity so im kinda lost in all that code
Ok, that is not a question about how to do things, but how to fix an error...
Which, we can hardly do without any code and context.
I will try some other thing, might come back here once i know whats wrong exactly.
Hello
i need some help here
I have wrote a static library in C++ for android
unlike dynamic libraries
static library is compiled to the executable so I tried to use DllImport(__Internal)
But it gave some linking errors while writing the library to libmain.so
any helps here?
Pretty sure you cannot use static library directly in C#. Maybe there is some hacks with IL2CPP though.
Ok I am using a dynamic library this time
the dynamic library name is FSBC
and on build
its included in the apk as well
but when I use DllImport()
it fails again
pls help here
it took me 3 hours to build and if the results are not working then its painful to see
here is the error
any help would be appreciated cuz I am spending like hours on this thing
wait, isn't that the FSB converter?
Well no
I wrote that FSB converter in C++ myself
for converting ogg packets to vorbis compressed fsb5 file
FSBANK is supported for windows only by fmod
I would think there's a way to call into an Android static library directly from the C# side; but even if not, there's always C# -(via JNI)-> Java -> static library.
well this time its dynamic
so dllimport should work
whereas its still not working
for static library you call the internal compiled code but the linker was making issues so I went dynamic
its pretty much a .dll but on android
@wise bobcat Ahh I was thinking of FBX not FSB
lol
Are you sure you have compiled for the correct target ?
I think yea
visual studio support ARM and ARM64
the ARM64 is traditional
i think ARM is armeabi-v7a
or maybe simple armeabi
I compiled using visual studio
Also, If I remember correctly, you can directly use C++ file in Unity with IL2CPP.
really
but I thought it might not work in Editor
cuz unity only compiles for C# in editor
It will definitly not work in the editor
Only in IL2CPP
hmmmm
like if i just add a bunch of header files and just compile them to IL2CPP
unity would make sure they are fine
cuz I dont have the source for libogg and libvorbis and they give tooo much errors on compilation
I have their binaries
Thanks
let me try this asap
Only supports source files
header files are kindda unsupported
I mean, it sure only support source files.
You compile it with your project.
and I have to make use of symbols defined in other libraries like libogg and libvorbis
cuz I dont have their source
and if I would try
it might cause a crash
lets stick to the idea of dynamic library for now
Anyway, I am pretty sure you want to follow tutorial on how to compile for Android.
I think I compiled all correct
but there is one thing
most android devices are x86
that,s why arm32 is being used
Yeah, does not mean it works with them.
i have a doubt that armeabi-v7a assembly i compiled is simple armeabi
but I am damn sure arm64 is correct
If i can get a player that is x64 then I might get a chance
know any emulator?
You might be right, however as things does not work, you should look into making it the write way.
Yea I will
Only android is causing trouble
Also, you can do a Windows version
for pc it works all fine
And test if works.
Then, even more reason to look into compiling correctly.
Your code might also not be correctly added to the APK.
maybe
but I dont think so
the library was inside the apk
meaning its all fine
the thing that is causing trouble is maybe the architecture
i fear visual studio doesnt support armeabi-v7a
let me have a look
๐ญ
Ow
it hurts
now I get it why people only build games for arm64 and x86
To build a C++ plug-in for Android, use the Android NDK and get yourself familiar with the steps required to build a shared library.
https://docs.unity3d.com/560/Documentation/Manual/AndroidNativePlugins.html
cuz visual studio doesnt compile for armeabi-v7a
it lied
as the emulator I was using was a 32 bit emulator
it couldnt call the arm64
so it tried to call the arm32
but the architecture didnt match
so the library didnt simply load
i gotta wait another 3 hours for build
any ways to fasten the build
?
Exactly what you want...
https://www.youtube.com/watch?v=zYiOP89Fcw0
thanks
your good
okay guys, I am working on a puzzle game where i have a 2d sprite, whch i have to divide into polygon. I found this project which seems to do the job: https://github.com/mjholtzem/Unity-2D-Destruction/blob/master/unity2DDestruction/Assets/2D_Destruction/Scripts/ClipperHelper.cs. But I need the pieces to be a minimum size. Sadly I dont know how to implement that into the class. I tried checking the size before returning the pieces but that just caused pieces to go missing. Would be nice if someone could explain to me how to achive such behaivoir. ๐
as UI is also a mesh
you can write code that just splits them as required
I never looked deeply into how Unity draws the UI
but that,s one way go
What you exactly want to do ? Do you need dynamic cutting ?
what do you mean by dynamic cutting?
What you want from the asset ?
Be able to explod things ? Like it suppose to be use ?
i want it to be cut into smaller fragments which can be individually manipulated, like move
Does not seem to be the asset for what you want.
It explodes things up.
You might want to redo the fragmentation process as a whole.
it does yes, but for that it also cutts them into polygons, so i figured i will just change some of the code
I could do that, if i would know how xD
You could, maybe reuse the triangulation of algorithm
The algorythm stays the same doesnt it? So why not try to implement my behaivoir into that project just to see if it works
The algorithm to triangulate a polygone say the same.
However, the way polygone are generate does not seem to work for your needs.
You want to implement something simular to GenerateTriangularPieces and GenerateVoronoiPieces from https://github.com/mjholtzem/Unity-2D-Destruction/blob/eab34e26f7721767e57afec02ce706ece111e6ac/unity2DDestruction/Assets/2D_Destruction/Scripts/SpriteExploder.cs
Alternatively, if you do not need to be able to dynamically generate fracture. You can simply do it with an editing software.
Thanks, i need it done dynamically sadly
i will look into that
i see now that i already did haha
yeah that also didnt work xD
Hi guys, does any one try 100 spines animations + a star pathfinding pro (grid graph) , any solution to optimize this case? I want to make some game like survival.io but it's laggy :>
i am thinking you could use for this many enemies dij for the shortest path tree
instead of bulding the path for each indiviudual enemy
just a suggestion
do you guys have a tutorial for reactive ui in unity? ui components in particular, not ui builder
I don't know if its a bug or w/e but I think it is just a visual error, something with Instantiated entities not showing aspects ? I just wrote some aspect logic and it works.
#1062393052863414313 might be a better place to ask
Thanks, issue resolved now tho just the editor being weird.
I posted this a bit ago, and also crossposted to gamedev.SE: https://gamedev.stackexchange.com/questions/206242/
I'm trying to render a shader onto a texture, but I'm having trouble using Graphics.Blit(renderTexture, renderTexture, material), it just outputs black no matter what. Code snippets in the link.
This is in editor code in unity 2022 using URP (if it makes a difference).
my code is basically ```csharp
var a = new RenderTexture(64, 64, GraphicsFormat.R32G32B32A32_SFloat, GraphicsFormat.None);
var b = Object.Instantiate(a);
var brush = new Material(Shader.Find("Hidden/My Cool Shader"));
// Here I would set up the material properties when using an actual shader.
Graphics.Blit(a, b, brush);
ctx.AddObjectToAsset("test", b);
Object.DestroyImmediate(a);
I use 2 RTs because eventually I'll have to run multiple passes so I'll be doing some double-buffering
Hey. Is there anyone here that has experience with Unity and OSC?
hello everone im currently geting an error with my code and i might just be stupid and not understanding what it means or im doing soemthing wrong but im getting an error saying:
Assets\marching cubes\MarchingCubesBody.cs(86,40): error CS0029: Cannot implicitly convert type 'int[]' to 'int'
i get this same error on line 87, col 40 and line 88, col 40
my scripts can be found here:
tri table: https://pastebin.com/MxsvYARu
main body: https://pastebin.com/6z2Jj8sv (error says its in this script)
any help is greatly appreciated, Thanks!
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.
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.
psa: i reversed the names of the scripts in paste bin :p
edgeConnections is int[][] so indexing it gives you a int[] not an int
thanks
lol got told to ask here by one of my friends
This is a simple compile error
Blitting in modern URP is a huge pain because of historical reasons and mostly the fact that it's all so new they haven't written any decent documentation yet.
Either you can wrap your rendertexture in an RTHandle and use the new blitter api, which is the new way to do it (various advantages with variable texture size and whatnot)
Or you just have to fiddle with it a bunch. What does your shader look like?
Note I've only done blitting for realtime (not editor) in urp, but I don't see it being different
it's linked on the SE, for now it just returns 1,1,1,1 for every pixel
Shader "Hidden/My Cool Shader"
{
Properties
{
_MainTex("InputTex", 2D) = "white" {}
}
SubShader
{
Blend One Zero
Pass
{
Name "Blit"
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0
sampler2D _MainTex;
struct appdata {
float4 uv0: TEXCOORD0;
};
struct v2f {
float4 uv0: TEXCOORD0;
};
v2f vert(appdata vertex) {
v2f fragment;
fragment.uv0 = vertex.uv0;
return fragment;
}
float4 frag(v2f IN) : SV_Target
{
return float4(1,1,1,1);
}
ENDCG
}
}
}
can you point me towards this blitter api or rthandle? I tried doing it with CommandBuffer+RenderTargetIdentifier with no luck either, and I couldn't figure out how to replicate Blit with simpler CB commands, or maybe i replicated it so well it also doesnt work lol
These are a few of the resources that helped me figure out URP blitting,
https://www.cyanilux.com/tutorials/custom-renderer-features/#blit
https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@12.0/manual/rthandle-system-using.html
https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@14.0/api/UnityEngine.Rendering.Blitter.html
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@16.0/manual/renderer-features/how-to-fullscreen-blit.html
I tried pretty much excactly that too at one point lol, I know the pain
xD thank you for the links though, i'll read up on those
A good tip is that for blit shaders in the SRP's is to use Blit.hlsl for certain things, I put this under my HLSLINCLUDE at the top of my blit shader. Blit.hlsl provides the vertex function as well as the structures for whatever data you might need in the fragment function. (You define the fragment function yourself obviously)
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
// The Blit.hlsl file provides the vertex shader (Vert),
// input structure (Attributes) and output strucutre (Varyings)
#include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"
#pragma vertex Vert
Oh, another important thing is that in URP _MainTex is called _BlitTexture (Including Blit.hlsl sets this up for you automatically, no need to add it as a property)
alright
this is from core rp right? would this work on hdrp too? presumably not built-in
(i'm working on a tool, so far i try to support builtin+urp, just want to understand the requirements here)
Hopefully. URP has been breaking all it's features (like blitting) recently in the name of HDRP parity. They both use RTHandles now for example
fun times
alright i'll read up on these and try it out tomorrow, than you immensely for the help!
for today it feels like i'm an egyptian mummy that got its brain scooped out through its nose...
No worries lol, feel free to ping me if you have more questions
thank you! i will use that power respectfully
A lot of graphics programming feels like that. It's like regular programming, except that in addition to the 40+ tabs of stackoverflow, you also have some random textbook from 2004, some guy's masters thesis, and a bunch of github tabs open
fun times indeed
too real, i have one open right now
hallowed be their name, but it is a bit disorienting
So I have a custom interpolator that ticks with my own clock similar to fixedupdate.
Basically whenever something moves during this fixed update, it saves the current and last states. Then it interpolates on renders until the next fixedupdate.
The problem, is that whenever you modify a transform, the physics engine decides to recompute the velocity if it's attached to a rigidbody.
Even setting a rigidbody's position to it's exact rigidbody position (not transforms) while it's sleeping, causes it to wake up.
So how did unity implement interpolation without causing the rigidbodies to wake up?
Physx is a damn blackbox and I can't find anything online. I'm guessing their interpolator sits inline with the engine itself, therefore bypassing these wakeup calls. Shame if it can't be bypassed
I'm not sure I grasp everything you just said, however I want to point out that you can decided whenever Physics are updated instead of relaying on the FixedUpdate.
I'm using Physics.Simulate on my own clock
that's not the issue
the issue is the setter on the rigidbody's position forcing a wakeup and setting a miniscule amount of velocity
even if both positions are identical
Why does it matter ?
because my ragdolls jitter around when they're supposed to be sleeping
Miniscule velocity should not be an issue ?
It most definitely is
If you know that the Rigidbody should be sleeping, can you not disable it in a way or another ?
In what way does it matter ?
The problem is that it can't sleep.
When my fixed update gets called, and they move, that's fine.
Next the interpolation happens between the fixed updates. This involves setting the transform position connected to the rigidbody
setting the transform forces a wakeup even if the physics engine isn't running that frame
and it's just stuck with a minimal amount of velocity that causes it to very subtly jitter around
what I'll probably have to do is separate the rigidbody from the visuals. was hoping someone had a hack or something
could you run rb.sleep or adjust the sleep threshhold?
I don't think that would really do much, since it would just wake back up the next frame and negate any possible optimizations
Set it very high. Still not sleeping.
I'm certain their setter forces a wake up. Unity loves to noob proof stuff like that
shame
Yea i just tried as well, even infinity sleep threshold doesnt work lol
from what im trying, it seems sleeping it on the next frame after adjusting its transform works..
That works fine, but on the next update frame when the interpolation happens, it's going to wake back up
or maybe not. I'm very tired
this is a problem for tomorrow
it doesnt seem to wake up at all, i guess as long as u call it everytime its moved
code was only
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
StartCoroutine(SleepNextFrame());
transform.position -= Vector3.right;
}
}
IEnumerator SleepNextFrame()
{
yield return null;
rb.Sleep();
}
calling rb.Sleep() on the same frame didnt do anything
๐
Does anyone know how using Application.backgroundLoadingPriority affects the SceneManager.LoadSceneAsync for additive loading? I have tried using it to make scene loading smoother in an open world, but it doesn't seem to make any difference in FPS drops when I set it to ThreadPriority.Low;.
I think it controls how long asset load process can take, but it cannot control the scene activiation overhead that has to be done in a last single frame.
That is actually instantiating the scene
hey i have been messing around with compute shader and i just dont know what the heck is wrong with it
The Shader:
#pragma kernel CSMain
// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
RWTexture2D<float4> Beginn;
RWTexture2D<float4> Result;
float4 Resolution;
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
float2 left = 0;
left.x = id.x + 1;
if (left.x >= Resolution.x)
left.x = Resolution.x-1;
left.y = id.y;
Result[id.xy] = Beginn[left];//float4(id.x/ Resolution.x,id.y/ Resolution.y,0.0,1.0);
}
The Initalise Script:
using System;
using UnityEngine;
public class Executer : MonoBehaviour
{
//[SerializeField]private
[SerializeField] private ComputeShader _shader;
[SerializeField] private RenderTexture _textureOut;
[SerializeField] private Texture2D _textureIn;
[SerializeField] private float lol;
private Camera _cam;
void Start()
{
_textureOut.enableRandomWrite = true;
_shader.SetVector("Resolution",new Vector4(_textureOut.width, _textureOut.height, 0, 0));
_textureIn = new Texture2D(_textureOut.width, _textureOut.height);
print("In MipMap: " + _textureIn.mipmapCount + " Out MipMap: " + _textureOut.mipmapCount);
Graphics.CopyTexture(_textureOut, _textureIn);
_textureIn.Apply();
_cam = Camera.main;
}
void Update()
{
_shader.SetTexture(0, "Result", _textureOut);
_shader.SetTexture(0, "Beginn", _textureIn);
Graphics.CopyTexture(_textureOut, _textureIn);
_shader.Dispatch(0, _textureOut.width / 8, _textureOut.height / 8, 1);
if(Input.GetKey(KeyCode.Mouse0))
{
Vector3 pixelPos = Input.mousePosition;
print("MousPosWhilePress: " + pixelPos);
// _textureIn.SetPixel((int)pixelPos.x, (int)pixelPos.y, Color.white);
_textureIn.SetPixel(1000, 1000, Color.white);
_textureIn.Apply();
}
}
private void FixedUpdate()
{
}
}
I'm trying to create a sand simulator updating with ECS, rendering with a tilemap. I've tried many things but the tilemap only seems to be loading on the first set. Anytime I try to set it another time, it just doesn't want to work.
But, when I change my code to the following, it does update, but with a lot of lagg
does anyone know how to keep is preformant while still rendering correctly?
I managed to fix the issue, apperently the "Lock Color" flag had to be turned on of the tile
Do not crosspost
What do you mean time slice the unity callbacks?
you can GetRootGameObjects(), disable them before any awake, and set active gradually in batches
then send impulse to start activity
all of this requires bunch of code
Yeah I kinda figure the same things yesterday trying to eliminate a small stutter when loading our scenes
Why havent unity time sliced the enabling of objects is beyond me
I also cant find a ready made solution for this which is strange
it requires heavy architecturing around it
cant fit into everything
i wonder if it can be done cleaner by overwriting playerloop systems
you would be replacing unity phased initialization
probably a good idea to keep a stopwatch between each enable, and yield when it exceeds frame budget
Thatโs not such a bad idea
I think it should be doable in a clean way
Because it all may cause unpredictable behaviour to call Start in different frames or have some of scene objects inactive
You might just throw scene away and stick with prefabs
Hello there, I have been struggling with this for a while and would like some advice, so I have these arrays on a parallel job
[ReadOnly] public NativeArray<half3> TopFace;
[ReadOnly] public NativeArray<half3> BottomFace;
[ReadOnly] public NativeArray<half3> RightFace;
[ReadOnly] public NativeArray<half3> LeftFace;
[ReadOnly] public NativeArray<half3> FrontFace;
[ReadOnly] public NativeArray<half3> BackFace;
I pass them as I normally would and now I need to somehow store that array in a temp variable based on a condition (if for example I have a block on the left direction, I should be able to store that native array on a temp variable so I can later on perform an operation with that on a struct) how can I do this?
I have tried passing a native array of type half3 called FaceComparer with the same lenght as LeftFace and I simply do FaceComparer = LeftFace but this does not work, the values stay at 0 on all indices, what can I do here?
I need to assign those values to a struct
currentData[index] = new VertexData
{
Position = new float3(FaceComparer[0].x + blockPos.x, FaceComparer[0].y + blockPos.y, FaceComparer[0].z + blockPos.z),
};
currentData[index + 1] = new VertexData
{
Position = new float3(FaceComparer[1].x + blockPos.x, FaceComparer[1].y + blockPos.y, FaceComparer[1].z + blockPos.z),
};
currentData[index + 2] = new VertexData
{
Position = new float3(FaceComparer[2].x + blockPos.x, FaceComparer[2].y + blockPos.y, FaceComparer[2].z + blockPos.z),
};
currentData[index + 3] = new VertexData
{
Position = new float3(FaceComparer[3].x + blockPos.x, FaceComparer[3].y + blockPos.y, FaceComparer[3].z + blockPos.z),
};
Also it is worth mentioning that I am making this equal to the target face on a condition
//left
if (blockLeft == 0)
{
FaceComparer = LeftFace;
}
I would tipically just pust he currentData logic inside of the condition too, but doing that never assigns the struct value, it works just fine if I were to use just a list instead of a struct, but since this is a parallel job and I am aiming to implement the MeshData API, then I have to use a struct (I tried using parallel native lists before but there was a loss of data sometimes leading to having incorrect values on some indices, so I heard structs should keep the expected value at the expected index)
your problems is when you assign a NativeArray b to a and a[some index]!=b[some index]?
i think this is impossible since the = operator should copy all the data (ptr, length, capacity) from b to a
so a.ptr and b.ptr should point to the same memory space
Debuging my code a bit, I have proved that the array does indeed get copied but since it is stored only at that very exaxct condition, later on it gets reset to 0. My problem relies on the conditions, to fix this I must have the currentData[index] on all conditions as I was doing before on a non-parallel job, but it seems like it's not possible, the struct values never get assigned, this is what I currently have
//top
if (blockAbove == 0)
{
FaceComparer = TopFace;
}
//bottom
if (blockBelow == 0)
{
FaceComparer = BottomFace;
}
//left
if (blockLeft == 0)
{
FaceComparer = LeftFace;
}
//right
if (blockRight == 0)
{
FaceComparer = RightFace;
}
//back
if (blockBack == 0)
{
FaceComparer = BackFace;
}
//front
if (blockFront == 0)
{
FaceComparer = FrontFace;
}
AssignData(currentData, index, blockPos, FaceComparer);
It makes absolute sense that the array values get reset to 0, but I can't manage to put the assign data logic inside the conditions and still being able to assign the struct data
private void AssignData (NativeArray<VertexData>currentData, int index, half3 blockPos, NativeArray<half3> face)
{
currentData[index] = new VertexData
{
Position = new float3(face[0].x + blockPos.x, face[0].y + blockPos.y, face[0].z + blockPos.z),
};
currentData[index + 1] = new VertexData
{
Position = new float3(face[1].x + blockPos.x, face[1].y + blockPos.y, face[1].z + blockPos.z),
};
currentData[index + 2] = new VertexData
{
Position = new float3(face[2].x + blockPos.x, face[2].y + blockPos.y, face [2].z + blockPos.z),
};
currentData[index + 3] = new VertexData
{
Position = new float3(face[3].x + blockPos.x, face[3].y + blockPos.y, face[3].z + blockPos.z),
};
}
this is the assign data logic
I would tipically do this, but it does not work (Sorry, I am new to the usage of structs, so I am confused)
//outputData is a Mesh.MeshData
var currentData = outputData.GetVertexData<VertexData>();
//top
if (blockAbove == 0)
{
AssignData(currentData, index, blockPos, TopFace);
}
//bottom
if (blockBelow == 0)
{
AssignData(currentData, index, blockPos, BottomFace);
}
//left
if (blockLeft == 0)
{
AssignData(currentData, index, blockPos, LeftFace);
}
//right
if (blockRight == 0)
{
AssignData(currentData, index, blockPos, RightFace);
}
//back
if (blockBack == 0)
{
AssignData(currentData, index, blockPos, BackFace);
}
//front
if (blockFront == 0)
{
AssignData(currentData, index, blockPos, FrontFace);
}
the currentData[index] not get assigned after and outside assigndata()?
wait you said that assigning a NativeArray a to b (b=a) the b.ptr is being malloc and memcpy(b,a,size) ?
i never assign a native array even use it (the indexer is annoying) and i just use pointer
Double check if your MeshData is writable
1, Yep, if I use conditions for assigning data to the struct, the value never gets assigned, however, if I call assign data outside the methods, then the value gets assigned but with position not matching the current face data
2, I am not using memcpy and malloc, I was just using FaceComparer = LeftFace, I also tried using LeftFace.Copy(FaceComparer) with no success, all the index elements would be 0.
3, I guess I should take a look into that, never used pointers before
It is, the problem only relies on the struct assigning logic, the conditions do happen but the struct value never gets updated
Outside the conditions the struct does add data
i have no idea why assigning native array not work
so, pointer
oh, face_base_addr doesnt need to be added by index, just pass the base addr
I see, I will take a look into that, thanks!
My brain is not braining, how can this even happen?
private string text
{
get => _textComponent.text;
set
{
StartCoroutine(SetTextHelper());
IEnumerator SetTextHelper()
{
yield return new WaitUntil(() => _setTextCoroutine == null);
_setTextCoroutine = StartCoroutine(SetText());
IEnumerator SetText()
{
if (value == null)
value = string.Empty;
value = value.Replace("\0", string.Empty).Replace("\u200B", string.Empty);
_caretPosition = value.Length;
if (value.Length == 0)
value = "\u200B";
_textComponent.text = value;
_textComponent.ForceMeshUpdate();
AlignCaret();
if (_textComponent.textInfo.lineCount > _textComponentLineCount)
{
Debug.Log($"before - index: {textComponentIndex}; lineCount: {_textComponent.textInfo.lineCount};");
int firstCharacterIndex = _textComponent.textInfo.lineInfo[^1].firstCharacterIndex;
string lastLine = text[firstCharacterIndex..];
_textComponent.text = text[0..firstCharacterIndex];
textComponentIndex += 1;
_textComponent.text = lastLine;
Debug.Log($"after - lineCount: {_textComponent.textInfo.lineCount};\nlastLine: {lastLine}; text: {text}");
}
yield break;
}
}
}
}
I don't know why, but that if clause works 2 times here
that cannot be so with this nice Coroutine checking
ok, actually it can, as we can see
but I do think that the issue is in WaitUntil()
I see what you mean. I still don't know why this issue appears, but I have fixed it with:
set
{
if (_setTextCoroutine != null)
return;
StartCoroutine(SetTextHelper());
// ...
}
that works now
so I can set text directly now
text = text[0..firstCharacterIndex];
textComponentIndex += 1;
text = lastLine;
gonna implement backspacing now too, thx @soft moon
no, it causes StackOverflowException now
https://gdl.space/ejunaqaful.cs
that doesn't make sense, right?
I don't even have while loop
or do I?
I don't
oh, now it's either resulting in StackOverflowException or adding more than one _textComponent
it's even worse
how I like coding.
oh, I have mentioned this recursion:
text = text[..firstCharacterIndex];
that's stupid actually
it just returns
but it shouldn't be overflow
oh.. so do I use _textComponent.text ?
yeah, that's right
it doesn't throw errors now
but it still jumps
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Looks like your raycast is just colliding with the object you are trying to place. Some basic debugging would have probably also indicated this.
It's only happening on the buttom of the screen, increasing the camera rotation it also increases the zone where the bug will happen.
The issue it's with this code and the camera. If I reduce the camera X rotation to 30, the bug completly disappears.
Have you tested what the ray is hitting when it does this, or where it's hitting in 3D space using the Debug.Draw functions?
I'm trying to implement it now, thank you for the idea.
when dealing with asset bundle dependencies, lets say we have
A depends on B, C
B depends on C
when you do GetAllDependencies on A, does the AssetBundleManifest return [B, C]?
in that case if I naively try to load the dependencies in the order B, C i'm guessing it doesnt work?
is there a proper way to obtain the correct dependency loading order? assuming there are no circular dependencies
@austere jewel Good sir, you're awesome, it was interacting with a part of the tower as I forgot to remove the collider. Thank you very much
Best to try it out but i vaguely remember that some references are resolved lazily and thus yuo can load B/C in any order
But it's been a while
hm okay
I'm having this issue where LoadFromFileAsync just isn't loading
I'm invoking LoadFromFileAsync and busy waiting for completion in a coroutine, but it's just straight up not completing for some reason
is there a good way to debug this?
trying to use VS debug crashes VS lol
the request just has progress stuck at 0
Anyways, I will put it here, what Im doing looks advanced to me:
I saw this: https://docs.unity3d.com/ScriptReference/NVIDIA.GraphicsDevice.html
And the docs say that can be used for DLSS, so I started with this to implement it on URP
The thing is, its crashing, and I dont know why.
This is the part of the code thats crashing:
CommandBuffer cmd = CommandBufferPool.Get("ExecuteDlss");
DLSSTextureTable textureTable = new DLSSTextureTable()
{
colorInput = menu.texture,
motionVectors = menu.motionVectorsTexture,
colorOutput = menu.colorOutput
};
device.ExecuteDLSS(cmd, context, in textureTable);
Graphics.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);```
After debugging, I think that the line with Graphics.ExecuteCommandBuffer(cmd) is the one crashing, but I dont know why. All values are initialized. Also, the documentation on this is VERY poor. Do I have to do something special, or Im just dumb and trying to do something its not possible?
I have an RTX 4070 btw, so thats not a problem
I can show more code if someone wants to
Ok. It looks like when I try to initialize:
data = new DLSSCommandInitializationData()
{
featureFlags = DLSSFeatureFlags.None,
inputRTHeight = (uint)menu.texture.texelSize.y,
inputRTWidth = (uint)menu.texture.texelSize.x,
outputRTHeight = (uint)(menu.texture.texelSize.y * menu.urpAsset.renderScale),
outputRTWidth = (uint)(menu.texture.texelSize.x * menu.urpAsset.renderScale),
quality = quality
};```
The texel size value is incredibly low, and gets rounded to 0.
Im completely lost now. How Im supposed to get the texel value?
Also, this is starting to become a graphics issue, but I dont know if I should move it to [#archived-urp](/guild/489222168727519232/channel/900380950083534888/)
texelSize is the size of a texel -- the smallest unit of texture size
For a square image with square pixels, it'd just be 1f / width
I suspect you just want to be using the height and width properties of the texture
(since the texture coordinates range from 0 to 1)
It asks for texel size https://docs.unity3d.com/ScriptReference/NVIDIA.DLSSCommandInitializationData.html
Oh
I'm unclear how texels aren't just equivalent to pixels here
So its width * texelSize.x?
no, that would be 1, most likely
imagine 100 texels equal 1 inch
a 3 inch by 2 inch texture would be 300 by 200 texels
width * texelSize.x would be 3, then
300 texels, 0.01 inches per texel, 3 inches
I have a 2560x1440 pixel texture (Its the screen) and the texel size is close to 0
In x is 0.000390625
what is the type of menu.texture ?
RenderTexture
0.000390625 * 2560 is 1, so yeah
you want to pass 2560, not 0.000390625 or 1
I don't see texelSize in the docuentation for RenderTexture
huh, yeah, it does exist
Ok, it crashed again
did you update the output sizes as well?
yes
what does the code look like now?
data = new DLSSCommandInitializationData()
{
featureFlags = DLSSFeatureFlags.None,
inputRTHeight = (uint)(menu.texture.height * menu.urpAsset.renderScale),
inputRTWidth = (uint)(menu.texture.width * menu.urpAsset.renderScale),
outputRTHeight = (uint)menu.texture.height,
outputRTWidth = (uint)menu.texture.width,
quality = quality
};```
I also changed the renderScale thing to be on the input
since it's < 1 ?
Its DLSS.
You give a small scale image and it amplifies it.
The render scale is the image %
The small one is the input
Right. I just figured you were using a value greater than 1 based on the original code
hm, well, I don't see why that'd be bogus now. definitely ask about this in #archived-urp
the documentation is definitely...spartan!
It looks like they didnt spent too much time on documenting this
I cannot type in text because of the setTextComponentCoroutine
https://gdl.space/ogocabuhed.cs
that shouldn't be so, right?
I am missing something
My _setTextComponentCoroutine is null here, but _setTextCoroutine isn't
If I have a grid based movement system, can I use the navmesh from unity? or would it be better to write a custom pathfinding solution?
I need to call a move function between each tile, to animate the move correctly, I'm not sure I can do it with the navmesh system or I need to write my own.
can I leverage the navmesh and still have control over what goes on with the movememt?
no you can't use navmesh from unity with your own grid based system
use standard graph pathfinding algorithms like djisktras/A*
as for animation that has nothing to do with the grid itself really
fair enough, shouldn't take that long to write either way
that would just be interpolated motion between two points
i basically have a creature doing a hopping motion to move, which I coded to follow an animation curve.
I want that animation to be used for each move to adjacent grid pieces
not familiar with djisktras, I gotta read up on it.
what?
if you can write a* then you can write dijsktra...
yes
Djikstra is A* without a goal node (and without a heuristic based on the goal node)
Hello!
Does someone here have experience with VContainer in their projct and has a couple of minutes to help me out?
true, my bad, sorry!
Let's then be a bit more specific.
I'm new to DI and although the documentation for VContainer covers a lot of cases they are mostly writen in a "per unit" way (e.g thats how you register interface, that's how you register prefab etc). Which is fine for someone who already has experience with other DI frameworks/libs but imo not for a new commer like me. For me the easiest way of learning new stuff is by looking at real life examples and trying to undestand them in this particullar case. Are there such examples that successfully use VContainer? Another thing that I could ask and that would help me: would be Is it worth looking on e.g zenject examples to also udnerstand VContainer or are they too different?
I haven't used VContainer but looks like few samples are on github https://github.com/topics/vcontainer
Honestly DI is about understanding the rationale so looking into other DI containers' examples will help as well.
Recommended article series if you haven't seen yet: https://www.sebaslab.com/ioc-container-unity-part-1
Thank you! I will look into those asap (havent seen the recommended one so big kudos!) ๐
"Shader error in 'Barracuda/StridedSlice': Bitwise integer instructions are not supported on GLES 2 (on gles)"
what can I do with this?
none of my code even does anything about shading
though i'm using barracuda for machine learning
and 2d lights
what is Barracuda/StridedSlice
but they're completely separate
is that a compute shader?
ir's doing somethign that's not supproted on your target graphics framework
Are you sure barracuda supports WebGL?
it worked fine before I started using 2d lights
then it started giving me those errors
Looks like it only supports CPU inference on WebGL
so i'm guessing the lighting is causing this?
yeah but i mean that it worked on webgl before
It only works with CPU on WebGL according to the docs
so maybe you were only using CPU workers before
since i'm only using it with numbers, nothing graphically related
yeah
i haven't chagned it at all
oh
hmm
what workers are oyu using?
or anything about how I'm using barracuda
which worker types?
the only thing I chagned was moving a few objects around and adding lights
lemmecheck
Worker = WorkerFactory.CreateWorker(WorkerFactory.Type.Auto, runtimeModelo);
I would try using explicitly a CPU worker type
instead of Auto
see if the error persists
yeah
i'll see
@sly grove i didn't get an error.........but for some reason none of my UI loads
it's supposed to be like this
it works well when building it for PC
Check the console for errors
"[.WebGL-000049E802774D00] GL_INVALID_FRAMEBUFFER_OPERATION: Framebuffer is incomplete: No attachments and default size is zero."
@sly grove
couldn't really get anything helpful, but changed the project settings back to default and then started getting the old error back
wait
seems like i was still using GPU
lemme check once more
welp, ended up going back to this
I think I'll just do it on PC and give up on WebGL
I don't know exactly which text channel to say this on but
Is it possible to change the color of a sprite of an unlit/Transparent type material?
I tried with a simple material.color through code but it still doesn't work
hi, if i instanced an animation clip, how can i save it with code so it would work even on the build version of the game
i really need help with this
save the instance with AssetDatabase. Unless you mean create at runtime in a build, in which case you'll have to store the data you used to create the clip instead and re-create it
Ok
https://assetstore.unity.com/packages/tools/utilities/easy-save-the-complete-save-data-serializer-system-768#description would this do the trick?
Just wondering since I would rather spent my time working on the other parts of my project than working on saving files
so this is saving at runtime? You can save your data however you want
How to preserve assembly's all classes and their default constructors in link.xml?
Hello guys! Is there any way to localize visual scripting string nodes using unity's localization system? Thanks!
<assembly fullname="thenameoftheassembly" preserve="all" /> should do it?
I tried to build like that. It seems everything in that assembly is preserved because the binary size becomes much bigger. Actually I only want to ensure the type decalarations and the default ctors are preserved
[Preserve] on top of each class can do the trick, however there are too many classes
I lied, i meant "to-workday-morrow".
So, I just tried using the RTHandle-based method, and... it works!
... in a monobehaviour. Yet the exact same code running in an importer yields black.
I again abstracted it into an utility class, but stepping through the code this is what I'm doing
var target = new RenderTexture(128, 128, ...);
var material = new Material(Shader.Find(...));
var handles = new RTHandleSystem();
handles.Initialize(128, 128);
var front = handles.Alloc(target);
var back = handles.Alloc(Instantiate(target));
front.rt.Create();
back.rt.Create();
var commands = new CommandBuffer();
commands.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.Ortho(-1, 1, -1, 1, -1, 1));
CoreUtils.SetRenderTarget(commands, front);
Blitter.BlitCameraTexture(commands, back, front, material, 0);
Graphics.ExecuteCommandBuffer(commands);
ctx.AddObjectToAsset(target);
if I paste this code (filling in the ...s for my shader and texture format) on a monobehaviour's Update method it works, yet if I run them in an importer's OnImportAsset it doesn't 
whats up guys, i recently have been working with customs srp and shaders. If i move my game window at all the games fps drops to around 5ps. Note this only happens in the editor, if i build the game and play it on any device it runs fine.
On my profiler im getting 99% on FlushCounters.
Any help would be great!
Dont cross post. Delete that q from here and u-talk, and ask in #archived-shaders ... but with more info or you'll get ignored there too
Because it's running in an importer, you need to (probably) create your own RTHandleSystem(), which I noticed you did. Looking through the docs, It seems that you might need to run handles.SetReferenceSize(width, height); after initializing the system, the docs are a bit unclear, but check under "Updating the RTHandle System" on this page https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@12.0/manual/rthandle-system-using.html.
This might be redundant, since you might be setting this value in Initialize(), but that's what I can think of off the top of my head.
i just joined and didnt mean to post in general talk, and the custom code for the shader is advanced code, but thanks for the input @craggy spear
but it's.. shader code, yes?
i dont know if this belongs here in advanced but here we go anyway.
so im developing a package to easily load in multiple scenes, part of it using async. The SceneManager.LoadSceneAsync() returns an AsyncOperation which is not an awaitable task that can be cancelled by cancellation tokens by default. That is where UniTask comes in which allows users to do await SceneManager.LoadSceneAsync("myScene").WithCancellation(token);
my question is then, does this properly handle the scene so it is unloaded from memory?
from what i have talked to other people this might simply kill the operation without handling the unloading, the readme for the package doesnt mention anything about this specifically.
and secondly is there any other ways i could cancel and unload a partially loaded scene? from googling the common answer seem to be no, but none of those posts mentioned UniTask either so 
I thought so too but it didn't make a difference.
I got some progress, if you could call it that, by not using an externally created RenderTexture as the input for the Alloc calls, instead passing the creation arguments directly to it.
However, that causes the resulting RTs to be somehow different, as I couldn't store them in the asset. So I'm copying it to a Texture2D as a last step using CopyTexture, which gives me... Something?
actually let me make a thread for this to not hog the channel (should have done so sooner sorry)
Hello and sorry to get you intrigued!
Let me introduce the wall of text. I have struggled with this for an hour and a half now, before i decided to check up with the pros over here :).
I have an gameobject in my scene, whitch is inherritate from Interactable, and is also on the layer "Interactable".
When i interact with the gameobject, i want to "Activate a quest", and spawn a random item. I might have nested myself into the doom of code, but please check if you can point me in the right direction ;D.
There is a huge wall of text, but im mainly experience some errors on the "Interact" function in "TakeAquest", line 223 in the Codeshare-link! https://codeshare.io/24Aj4K
some errors on the
Interactfunction
What errors?
abstract class Interactable, methodsInteract,ActivateQuest: as they're not meant to have code in them, they should be abstract, not virtual
Trying to change it from virtual to abstract just tells me that "Cannot declare a body because it is marked abstract"
Yeah, abstract methods don't declare a body { }
End them with a semicolon
public abstract void Sample();
This now forces the inheriting classes to implement the methods, whereas with virtual, it was optional
Awesome, well its getting somewhere, but im getting this problem now
StackOverflowException: The requested operation caused a stack overflow.
Interactable.BaseInteract () <0x20dd4e77f40 + 0x00008> in <102e6767c7284913bc07b0deef5c95a6>:0
TakeAQuest.Interact () (at Assets/SCRIPTS/Intreact/Objects/TakeAQuest.cs:11)
Interactable.BaseInteract () (at Assets/SCRIPTS/Intreact/Interactable.cs:25)
Sweet, infinite recursion
Sounds sweet! ๐
A method is calling itself uncontrollably, which exhausts the memory space it was given
I see it, TakeAQuest's Interact executes BaseInteract, which executes Interact, which executes BaseInteract, which executes Interact...
I think i managed to solve that perticular Infinite Recursion,
I had "double" interacts here, i guess that triggered it. The TakeAQuest-script is only suppoed to use the "ActivteQuest"-method.
Thanks alot SPR2, now im on the road again!
Is there a way to compare a AssetBundle object to a local assetbundle file?
Unity knows to throw an error you try to load an assetbundle that has already been loaded, so I'm sure its possible, but there's no exposed method in the documentation that I can find. And I'm not downloading an AssetBundle so I can't compare raw bytes either. I'm just loading an assetbundle from disk, and as far as I can tell, there's no way to compare an assetbundle file and an assetbundle object.
I haven't looked into it myself, but UniTask is open sourced so you can check it out: https://github.com/Cysharp/UniTask/blob/master/src/UniTask/Assets/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs#L28
You guys know how I can prevent one CharacterController from pushing the other using the "Physics Contacts API"?
CharacterController will never get pushed by another one
Oh, they do
though it may "depenetrate" if it finds itself inside some other collider
Yes
it's not so much being pushed as it's moving itself outside of the other collider
physics contacts api won't help you here
if you want them not to collide, you should be able to use layer based collisions
There is the point
They should collide, but only enemies can depenetrate
Not the player
And both uses CharacterControllers
I don't understand what that means
what kind of gameplay interaction are you trying to create
I'm porting a raycasting engine game to Unity, so physics interactions there aren't the same as Unity ones
That's not really an answer to the question.
A bit of patience, let me explain it
In the original engine, the player do collides with enemies, etc, but the player position never changes when a given enemy (character controller) collides with it
But the enemy position can change in response to colliding with player
Eg: it can be pushed away when colliding with player
Maybe it is something with my code, but it looks like character controllers are pushing each other (there is a depenetration at both controllers, player and enemy)
@sly grove , same thing as this guy:
https://discussions.unity.com/t/character-controllers-push-each-other-around/238549
I have two characters in my game, the player character, which has a simple mesh made in blender along with several animations, a character controller, and some stand ins for swords attached to their hands; and an NPC who i just started working on, who has a more detailed mesh and a character controller. when i run into the npc, whether he is im...
Characters pushing each other
The player should use a kinematic Rigidbody then, instead of a CharacterController
@icy smelthttps://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
Here's something you should look into
You can essentially write your own bare depenetration algorithm for a completely custom character controller
The contact modification api does nothing in this case?
Afaik, it can be used to modify collision response
And it works with character controllers
I mean, I havent used it yet bc I dont fully understand it. That is why Im unsure about it
It completely depends on what you want. If you want to design exactly how your character responds to collisions on a movement basis, then ComputePenetration allows you to do that
You can make your enemy AIs depenetrate out of the player, but not the other way around
That is the goal
You're essentially making your own CharacterController component with the link above
this doesn't use rigidbodies
and therefore won't react to physics in any way
I guess I will keep the map character collision the same and use computepenetration for special cases with other characters
You can't use this on top of CharacterController
you would have to write your own solution
I already have a kind of rigidbody based character controller, but not using it yet
I see no reason why I cant use the depenetration with a character controller
If I disable character/character collision
What would be the point of the character controller then?
Since that's it's only purpose.
Character/map collision can use it, in my case
I just cant let characters push each other
Maybe checking their next moving position and prevent them from moving at all
Instead of depenetrating them
@icy smelt this may be a long shot, but you can set up parallel physics world, or do it in the same, you create rigidbodies that sync to cc's, and if collisions between rbs happen you snap cc's to rbs
this may also not work at all
yeah it wont
I guess simply prevent characters from moving when any collision will happen is going to work
I mean...
They can collide with each other and the map at the same time
hmm
I guess it is going to work (prevent them from moving)
sure but it will require you to handle it the same way you handle walls
collide and slide
otherwise they will get stuck in each other all the time
Doing an overlapcapsule on the target position adding the moving delta magnitude as the capsule radius seems to work
I simply prevent enemies from moving when that happens
Have to test it better
Does anyone know of a resource that would contain a full map of all fields and properties of a monobehaviour? I'm working on writing some Asset Code for managing save data. I'm considering using reflection to save and load all fields/properties (Including Base Classes) that have setters both public and private. However, I know monobehaviour has allot going on under the hood so it would be nice to see what all is included so I can understand what all would be saved.
What's wrong with Unity's existing serialization mechanism
Or any existing serialization tools like Newtonsoft JSON, MessagePack, etc
I'm trying to write it generically for a unified saving system. I'm admittly not well versed in Unitys serialization so forgive me if I'm missing something. I've already written a system for storing a list of a specific type. Deserializing that is pretty straight forward. However, I'd like to be able to inherit from Monobehavior and extend it, so it can automaticly handle collecting data that needs to be saved on an event, hand it to a storage container, which then hands the all the data collected into a dataserializer to be saved to file via binaryformatter. In the load event we deserialize the saved data, but we can't just create a new instance of the saved class, we need to transfer the values to the fields and properties of the existing class such as with a component on a scene object, right?
although now that I'm writing it out, trying to include monobehaviors in this system wouldn't be ideal due to event limitations when the component is disabled...
It literally just sounds like you're describing a serialization library to be perfectly honest
Perhaps just combining that with reading/writing to/from a file
That's all a save system is of course
But basically you can just use an existing serialization library rather than writing your own
saved to file via binaryformatter
please do not use binaryformatter
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
And no, serializing Monobehaviour is usually a bad idea
Thanks I'll take a look didn't realize it was a security risk.
Anyone know ArborXR or got advice about packaging content for remote distribution to clients?
Basically, like localization but we need to swap out specific materials and prefabs, as well as sometimes run completely different scenes etc.
I can script all the changes, so there's a scriptable asset that we can call a public method on that sets everything we need. This way (I believe) when we do a build it won't include the scenes or prefabs if nothing references them directly. (And yes, we'll need to update the scenes listed for the build)
What I don't know is how we should manage this, especially long term. We distribute via ArborXR, and I don't know if I can distribute separate "asset packs" or something to automatically push to the clients. I know if we've got everything in a build we can push it to the clients, so I'm thinking for step 1 to just make a separate build for each client.
But it'd be WAY nicer, of course, to make one build and have the content separated somehow, so the clients still get both but they can all get the same actual "product build" and separate "content"
I know the basics for things like addressables, and I can look up more info. I'm mostly hoping for someone who's done something similar to say "Yeah, you can send out content with ArborXR" or "don't bother using addressables, manage it directly in the build by doing X" or "Yeah, just use addressables" or whatever ๐
I'm sorry to add another question on top of yours, but would anyone know how to get around this?
I'm writing an encoding/decoding bytes script for my multiplayer game and I'd like to have an all-encompassing function that just lets me convert an array of bytes to whatever type I pass in
i was able to get this to work here for doing a switch based on the type of an argument passed into a function, but I don't know how to do this just based on a type
i know this isn't really the best workflow but it would be incredibly helpful for what i'm working on and any advice would really help <3
there's also a question above this one
i was thinking of using "out T variable" but it would be really clunky to use and i'd like not to if possible
Can't you just do an if instead?
i could but i was really hoping i wouldn't have to do that either
it's a bit more complicated than it'd need to be but i could just fall on that if nothing else works
Switch vs If is not that different really
i know i was just hoping for cleaner code :(
Anyways, I don't think you can make it work with a switch
you are doing it wrong
well actually hold on i couldnt do that anyways
i cant return any type i want it needs to be of type T
how should it be done?
cast it to T
i can't
class Converter{
}
abstract class Converter<T> : Converter
{
public abstract T Convert(byte[] bytes){}
}
class IntConverter : Converter<int>
{
....
}
class Converters
{
Dictionary<Type, Converter> converters;
public T Convert<T>()
{
Converter<T> converter = converters[typeof(T)] as Converter<T>;
return converter.Convert();
}
}
this is almost pseudocode i hope you understand it
No it doesn't
Did you try it?
STJ is not supported for variants of .NET Standard (which is what unity uses) so unless you messed with the linker there's no way you can get it to work on Unity.
bruh, been using it since 2022.2
download the nugget package extract to your project folder
set the linker so it won't get stripped by il2cpp and works on webgl (Mono is fine)
it's been working since 2020, but the difference is that it used to not take advantage of Span<T>... but now it does
definitely not true 
Which part, the fact that STJ does not target .NET Standard or that the setup is difficult?
Former: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer?view=net-7.0&source=recommendations#applies-to
For the latter: I would not even know, I had this discussion plenty of times and this was mentioned quite often.
the setup is far from difficult
.. just copying the dlls and set the linker
So if you used STJ, I can only assume you are using some fork that has been adjusted to build with .NET Standard
uh, no?
That's literally what I said, you can make it work if you set up the linker
Then what is the issue? ๐
That's not exactly something the average user is going to do though
in what context that do you think the linker is difficult? it's just xml ๐
Perhaps not for you, but it strafes away from the usual setup
don't be fooled by nugget versioning. If the api works in other net versions then it works
it's much faster and less alloc than newtonsoft's, two important things when talking about stj
Whatever, there's no use bickering back and forth. My point is that STJ is not supported because the version does not match what Unity allows, and you need extra work to make it work. I think that was proven already, but feel free to explain how easy it is to set it up for those that have no idea
NuGet, please stop with the double g 
oh haha ๐คฃ
mb
we begged for stj to be officially supported years ago
https://forum.unity.com/threads/please-add-system-text-json-support.1000369/
and it did finally supported
Nice, I was actually under the impression that the steps were way harder than described ๐
they're not hard really ๐
Granted, too bad it still requires all this work, but I do agree it's a step ahead compared to Newtonsoft
oh no, the turtle Newtonsoft that keeps spewing unnecessary allocations... yeah stay away from that prick ๐ฅน
I am trying to make selectable objects through scene (editor) view but im unable to identify what's the issue with the cursor, when i tested the mouse position it felt like it was working properly but it feels broken on the monobehaviour, perhaps i didn't write a proper solution, i need help spotting what's wrong
Monobehaviour:
/// <summary>
/// Selects a transform based on the mouse position in the scene view.
/// </summary>
/// <param name="mouseWorldRay"></param>
/// <returns></returns>
public Transform TransformClosestToCursor(Ray mouseWorldRay)
{
Transform closest = null;
foreach (Transform obj in transforms)
{
var objAccuarcy = Vector3.Dot(mouseWorldRay.direction, obj.position - mouseWorldRay.origin);
var closestAccuarcy = closest == null ? 0 : Vector3.Dot(mouseWorldRay.direction, closest.position - mouseWorldRay.origin);
if(objAccuarcy > closestAccuarcy)
closest = obj;
}
return closest;
}
Editor script:
private static Vector3 MousePosition => Event.current.mousePosition;
private static Ray MouseRay => HandleUtility.GUIPointToWorldRay(MousePosition);
void OnSceneGUI()
{
_target = (CollisionBuilder) target;
_target.CalculateClosestTransform(MouseRay);
}
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
can someone think of a more efficient way to check for bounds collision than checking for each point if it is in the other bound and vise versa?
are these axis-aligned bounding boxes?
yes so the bound is just defined by a vec3 btmL and a vec3 topR
that s great but it does not explain how efficient bound collision is calculated
You can always look into their implementation
https://github.com/Unity-Technologies/UnityCsReference/blob/e7d9de5f09767c3320b6dab51bc2c2dc90447786/Runtime/Export/Geometry/Bounds.cs#L147
thank you very cool
Did you share it as editable? Someone sabotaged it
Woooooaaaw, i had no idรฉa i could share it as non-editable... yeah someone sabotaged it...
What about this time, dose it work now?
https://goonlinetools.com/snapshot/code/#odiyynxp9hpxak4gnqxadn
The Share Code Snippets Tool helps you to easily share code snippets online with your developer friends or colleagues.
What is Quest here? Is it MonoBehaviour or something?
Quest is just a script thats inherriting from Scriptable Object. Then i create those Scriptable Objects, as Quests so to say
Eww. ScriptableObject
And what is questObjectSpawnPoint?
That is a Transform sitting on the Quest-Scriptable Object, I want to spawn an object there
And its different on all t he quests im creating ๐
Okay, Transform on scene cannot sit on SO
So that sounds wrong
Well, actially, the Transform is a prefab, haha. It is a shitshow. But okey, that is actually the problem
The problem is, the Transform aint being spawned
You have if (quest.questObjectSpawnPoint != null) and if the log is printing then.. it is actually not null and set
So your log message is wrong or your condition is wrong
I ils like to implement a local avoidance for a group of units, similar to RTS behavior. Is there any suggestions how to implement this?
Just to add to what has been said consider the following. The Get method will return an exception while the Get2 will not.
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
try
{
var t = Get<float>();
Console.WriteLine ($"The result is: {t}");
}
catch(System.InvalidCastException e)
{
Console.WriteLine ("An Exception has been launch for var t = Get<float>() !!!");
}
try
{
var t = Get2<float>();
Console.WriteLine ($"The result is: {t}");
}
catch(System.InvalidCastException e)
{
Console.WriteLine ("An Exception has been launch for var t = Get2<float>() !!!");
}
}
private static T Get2<T>(){
if (typeof(T) == typeof(float))
return (T) Convert.ChangeType(GetValue(), typeof(float));
return default(T);
}
private static T Get<T>(){
if (typeof(T) == typeof(float))
return (T)GetValue();
return default(T);
}
private static object GetValue()
{
return (object)0;
}
}
I designed a chart that explains how Unity developers can create a form of lagless frame generation
This applies to any framerate to any framerate, even though it was part of an article about enabling-tech for future 1000Hz displays.
Hope the chart is useful to devs (VR, etc) looking to fix reprojection lag (timewarping, spacewarping) and remove double-image artifacts (etc) on some displays.
The article is up at blurbusters too, and there is a "Developer Best Practices" chapter ( blurbusters.com/framegen#dev ), from our tests.
Unity-powered source code is linked over there, although it is very Wright Brothers (simple graphics, doesn't implement all best practices yet). LTT covered it at https://www.youtube.com/watch?v=IvqrlgKuowE but my article now links to the Unity source code of the lagless framegen demo!
Get up to 25% Off Pulseway's IT Management Software atย https://lmg.gg/PulsewayLTT
Save up to *40% off and get Free Worldwide Shipping until Dec. 22nd at https://www.ridge.com/LINUS
What if you didnโt need the best frame rate to reduce input latency? What if your displayโs refresh rate was enough all on its own? With Async reprojection, anythin...
I have a native array, or a mesh, containing the vertices position, i need to use them on a compute buffer, what's the best way to do it?
Im not sure how I would use that
This link seem like a good start: https://blog.en.uwa4d.com/2022/10/25/basic-introduction-and-implementation-of-compute-shader-in-unity/
Im still not following, i know what the compute buffer and shader is. Until know I've been mapping the height of the vertices and passing that to the compute shader as a texture. But I'm wondering if there's a shortcut to transform a Native Array into a compute buffer
This Append compute buffer is a compute buffer than can get it's size increased through append, which is nice, but not surr how it's relevant
My bad, though you were talking about doing operation to create the data from the ComputeShader. You might want to use ComputeBuffer.SetData or ComputeBuffer.BeginWrite I guess then. Pretty much sure this is the standard way of proceeding.
i watched stinger (the guy who made that reprojection demo) develop that thing in a discord call a while back. it's neat stuff.
I have tried to reach out to him, to ask what source code license he put on the code that he linked to. The source code is linked from the blurbusters article, from the link on the YouTube channel, but there is no LICENSE file.
I personally want to light fire under manufacturers, game engine makers, and API vendors. Just need to give due credit.
I suggest MIT or Apache 2.0 for maximum industry impact, with name credit mandatorily in lights
I'll ask him about it
he said he meant for it to be public domain. he also said the code is, to quote, "cringe" and that he didn't expect people to want to re-use it :p
probably needs some prettying up
so its not theoretical?
Tell him to put a CC-by-SA 0
Some countries doesn't permit public domain without a "license"
So that's the defacto "public domain" license.
It may be cringe, but some people will still try to play with it anyway. Be amazed how such simple code pulled it off. And take upon challenge to rewrite a better implementation
the code isn't for rendering at a kilohertz
just for using reprojection to make mouse look nice and smooth even with awful framerates
3kilksphilip has a good video on the topic https://www.youtube.com/watch?v=f8piCZz0p-Y
DLSS 3's framerate doubling feature is all well and good, but that lag is painful. But... what if there was a way to reduce it? Welcome to the wonders of Framerate Independent Mouse Movement.
Download Comrade Stinger's demo here: https://drive.google.com/file/d/1lSONJxTz3ThsKSoYwm7lP3sAuYN5rLyg/view
It took him one evening to make, and another f...
well, 2kliksphilip
close enough
havent watched him in a while, thanks
That video is also embedded too at https://blurbusters.com/framegen - both this one and the LTT one
Brand new article that went up yesterday
I am lighting a fire
I have over a hundred friends at GPU employees
basically, you can warp the last frame's image a bit to create a new image
you can do this for both translation and rotation
possibly including the depth buffer to figure out how to do the parallax correctly
It's very fast compared to rendering a whole frame
Yes. Needs to be built into FSR 3 / XeSS 3 / DLSS 4
This is already done in VR.
It's why I don't immediately die when I'm in a VRChat instance with 80 people in it
To replace BFI and ULMB
my framerate is like 20, but my head motion is still handled at a high refresh rate
you'll have to explain what those are :p
i'm not terribly familiar with stuff like strobing and monitor motion blur
Yes, I also wrote about this in 2018
https://www.blurbusters.com/frame-rate-amplification-tech
However, VR needs to stop flickering. Not everyone can handle flicker. Flicker is great, but we need to kill blur strobelessly in future
So to go strobeless AND blurless, we need 1000fps 1000Hz reprojection
Reprojection at 8x+ ratios can be commandeered as strobe free low persistence sample and hold
Ergonomic PWM free blur reduction. And only reprojection can easily do 8x ratios or better at low compute cost
Tests show we can reproject to 1000fps on RTX 4090 already!
Imagine 1000fps pathtraced graphics on near term GPUs.
Read the new article to see why I am so freaking excited when testing on my prototype displays
I work for display manufacturers
I am in 25 peer reviewed research papers
I was summoned ๐
Hola.
I linked your code at https://www.blurbusters.com/framegen
But what source code license does your reprojection sample use?
Since I have hundreds of friends at AMD and NVIDIA I am trying to light a few fires.
haha yeah fen informed me, I love how far it went, really hope more people do research into it
hell yeah
But companies (in some countries) won't touch unlicensed code
Public domain code should have a CC-by-SA 0
Or use MIT or Apache 2
I want it to be as permissive as possible, something like CC0?, no credit needed, use it for literally whatever you want.
thing is too, my demo doesn't actually do asynchronous reprojection. It runs as fast as it can and "simulates" a low framerate, which it then reprojects.
so the only interesting part of it is the reprojection code itself, but I feel any competent graphics programmer should be able to re-implement that part pretty easily.
the hard part (which I have not done) would be spinning up a separate higher priority render context and then coercing unity into using it
that sounds scary
yeah.. as far as I understand this is how VR games do it. It's almost like two games running at the same time. one renders the game, the other does reprojection. and the reprojection one is allowed to interrupt the game one whenever it feels like it
Unlicense?
like, I have yet to see anyone try this in a third person game?
Racing game? RTS?
How do we solve reprojecting things like transparency or particles?
lots of stuff that might be big problems
yes the value of this seems to stem from concept
yeee
Then tell Unity developers to make engine compatible with the algorithm. We need to refactor the rendering ecosystem to be friendly to this
that sounds like it will never happen
@trim vine Would you already be able to do so with Scriptable Render Pipeline ?
at least not by unity hands
One possible method is two independent Unity processes, using low latency IPC mechanisms to communicate final frames.
But ideally it should be same process, possibly as a third party library.
Minor modifications may be needdd to help third parties reduce contention between two rendering pipelines running in parallel, and GPU vendors need to make multithreaded rendering a little less costly to each other
We can still tip a few dominoes, even if others have to do the heavy lifting
It's a full decade iteration
240Hz OLEDs are flooding inwards and they benefit from warping/reprojection way more than LCDs
480Hz OLEDs roadmapped 2025ish
something like create a working tech, paper, and visit siggraph with it
Maybe I will for 2024 or 2025, but I'd have to find funding (or Patreon it)
this article goes into how to do it in DirectX 12
but yeah, non-trivial. would very likely require engine modification to work right
The main rendering thread may need to be paused mid-render to let a secondary thread do a surge execute to reproject a previous frame. That'd be 2000 context switches for 1000fps, but not altogether impossible on certain GPUs.
Some cache/pipelining optimization needed, but, we gotta tip some dominoes on that if it framegen is ever to be used in esports
We can begin with reproject/warping any low frame rate to 240fps for the OLEDs that has more
dramatic 120-vs-240 visibilities than LCDs
Tsunami flood of 240Hz OLEDs coming
critical mass to help devs be more interested in all this.
Could be added to FSR 3 or DLSS 4
Which would help Unity need to do minor tweaks to not underperform with those, and even more important if a future Vulkan later this decade gain some (more) warp-related helper APIs (etc)
It's all about tipping dominoes - have 3 more framegen related articles planned this year
i am doing culling stuffs
culling can do that
where it keeps record of transition and states only
but gets back on track after turned on
in my case i dont want animations to be played at far distance
at the same time i want to turn on and off however i feel like it
anyone?
posting this because its advance code stuffs
@azure moss Not really advanced, you can just measure the object distance to your camera and if it passes a certain threshold you can disable the animator component or change the animation to idle / however you want.
So, just create a script that references the camera and the animator of the object it is in, then check how often you want for distance -> disable animator / change animation to idle, vice-versa.
just deactivate the animator at a distance
or did i missunderstand
Problem comes to restoring like predicting how exactly it was
Let's say its fine you turned off