#archived-code-advanced
1 messages Β· Page 106 of 1
The point is that I don't know the T.
but you can find the T by examining the returned object
Using the pattern, your subclasses can now implement a specific return type.
abstract class AttributeType<T> where T : AttributeType<T>
{
public abstract T ModifyValue();
}
class IntAttributeType : AttributeType<IntAttributeType>
{
public override IntAttributeType ModifyValue()
{
// ...
}
}
AttributeType at = new AttributeType<MyClass>();
---
object o = (object)at.ModifyAttributeValue();
This won't work since ModifyAttributeValue is inside AttributeType<T>. at in this case is the type of AttributeType. You can't use it like this unless you cast at to AttributeType<T>, but you don't know the T at the moment.
Gonna check
good point, it would need to be on AtributeType so object is your only return type
hmm why do you want to call ModifyAttributeValue without knowing the type? that limits what you can do with the result quite a bit
On second thought this solution misses the point of what I was planning. I wanted to have class IntAttributeType : AttributeType<int>, which would return int value from ModifyValue. But I think I will find a place for your trick in another place.
I wanted to get a value and instantly use it on an object of the same type for some other method.
I feel like some context is missing, might be a better idea to share your current code.
As I see it, your current implementation of ModifyValue in your non generic base class AttributeType cannot be safe without knowing T, yet the inherited generic class can make T be anything.
The concept is to create some system for generic attribute scriptable objects. Depending on the attribute, it could be int, float or something else. It worked nicely until I wanted to create an ability that transfers a value of some attribute from one object to another. E.g. you could drain enemy's health or mana. I think implementing such "transfer" functionality directly into AttributeType could do the job, but I was hoping for a solution that wouldn't require modifying AttributeType's code each time I want to create a new kind of effect.
Why does not Burrito's solution work in your case ? I would assume that the operation made by ModifyValue() would change depending on the type of the object
you just want this, no ?
abstract class AttributeType<T>
{
public abstract T ModifyValue();
}
class IntAttributeType : AttributeType<int>
{
public override int ModifyValue()
{
// ...
}
}
(Just trying to understand)
I want to be able to do something like this:
void SomeMethod (AttributeType someAttribute)
{
someAttribute.ModifyValue (someValue);
}
But the method ModifyValue would be inside of AttributeType <T>, which derives from AttributeType, so I can't access it from AttributeType unless I cast it to AttributeType <T>, but I need to know the T in order to cast it.
OK. Thanks, it's more visual that way haha
adding it to AttributeType is probably the route i'd go with, there's not much benefit to making it generic if you're casting back to object for every operation anyway
i don't know exactly what you need but i guess you'd only need to put enough building blocks in AttributeType that you could implement more specific stuff in terms of those?
^ This is honestly what I'm interested to see.
Adding more building blocks seems to be the safest way, so I will most likely stick to it.
In this situation, what is the type of someValue and where it comes from ?
Hello, I'm trying to implement a StateMachine for my character's controls. I use rigidbody.
I need a basic class or interface from which to derive the various states my character will be in. But I've run into a dilemma.
In your opinion, is it better to use an abstract class or an interface to define a State Machine ?
From what I've seen on the internet, it's the interface that comes up most often. But the tutorials on the iHeartGameDev YouTube channel, which I think are very good, use an abstract class.
What do you think I should choose ?
An interface only makes sense if you have multiple characters which each implement their own behaviours
there's really not that much of a difference conceptually, go with whatever is most practical for your code
Could you elaborate on that ? I want a StateMachine just for my character. So if I go by what you say I should use an abstract class ?
Got it. So in terms of good practice you think the two are equivalent ?
the point is, if you use an interface you MUST implement the methods for each class that inherits it. for an Abstract class this is not a requirement. If you are only implementing a State Machine for one Character then a standard class is more than enough
there's a lot of overlap between them, i guess generally i'd go for interfaces as a preference but they're two ways of achieving more or less the same thing and the differences are stuff like multiple inheritance and whether you need fields in the base class which probably don't matter here
@pure berry If you have only one Character that needs a State Machine then the question of Interface or Abstract class does not even arise
OK, thanks for the reply. I will take this into consideration
OK, I understand. Thanks for your reply
Oh so using an abstract class for one character is an insdustry standar ? This is what most game dev use you mean ? Because I've already done both, but never in the context of creating the movement of characters video games.
Absolutely not. why would you create either an Interface or an Abstract class which is only going to be used in one place?
this is about a character with multiple different state classes implementing a common interface
that is not the way I read the question
The same type as T in someAttribute. I think I could add a Type property that would return it. π€ It would look ugly, but would do the job.
I want to build a StateMachine to define the different states of my character. This is made up of a main class or interface. And from this derives the different states that will redefine the character's movement logic.
but, I guess, the character here is irrelevant. you are talking about building the State data structure?
Yes, but what is the data structure that holds that ? Do you hold your object in a list<object> ?
Yes, if I decide to work with interfaces, that's what I'll have to do. It's mentioned on this site: https://gamedevbeginner.com/state-machines-in-unity-how-and-when-to-use-them/
If when you say "State data structure" you're referring to the way we manage the various states of an object, yes that's what I'm talking about. But the link with the character is that depending on the state, the character will follow a different movement logic. I'm talking about movement logic because that's what I'm working on at the moment, but it could be something else.
well really i mean "interface" in the general design sense, an abstract base class can be considered a type of interface in this context π whether you use a C# interface or a base class is still basically down to convenience IMO, i've done it both ways for player state classes
OK, I misunderstood what you were trying to do. There is no reason not to use both Abstract and Interface. What I would do is evaluate where the commonalities are. For those states which have much in common implement them in an abstract class, for those with little or no commonality implement them in an Interface. But as @stuck plinth says, there is really very little conceptual; difference
Basically if you find yourself duplicating code you have chosen the wrong path
Oh ok i understand what you say π
Ok got it. Thank your for your answer.
Thank you very much @stuck plinth and @upbeat path . It was really helpful. Have a nice day ! π
Allright, lets do it the hard way:
[CreateAssetMenu(fileName = nameof(TransferAttributesEffect), menuName = "Interactions/Effects/TransferAttributesEffect")]
public class TransferAttributesEffect : InteractableObjectAlterationEffect, ICellInteractHandler
{
[SerializeField] AttributeType [] attributeTypes = new AttributeType[1];
[SerializeField] AttributeType.ValueType valueType = AttributeType.ValueType.currentValue;
[SerializeField] Modifier [] modifiers;
[SerializeField] TargetConverter targetReceiverConverter;
public override void InteractWithTargets(IInteracter selectedSource, InteractableCell[] selectedTargets)
{
var covertedTargets = GetConvertedTargets(selectedSource, selectedTargets);
var transferReceivers = targetReceiverConverter.ConvertTargetsToInteractables(selectedSource, selectedTargets);
foreach (var covertedTarget in covertedTargets)
foreach (var transferReceiver in transferReceivers)
foreach (var attributeType in attributeTypes)
attributeType.ModifyAttributeValue(transferReceiver, valueType, - attributeType.ModifyAttributeValue(selectedSource, covertedTarget, valueType, modifiers, multiplier));
}
}
I just have a bunch of AttributeTypes and I try to use their generic value as an argument for another generic method from the same AttributeType. I don't know what T I'm ending with, but I'm sure it's the same as AttributeType's T.
Is there any particular reason why you do not use SerializeReference for your array of AttributeType ?
It seem like you handle the type without actually using the type. By using an enum.
AttributeType is a ScriptableObject. I'm not sure if it works well with ScriptableObjects.
What is the attribute type ? Float, Integer, etc. ?
It can be different for different ScriptableObjects. There is a separate type for each class (e.g. IntAttributeType : AttributeType <int>), which makes it possible to create multiple types of them with the same basic logic.
Why are you not using something like Modifer<int> ?
Modifiers here are supposed to handle the logic of modification, e.g. "increase by 3", or "reduce by 100% of source's power" or "increase by 50% of target's shields". So Modifiers here don't have a type.
It really seem strange that they have a type given that you cannot increase by 3 on a boolean type by example.
So, your AttributeType is what define the operation ? Like summation, division, etc. ?
True. I don't have planned adding support for bools so far, but if I made one, I would just leave NotImplementedException here and some comment/log to not modify bool that way. The logic should be implemented for types such as int, float and maybe some other numeric types.
So, your modifier defines the operation to be executed and the AttributeType is the one actually executing it ?
AttributeType is mostly for directly handling data. Possibility of setting its min and max value, clamping the value accordingly, managing listeners (when it's modified), changing the values in the correct order (e.g. increasing max health before current health during addition, but in other way during reduction).
I would treat it more like a scalar.
So, attribute type represent Health, Mana, etc. ?
Yep, stuff like that.
I am not sure why the AttributeType is not directly linked to the Modifiers.
By example, (Obviously, not exactly that)
public class Modifier<int>
{
[SerializeField] private AttributeType<int> attributeToModify;
[SerializeField] private int value;
public void Execute(Context context)
{
Target target = context.GetTarget();
Attribute<int> attribute = target.GetAttribute<int>(attributeToModify);
attribute.Add(value);
}
}
The issue seem to be that you have two different Type which could be different (Impossible to know at compile time).
You would either need to restrict further at compile time or make runtime validation/cast.
Currently, I'm just casting it if needed (to calculate percentages I need floats anyway). I'm using numeric values, so there are no issues so far. But in the case of other types, I suppose I will simply make separate methods and call them (e.g. in Vector2AttributeType I would call Modifier.Vector2Fraction (IInteracter selectedSource, IInteractable selectedTarget, Vector2AttributeType attributeType) instead of Modifier.FloatFraction (IInteracter selectedSource, IInteractable selectedTarget, AttributeType attributeType)).
You do you. From what I see, you wont have any choice to use object and cast given how you use your data/store them.
im writing my own transform / physics system for a fighting game, because i cant use unity's float based transform system for calculations. i was thinking of making a base class "entity" which would store the positions and velocities of an object such as a player or projectile. I'm just wondering what else I should store, if anything?
What is the problem in using Unity's float based transform system?
from what i've been told floating point numbers are not deterministic and are subject to errors between different machines. as such i've been recommended using a fixed point system
Hello there...
I need some math smart guy because I'm lost π
Hello there π
I'm trying to make a sort of solar system, but the game is based on a grid, so I'm using this to calculate the position for each planet
for (int i = 1; i < celestialBodies.Count; i++)
{
float angle = CalculateOrbitPosition(celestialBodies[i], currentDate);
float distance = cellSize * (i);
float x = centerX + distance * Mathf.Cos(angle);
float z = centerZ + distance * Mathf.Sin(angle);
celestialBodies[i].celestialBodies[0].transform.position = new Vector3(x, 0, z);
}```
But the problem is that I have to keep the planets centered on a 2D Grid... which is "virtual" because I won't use trigger.
So the cellSize defines that theorical cube, and I've stored it in a bidimensional int [,] ... any advice? ππ
Ok... I know the center of the grid, so if `i` = 1 define also the cell closer to the center which is the sun ... and here I'm lost π€
I'm really not sure what you're asking to be honest
π
but if you want a grid based game I would highly recommend Unity's Grid component
it will take care of all conversions to and from grid coordinates/world space and is freely configurable
I'm making object orbiting around an object, but I want that are snap to a grid
that's very confusing
I can think of at least two different ways to do it though.
- You might have a "real" position with full floating point fidelity, and when drawing the things on screen you just snap the position to a grid for presentation purposes.
- You reimagine the concept of "orbit" in a grid-based setting which means throwing physics and such out the window
I see, so would you like to fully recreate Unity's physics with another data type?
I need the planets switch from cell to cell, should follow the orbit, but stiked to the center of the cell.
I'm unclear about what you mean about them "sticking" to the center
if they stick to the center, they will not be orbiting
Is it more that you just want to be able to identify which grid cell they are in?
sticked to the center of the cell. π
yea!
Well as mentioned, just use the Grid component
You can use https://docs.unity3d.com/ScriptReference/GridLayout.WorldToCell.html this to convert from a world position to the grid coordinate
Ok I will investigate on the grid component not even know that exists
Ok I'll start studing it thank you π
Sorry for my bad explanation, but I'm Italian and my English sux a lot π
(this isn't really an advanced code question by the way)
I was expecting some complicated array and trigonometry stuff π
not fully, but i need simple things such as collisions and velocity and stuff
Can your game logic be implemented with Unity's built-in physics?
it can, but it wouldnt be good for online multiplayer and stuff.
i need to make my own physics for this case
its not deterministic like i said before
Do you only mean errors when calculating floats?
yeah
Do you know how huge they are?
they are not cross platform deterministic, which means different machines may have different results for a simulation.
Why does everyone still use Unity's physics?
for their case its probably fine, but im doing online multiplayer eventually so i need bit-perfect simulations across any platform
apparently π
I think you should reconsider it
I wonder whether you'll be able to recreate Unity's physics, even party, in a better way than Unity has done it. Also, this may take quite some time, especially, if you're asking for the hints from the start
I'm also not sure whether you have already tested this calculation impact across different platforms
i think i may have made what im trying to do seem more grandiose it is. I'm not trying to make proper rigibody simulations with like 100s of cubes or whatever. at max, 4 things are going to be on screen and stuff. I'm already in part doing physics kinematically in my current system
There is no need to create your own physics unless you're e.g. dealing with a grid-based game, where Unity's physics may not act accurately
Easy as can be Thank you! π»
If you are doing multiplayer, only one client (or server) will have authority over simulations, so making them deterministic will not matter as much
Unless you are making something like Trackmania where each session must be deterministic and comparable
its a fighting game, so i'm only streaming inputs to the server, which is why determinism matters for for me
So only one machine does the calculation, what will determinism achieve?
fighting games only send the inputs to the server, and each machine does their own simulation. this is why i need determinism
Your server should sync all states, and clients will only display visuals
most of fighting games are p2p (if not all of them), and don't involve physics simulation at all
wdym? stuff like moving up and down? im doing a platform fighter as well, with some projectiles that are affected by gravity
oh, a platforming fighting game, not too familiar with those
traditional fighting games operate exclusively on animation frames
Still, your server should override all simulations and sync visuals. Without it you are open for cheating
awesome!
That's not really how cheating works
how? if the server only streams inputs, how would you move the players around and cheat?
you dont have direct control of the character itself, as well as its position
Sure, it won't give you advantage but just desync everything completely
i suppose. thats what rollback is for i guess
I feel theres a major difference in what you asked and what's actually being discussed. You're making this for a replay system right?
Client will receive a state of the opponent, so it shouldn't be a problem to also get it's own state
i'm making this for the replay system, and that's going to be a precursor to online multiplayer. I've been recommended to make the replay system, because if I can perfectly recreate a match from inputs alone it apparently makes it viable to for online multiplayer
Yeah, it makes sense for replays, but it's not a requirement for multiplayer
Well there might be slight differences tbh. Many multiplayer techniques are made specifically to fix desync issues which will happen no matter what. This is just a cause of networking. Meanwhile a replay would exist locally
i'm in a fighting game development discord server, and they have all attested to using fixed point transform system instead of floating point ones
which is why i wanted to give it a go
I'm not saying you shouldnt use this kind of system, just that a replay system alone is gonna have some differences. Even with a fixed system, networking a game will require more to fix desyncs
thats fine, i understand that. its meant to be a good start, though. i plan to use a networking system called lockstep, where it waits for all inputs to come through before simulating anything
i know im oversimplifying it a bit though π
Have you looked into what other games, similar to what you're making, are doing for such a system?
A lot of fighting games systems are well known/somewhat documented
networking or transform system?
Their movement and hit detection system, which I believe your original question was for
oh right. I've not looked, i'll check that out. my original question was "what sort of things should i store in a base 'entity' class for a transform system"
my idea is that i'll calculate the mvoement in fixed point system, and then show the transforms in unity's system
seperating the simulation from the visual or whatever
Hello everyone, I am currently trying to work on a school project with some friends of mine. We want to recreate a game map on unity HDRP. The issue I am running into is that the base project of HDRP is already 2GB. Which makes it so that when I want to push to unity, to work collaboratively. I get an error from it, for it being too big, I believe the maximum is 50MB or something. I have made a bit of reserch, and there seems to be something called LFS that might help, but it seems that to use it, I need to use Git Krakern's terminal which I am not that experienced in. Anyone that could help with this?
In git you usually add to ignore the library folder
I have that, but there are still files in hdrp that are just too big, or I guess they are not being ignored if that is the case
You can sort big files into one folder and ignore that folder, and copy that folder in google disk to share with friends, but it will work only if it is some static things for example 4k texture
there is no reason you should be pushing "the base of HDRP" into your version control system
show a screenshot of your repository
Hi everyone, can I promote my Unity package here?
How do i get hdrp in my project without, starting up with the base unity hdrp project?
I don't care about the commit
just install HDRP from the package manager
but - show the files in your repo
you can just take a screenshot of the repo from github
this?
yeah see - you committed the Library folder
and the Temp folder
so you screwed up making the repo
that's why the repo is so large
So the git ignore is not doing anything?
You probably added gitignore AFTER committing the library folder
or you just didn't set up an appropriate gitignore file
hmmmmm okay okay
the easiest thing to do here will be to just delete the repository and create it fresh
but you say that if i just start a normal unity 3d project, and then just add the hdrp package. my project then converts into an hdrp project?
Yeah I will probably do that
I mean it's easier to just start with HDRP
You will need to setup harp properly
don't see any reason to do it that way
hello. why does GPU Instancing not cause any performance boost? im spawning 65k cube, with standard material and "GPU Instancing" ticked on. i get the same 7-10fps.
Not a code question
where do i post ?
not here...
#π»βunity-talk if nowhere else
bit confused i tried to replicate some code from unity's documentation and its not working in my test script. im trying to load an asset reference if the field is set like so:
public class LoadWithReference : MonoBehaviour
{
[SerializeField]
AssetReferenceT<MeshAsset> _meshAssetReference;
MeshFilter _meshFilter;
MeshRenderer _meshRenderer;
void Awake()
{
_meshFilter = GetComponent<MeshFilter>();
_meshRenderer = GetComponent<MeshRenderer>();
if (_meshAssetReference != null)
Set(_meshAssetReference);
}
public void Set(in AssetReferenceT<MeshAsset> assetReference)
{
if (_meshAssetReference != null) //release if already set
_meshAssetReference.ReleaseAsset();
_meshAssetReference = assetReference; //set it again
AsyncOperationHandle<MeshAsset> handle = _meshAssetReference.LoadAssetAsync<MeshAsset>();
handle.Completed += OnCompleted;
}
private void OnDisable()
{
if (_meshAssetReference != null && _meshAssetReference.IsValid())
_meshAssetReference.ReleaseAsset();
}
//...etc
}
currently the field is not set and yet when i press play i get:
UnityEngine.AddressableAssets.InvalidKeyException: Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown. No MergeMode is set to merge the multiple keys requested. Keys=, Type=MeshAsset
OperationException : ChainOperation failed because dependent operation failed```
The error points to this line `AsyncOperationHandle<MeshAsset> handle = _meshAssetReference.LoadAssetAsync<MeshAsset>();`
Which i don't understand, why is that function even occurring since the field is not set so it should be null π€
You'll want to check _meshAssetReference.IsValid() before trying to load it
but shouldn't != null be sufficient?
the field hasn't been set to anything in inspector
it inherits from Unity's Object so it should be able to be null right?
AssetReference is a struct
nvm I'm wrong it's not
but still
it's not going to be null
it's just going to be invalid
Unity serializer doesn't leave things null
And it doesn't inherit from UnityEngine.Object.
oh i misread the source it restricting the generic to object ok that makes more sense whats interesting is unity's doc uses null check https://docs.unity3d.com/Packages/com.unity.addressables@2.2/manual/asset-reference-create.html
Hey guys, what is the best way to find the root cause of this issue?
did you extract a stack trace? That would be the place to start
There's a utility under Tools in your screenshot to do it, and instructions in the logcat docs
Is there a way to automatically call reimport on a bunch of comoute shaders to recompile them every time I change a line In a Cginc they use?
I know unity is supposed to handle it automatically but Iβm running into a massive issue that makes compute shaders fail to recompile automatically, forcing me to reimport them all manually: #archived-shaders message
nvm sorry, figured out that setting the shaders all to use the platform preprocessor fixes it
Hello. I'm working on a 3D character controller. Right now I'm not using rigidbody or collider, movenet is only done through scripts. The colliding is done via raycasts (its a cylinder collider). Might sound stupid but I need it this way to have full control over player's surroundings and velocity. So i'm just modifying the transform every frame. It works, but sometimes i clip through objects (as expected). I could easily add the collider and fix it, but i dont want to because i dont need it. What should i do?
The alternative would be to add rigidbody and collider back, but instead not use the raycasts. But i need them to get surface normals. Maybe there's some other way? OnCollisionEnter doesnt cut it
https://docs.unity3d.com/ScriptReference/Physics.ContactModifyEvent.html can be used to control the contacts generated by PhysX.
Hello, since yesterday when I press the ctrl key my scene blinks and it prints this in the console, Im using Unity 6 Preview
I'm re-writing my managed voxel renderer to use jobs for both the data and rendering itself.
I populate a collection (I've tried NMHM which required a huuge capacity due to collisions(?) like 10x the known worst case), NHM, now NL)
with this collection I can sample the noise of any voxel values neighboring the chunk border. This way I can clip chunk borders without needing to know anything about/load the neighbor chunk itself.
I schedule that to run and when it's finished I chain the render job to it..
I use .AsParallelWriter when writing the skirt, and AsParallelReader when reading the skirt. I've also tried a normal writer/reader.. but I'm guessing if I want it to work correctly in a IJobFor it needs to be parallel?
The problem is with the attached photo. I've debugged the positions and made sure the skirt values are correctly encompassing the entire chunk.. but for some reason here it's only picking up some values?
private IEnumerator RegenerateRoutine()
{
_chunkDataJob.Skirt.Clear();
_chunkDataJobHandle = _chunkDataJob.Schedule(ChunkSize, 1);
// bad to call immediately? negates parallelism
while (!_chunkDataJobHandle.IsCompleted)
yield return null;
_chunkDataJobHandle.Complete();
// Provide render job with the new data
_chunkMeshJob.voxels = _chunkDataJob.Voxels;
_chunkMeshJob.skirt = _chunkDataJob.Skirt;
_chunkMeshJobHandle = _chunkMeshJob.Schedule(dependsOn: _chunkDataJobHandle);
// bad to call immediately? negates parallelism
while (!_chunkMeshJobHandle.IsCompleted)
yield return null;
_chunkMeshJobHandle.Complete();
// advanced mesh api (much faster(?))
_chunkMeshFilter.mesh.SetMesh(this);
_chunkMeshCollider.sharedMesh = _chunkMeshFilter.mesh;
}
Very new to jobs/burst but I've been learning a lot on github, the chunk itself is rendering fine without using any parallel writing, it's only when I try to write/read do I get this jagged appearance.. I know my face culling logic in the renderer itself works as this is based on a managed version. It definitely seems like the collection isn't writing, or reading the right values
it looks like it's being read when the data isn't fully finished writing, but how would that be possible if I'm waiting for completion/chaining dependencies ?
to be clear the mesh job is just an IJob, the data is IJobFor which makes sense for it
- There's no point making a dependency if you're waiting for the job to complete anyway.
(totally, just trying everything I can at this point)
What does your job look like?
Just share the whole file correctly. Upload to a paste site. !code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A bit too complex to find the issue by just looking at the code. I'd step through the code with a debugger and confirm that all the values and calculations are what you expect.
Hi all,
Am using URP and seem to be having some trouble passing depth to my compute shader, I have called:
_computeShader.SetTextureFromGlobal(_kernel, "depthTexture", "_CameraDepthTexture");
And also enabled depth in my URP options and end up getting "Property (depthTexture) at kernel index (0) is not set"
Does anything else have to be enabled? I checked the frame debugger and it seems like something exists at least
(Not sure what the right channel for this was so apologies)
Most likely a race condition
Then debug it. If there's a racing condition, you're probably writing to the same index ranges from several threads. Confirming the values and indices involved with a debugger would help you identify that.
Speculating is not gonna help. You should debug properly.
Why can't a debug log be helpful? It totally can. And If it really doesn't, then stepping through the code, or using log breakpoints can.
Of course you can
This is just code running on separate threads. You just need to disable the burst compiler
And weith some tinkering you can probably even debug burst compiled code
If you don't know how to debug properly, then ask about that, instead of expecting people to run your code in their heads to find the issue.
This video covers some of the questions you might have about debugging a job:
https://www.youtube.com/watch?v=nou6AIHKJz0&ab_channel=LeeHammerton
hello can someone help me in putting ads in my game i have no experience in it and tried several times from many documentations and videos but never succeded if someone has done it and wants to help, DM me i'd be very gratefull
Post a specific question, and your possibility of getting helped may increase. Also, I suppose, this refers to another channel. Try #π»βunity-talk
Can anyone help me do to damage model for flight sim?
If you have specific issues then ask about those
I doubt anyone is going to go "yes sure, I will help you build the entire system"
I want to know how it works. Any documentation or something.
so I can implement myself
hey all, is there anyway to programmatically add new agentTypes for the NavMeshSurface component baking? I know I can define it using the editor, but i would like to programmatically create agentTypes so i can loop through and re-bake terrains during the runtime.
Hi everyone. I need help with Coroutines and web requests. I need the script to return data for other scripts to run. Is this possible? If so how?
Yes. Events.
Sorry for the late reply. How would I do that exacly?
I also don't want the frame held when doing the web request
Events are used to be subscribed to, making other scripts be able to retrieve data from the one holding the event. Could you, please, explain your issue more thoroughly?
I need a script that will request data from my website like version codes, ect. I want this scriptr to be callable by other scripts to get data when needed
Did you look at the examples in the documentation?
I see, web requests is something I cannot help you with
I did and couldn't find any help
Maybe ask a more specific question. The docs have a non-blocking coroutine example for a get request
They do?
Problem solved thanks to Opera's Aria
Hey guys, I have a C# question;
I have a list of structures, which I want to author and then put onto unmanaged memory(for jobs & stuff). I plan to do this by malloc-ing space for each structure and then maintaining a native array of pointers to these structures. These structures need to implement certain functionalities, defined by an interface. In managed-memory I author this as a list of interfaces. However to convert this to a pointer to unmanaged memory I run into some problems.
- Firstly, to malloc memory I need to know the underlying type. I guess there might be a way with reflection.
- Secondly, to get data from the pointer in a job I need to cast it back to the underlying structure. Interfaces are managed objects so I canβt cast it to an interface pointer unless I make the interface unmanaged somehow.
Are there any workarounds to this problem? Perhaps a different way to get structs to inherit functionalities so I can call them without knowing their specific type?
What's wrong with a regular blittable struct and a NativeArray<MyStruct>?
There's not one type of structure in the array. There's multiple different structs all of different strides that all implement the same methods
Like if I had an interface for a car(ICar) I can have a list of cars called List<ICar> in which I guarantee all of them have the same basic functionality--I just need to translate this to unmanaged memory.
In that case there's an even bigger problem which is you won't even know how to index your objects in this array
They're pointers to memory scopes I malloced
the memory scopes aren't the same size though, but they don't need to be (I don't think so fundamentally)
do you really need them to be different structures? It might be better to make a struct that's a union of them all and just make an array of those
with an enum flag or something denoting the type
basically - don't try to force polymorphism into the native world
It'd be really wasteful memory-wise for me to do this. There's some structs that require a lot of memory and others that don't.
how much is "a lot"?
and how many things will there be
and if so - you could store that extra data in a separate collection if those things are rare
If size is a concern, your struct can very well be just a tag and a pointer to another struct that contains more data for the specific type.
I'm trying to do this for some entities(like animals). They have different behaviors and different stuff they need to keep track of. A certain animal needs to keep track of different data & different amounts of data than another animal.
I mean... fundamentally I should be able to malloc different sizes and store their pointers in a native array to use them in a job
yes you fundamentally could but the things that are good for performance are not necessarily things we normally consider "clean"
there are large performance advantages to having all your data in a single colocated array rather than all over the place with pointers and malloc'ed locations
It's also just two different ways of writing the same code.
Basically all the things that make OOP and polymorphism nice are actually anathema to performance and how computers actually work
I have something similar in my code. But instead of structs I store values in a big number of arrays for jobs / compute shaders. And in managed code I use a number of "view" classes and manipulators that change the underlying arrays directly.
This is like completely abandoning OOP, I mean I could try something like that
yeah, I went pretty much data oriented with oop convenience
this seems like you are trying to implement C++ inside of C#, why not just write a native code dll
I would if I knew how lol-- I can do some research if u have some pointers
Unity docs have a complete section on it
Seems like a rabbit hole but I'll tell u guys if I figure out a way to do it
It's not dificult, I mean Unity devs built Unity that way so how hard could it be?
Hi, I have a game with levels and I have an editor inside the unity editor to make them but I don't know where to save them (I don't want/can't save them in different scenes etc...). I want to save them in a json (it's actually just some lists of points), problem is idk how to create a json file inside of the assets folder neither how to access it (the path), how do I do that? Or is there a better way than json to save lists of vector2D/bools/in
Famous last words
you could save it as json in StreamingAssets or you could use ScriptableObjects instead
Yeah I found that out but I have no idea how to use ScriptableObjects
if you want to save in the Assets folder look at Application.streamingAssetsPath
Thanks
then don't you think it's time to learn?
That's what I'm doing π
It's honestly just two different ways of writing code, if you are deep in OOP you might have only worked with the OOP way:
(The following codes are in TS because C# doesn't have real nice union, but the examples are just to demonstrate how to write the exact same code in two different ways)
type Shape = {
calculateArea(): number
}
class Circle implements Shape {
constructor(
private radius: number
) {}
calculateArea() {
return Math.PI * this.radius * this.radius
}
}
class Rect implements Shape {
constructor(
private width: number,
private height: number
) {}
calculateArea() {
return this.width * this.height
}
}
const circle = new Circle(42)
const rect = new Rect(42, 69)
circle.calculateArea()
rect.calculateArea()
type Shape =
| { type: 'circle'; radius: number }
| { type: 'rect'; width: number; height: number }
function calculateArea(shape: Shape) {
switch (shape.type) {
case 'circle':
return Math.PI * shape.radius * shape.radius
case 'rect':
return shape.width * shape.height
}
}
const circle: Shape = { type: 'circle', radius: 42 }
const rect: Shape = { type: 'rect', width: 42, height: 69 }
calculateArea(circle)
calculateArea(rect)
The first way fundamentally relies on dynamic dispatch, which C++ implements it as virtual function table. If you want to get that in your native code, you will have to basically reinvent it yourself.
The second way however does not require that.
OOP encapsulates data and behavior together into classes, whereas functional separates them into plain data (with no behavior) and free functions operating on those data (behavior). It's not too difficult to change your code between the two styles once you understand them, and the functional style works a lot better with the constraint of Burst.
I'm not very used to that paradigm--and that way is very similar to DOTS I believe. I wanna try to see if I can mimic OOP with some custom code first and then I'll do that if I give up ig.
You can, by basically reinventing dynamic dispatch yourself.
Burst supports function pointer, so instead of IFoo with a method DoFooThing(), you would have a Foo struct with two fields, one is a pointer to the data, and one is a function pointer. And calling DoFooThing would be calling the function pointed by the function pointer, with the first argument being the data pointer.
levelData is a ScriptableObject class, this script is not from runtime but it's only runned manually from the editor.
How can I make the values be permanents? I want them to still be available when I start the game
public void SaveLevel(){
if(levelData.levelPoints.Count >= level){
levelData.levelPoints[level-1] = path.points;
levelData.obstacles[level-1] = new List<Vector4>{};
levelData.end[level-1] = new List<Vector3>{};
levelData.levelType[level-1] = "default";
levelData.minimumDriftDuration[level-1] = 0f;
levelData.isNight[level-1] = false;
Debug.Log(levelData.levelPoints[0][1]);
}
else{
levelData.levelPoints.Add(path.points);
levelData.obstacles.Add(new List<Vector4>{});
levelData.end.Add(new List<Vector3>{});
levelData.levelType.Add("default");
levelData.minimumDriftDuration.Add(0f);
levelData.isNight.Add(false);
}
}
I don't recommend using Scriptable Objects to save data, but if you are--I believe it's something along the lines of
EditorUtility.SetDirty(scriptableObj);
AssetDatabase.SaveAssets();//
AssetDatabase.Refresh();
You should really save in another format though. Scriptable Objects are mostly for settings and shouldn't be changed
Well they're never gonna be changed at runtime if that's the problem
Anyway, thanks for the help
oh then it's fine
Where do I put that piece of code please?
When you want to update your asset. You can think of your instance being a copy of the scriptable object, and when you call that it copies it back. That's not really what it is but it's close enough in effect
you will need a using UnityEditor;
put this
using UnityEditor;
Thought I had it sorry
Got another problem (kinda related)
It only saves part of the data
I have problems with this part:
public List<List<Vector2>> levelPoints = new List<List<Vector2>>{};
First of all it does not show in the inspector (which might be the default behaviour for lists into lists, idk)
Secondly, this part doesn't seems to save for some reason...
I add things to it like that:
levelData.levelPoints[level-1] = path.points; //path.points is List<Vector2>
to show up in the inspector you can create your own class:
[System.Serializable]
public class Path
{
public List<Vector3> pathPoints;
}```
And then have a List<Path> in your script.
It also makes it more readable and might fix your saving bug.
Ok thanks
public class LevelData : ScriptableObject
{
//Vector2: x,y pos of the points
//public List<List<Vector2>> levelPoints = new List<List<Vector2>>{};
public ListsOfLevelPoints levelpoints = new ListsOfLevelPoints();
}
public class ListsOfLevelPoints
{
public List<LevelPoints> list;
}
public class LevelPoints
{
public List<Vector2> list;
}
Like that?
Sorry I'm still new to this lol
That throws me an error, cannot converts from LevelPoints.levelPoints to Vector2
AAh those errors come from the script saving them
But now it does show up in the inspector
Still trying to find how to access the values
Now how to add things
I figured it out
I don't know if it fixed my problem
But at least now it shows up in the inspector
Thanks a lot
It fixed it
Tysm
im trying to update normals after editing vertices but i am getting this error:
System.IndexOutOfRangeException: ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.
This Exception was thrown from a job compiled with Burst, which has limited exception support.
not sure why though, this is the setup:
var vertHandle = new Deform(vertexData, uvs, output, spline, span, scale).Schedule(output.Length, output.Length / 8);
var tris32 = meshData.GetIndexData<int>().AsReadOnly();
var normalHandle = new RecalculateNormals32Bit(output.AsReadOnly(), tris32, normals).Schedule(tris32.Length / 3, tris32.Length / 8, vertHandle);
wondering if passing in output.AsReadOnly() is the issue? though i don't see why because recalc of normals depends on the completion of the vert handle so it should be fine...
ah i have fixed it nevermind π
Ok, after a lot of brainstorming I came up with this solution. We can expose the functions thatβs originally defined by the interface by using a function pointer. Then we can define a struct that holds these exposed functions as well as the original pointer which can be put in a native array and used in a job.
To address mallocing enough space for the data we can define a function that queries the size of the object. When we create a new object we need to assign the function pointers to the specific functions defined by the specific structs.
Is this the best way to do this? Probably notβtell me what you guys think though.
I don't think following pointers in jobs makes a lot of sense (performance/safety wise).
I mean it's a tradeoff. OOP is often easier to define contained functionality with, and using 2-4 pointers in a job probably isn't the bottleneck
Out of curiosity, what are you actually trying to do goal-wise? I would shoot this down in a PR so fast
I'm trying to do a bunch of calculations for some agents(mainly pathfinding) in a Unity parallel job where the each execution thread(?) handles an individual entity
There's also other considerations about storage and disposal cause I'm doing this for a procedural world
Pointers won't be the thing that's hurting performance the most, but all the cache misses because all of your data is scattered everywhere.
Actually--I don't think so, each thread(?) handles one entity at a time. So all data about that entity will be on the same core's cache so there shouldn't be that many cache misses
That's already a performance loss
How so? Is that not how parallel jobs work?
No, well, not exactly
Usually your data are packed into a continuous region of memory, and when you schedule a job to run in parallel it has a batch count, so each thread processes batch count amount of work rather than 1 at a time.
It means that a thread when finishes one piece of work, the next piece's data is right there in the CPU cache and no miss.
I understand that--but if each job is a lot of work, the main concern is the cache misses inside a long job rather than between the next one. I plan for each job to do a lot of work, and the cache miss between processing the next entity is far less of a concern than the cache miss inside a single job.
What I mean is that if you have a job that processes 10,000 jobs, and each one takes 0.01 ms to complete, cache misses between them matter a lot, but if you have 100 jobs that take 1 ms each/thread cache misses between them matter less than they do inside it
Also I don't plan to put a lot of memory in these entities either
I'm not sure that's quite true, your IntPtr obj will be all over the place in memory, so every work which needs to dereference that, will be an almost guaranteed cache miss.
Yes but each job will only dereference it once and then process a long task
what is happening in that long work unit?
Pathfinding mostly I think
Sure I guess, but yeah you have just effectively reinvented dynamic dispatch with a vtable and a pointer to the object.
and the data of the graph fits into one memory page?
No--but the data is partitioned and it's complicated
I'll worry about cache misses with the graph later
you should worry only about them because it sounds like those are your bottleneck
Yeah exactly--but I just wanted to answer my question from earlier; also someone who really wants to stick to OOP can use the reference
hello all, how do i make this code function properly? i want to make an airship hover in place, and this code works fine if angular drag is set to some arbitrarily high number, but when i set it to 1 the airship flips out and starts spinning weirdly
private void ApplyFloatingPower()
{
Vector3 centerOfMass = rb.centerOfMass;
float upwardForce = -rb.velocity.y; // Invert the velocity vector to cancel out the vertical velocity
rb.AddForceAtPosition(new Vector3(rb.velocity.x, upwardForce, rb.velocity.y), centerOfMass, ForceMode.VelocityChange); // Apply the force as a velocity change// Calculate the current up direction of the object Vector3 currentUp = transform.up; // Calculate the desired up direction (Vector3.up) Vector3 desiredUp = Vector3.up; // Calculate the rotation required to align currentUp with desiredUp Quaternion targetRotation = Quaternion.FromToRotation(currentUp, desiredUp) * rb.rotation; // Smoothly interpolate towards the target rotation rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, 1 * Time.deltaTime); // Apply damping to the angular velocity to reduce oscillations rb.angularVelocity *= (1f - 1 * Time.deltaTime); }
Looks like ai
? ah i did run this through chatgpt a few times, but each iteration it spit out just made things worse lol
Man this code is becoming more cursed the more I looked at it
yeah sorry, physics is not my forte
set velocity to zero // Will not move
set gravity off // wil not fall
result - hovering
That's definitely not an advanced channel issue.
Hi. Does anyone know if is it even possible to create an attribute that makes it so when the method is called, it automatically adds that method's name to a list? Like for example something like this:
public class RandomClass
{
[Replayable]
public void DoSomething()
{
//whatever
}
}
And when I do RandomClass(), as it has the [Replayable] attribute, it should automatically call like another method. Is that possible?
you would have to write a source generator that hooks into these attributes at compile time and extends your code to make these additional calls.
hmmmmm okay. I think I could do something like that. Thanks
any one here know the algorithm to calculate normals for a mesh ?
ive tried two methods and it doesn't produce the same as unity's built in one i have no idea which algorithm they are using but their solution works
Have a look at the implementations here https://github.com/gradientspace/geometry3Sharp
is this unity's ?
No
ah whats the bet it uses the same one i already use
there are many ways to calculate normals
Look at that library
yet unity's worked exactly how i needed it but their code is closed off
It has them all
i only see one in their code?
unity probably is a cross-product average of all incident vertex edges or an interpolation of face normals calculated from triangle edge cross product
the two i tried was sum the cross products for each vertex then normalize on the next pass, and the other was sum the normal * half length of the normal magnitude and then normalize those
the issue was edge vertices produced wrong normals
since they only join to half as many faces
This is the only normals calc i can see in that geometry project
You have to intensely guide gpt for it to give you anything useful
Does look like what unity does with its area weighted option?
are you sure thats what unity does though ?
this is what i originally did:
for (int i = 0; i < _triangles.Length; i += 3)
{
int a = _triangles[i];
int b = _triangles[i + 1];
int c = _triangles[i + 2];
var side1 = _vertices[b] - _vertices[a];
var side2 = _vertices[c] - _vertices[a];
var normal = math.normalize(math.cross(side1, side2));
float area = 0.5f * math.length(normal);
_normals[a] += normal * area;
_normals[b] += normal * area;
_normals[c] += normal * area;
}
then i normalize all the normals on the next pass
but it produced different normals to unity's
can't be sure, but it seems to be a reasonably generic algorithm.
Why do you multiply by area if you're going to normalize it again?
Also that is how unity should be calculating normals(idk about multiplying by area)
i dunno thats just how the algo is Β―_(γ)_/Β―
a large area adjacent to a vertex has a larger influence on the normal than a smaller one
Oh so the normals are different per vertex... I see
yes they have different adjoining faces
in this approach to normal calculation on a 3d mesh, yes, this should also get around the weird-boundary-edge-vertex-normal-problem
hey, i'm also trying to figure out how to give a sprite thickness, don't listen to people saying "well use a mesh duhh" because in the game they don't use meshes, it's part of the game's shader, i have NO CLUE how they managed to achieve it but it's probably something to do with parallax shaders, if you figured out how to do this please tell me i'm also trying my best to replicate this effect
i MANAGED to replicate it (poorly) on blender, but i have no clue how to do it on unity
@compact ingotdont suppose you know how they recalculated the mesh tangents too?
add a normal map that your shader uses to do some edge highlights/shadows
ive got no idea on that algorithm
https://docs.unity3d.com/ScriptReference/Mesh-tangents.html its mentioned here how it is calculated.
hmm that does not seem easy
check listing 7.4 here: https://foundationsofgameenginedev.com/FGED2-code.cpp
(this is c++)
thanks!
btw, this has all the answers: https://foundationsofgameenginedev.com/
neat, once this is done i finally got all the mesh generation applied to job system
i don't think it's a normal map because i've seen the game's textures and they dont use normal maps for the sprites, if you see how they look in-game it looks like the sprites have some sort of thickness, i SUPPOSE they use a parallax shader but i have no idea how to do it in unity
you need a data source for those effects, and a normal map is the richest data-source you can have for them before using a mesh
it doesn't mean its rendered like a regular normal map. Its just input for the custom shader that adds the shadows & highlights
actually it looks like it could also just be a bump + occlusion map, and the normals for the highlights are calculated from the bump
anyway, light edges on sprites are typically done with normal maps, the shadows could be something entirely separate (a post effect), assuming these are skeleton animated?
okay i see, i'm less than a beginner on shaders and complex stuff like this, so i kinda get what you mean but there are a lot of stuff that i still don't understand, and i wouldn't know how to replicate it on unity
have a look here: https://unity.com/how-to/2d-light-shadow-techniques-in-the-universal-render-pipeline
Maybe this is the wrong place to ask but does anyone know if it is possible to create a dotween sequence and run it in editor mode? I am woring on an aniumation tool and was curious about testing animations in Edit Mode
DOTween is the evolution of HOTween, a Unity Tween Engine
Could likely use the alpha channel as both alpha and height for a flat object with rounded edges like that. You'd need to add some blur to the edge, if course, and use alpha clipping.
Another option would be to use a geometry shader to just draw more planes for each sprite, to provide edge depth
how do I retrieve these values via scripting?
I tried this, but it's giving me way more values than I expected. I want to just return the 3 AnimationCurves
Can I serialize and select between delegate functions in editor?
i'd also like to know if there is a good way to go from like a visual graph to a c# function based on a GUI like how they do it in visual effect graph
You can do events I think
Well, UnityEvents at least
That's not what I was asking though
I was just asking how to get the animation curve from an animation clip
I want something more type-safe, I want to enforce selected functions have a specific signature
How about an enumerable variable, as well as an enum/action dictionary?
A dictionary lookup doesn't make sense, I could just use the enum values to index an array
Fair enough. I prefer dictionaries because I move items around a lot.
Or if you want items blank. Though ig it depends on context and preference.
does anyone know what "=>" is doing here?: (Grid<GridObject> g, int x, int y) => new GridObject(g, x, y). I thought it was related to lambda function but i am not so sure anymore. It looks more like just declaring and initializing a new GridObject
Shortcut for return
Or just single line methofs
int AddOne(int x) => x + 1;
so AddOne is a method that takes input x and returns x+1 right?
thanks! I think i understand
Hey folks, could you mention a scenario, when using fp16 provides visual artifact/degradation compared to fp32?
anytime you have very very large objects or objects very far away from the worlds origin point
floating point numbers are just approximations, the larger the number gets the more precision is lost in that approximation
can someone help me with this? I can't find any documentation online about what a curve binding is and how to use it
all I want to do is get the 3 curves from the animation
but the function is returning 723 items in the array of curves for some reason
I assume it has to do with how curve bindings work, but I'm not sure what to do with the data since I can't find any documentation online about it
why does a curve binding give me an entirely new AnimatorCurve? How does it go from 3 curves in the animation to 723 bindings and how do I use those to get back to 3 curves?
do I have to combine them somehow?
16 bits can only store 65,535 unique numbers, while 32 bits can store 4.2 billion unique numbers
With floats, when you go twice as far away, you get half the resolution
So since 32 bit floats have much higher precision than 16 bit floats, you'll have better resolution throughout
I have a build error:
MyScript, No suitable method found to override: OnValidate()
That script inherits from LayoutGroup and is inside an Assembly. I added a reference to UnityEngine.UI, but that didn't fix the problem.
It's probably not implemented in the base classπ€·ββοΈ
Remove the override keyword and it should work probably
nah, it is. The compiler doesn't give me an error, only when I try to build does it show up.
ah I found the problem:
What is making him do this?! Red arrow is where I press a button which changes a single integer, which should then be simply updated to GPU? I ain't even rendering here man
Without seeing the hierarchy view how can we know
Oh it's rendering
Time for the frame debugger
What do you see in the GPU usage hierarchy if you select the frame with the spike?
would get the frame debugger out
Hey thanks!
Why would be more precision lost? π
Ok I got it π
This missing reference is eating my head, Basically this only comes sometimes, if i add some debug or something in the code and run again its not coming, also in the build its not happening, only in the editor its happening, Is there any fix for this or has any one faced this before? please help.
Error:
MissingReferenceException: The object of type 'UI_References' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.StopCoroutine (UnityEngine.Coroutine routine) (at <2d8783c7af0442318483a199a473c55b>:0)
UI_References.SetLoadingScreen (System.Boolean status, System.String msg) (at Assets/UI_References.cs:111)
LoginManager.Init (System.Boolean isTestUser) (at Assets/LoginManager.cs:102)
GameConfigurationManager.ApplyRemoteSettings (Unity.Services.RemoteConfig.ConfigResponse configResponse) (at Assets/UI Manager/GameConfigurationManager.cs:101)
Unity.Services.RemoteConfig.ConfigManagerImpl.HandleConfigResponse (System.String configType, Unity.Services.RemoteConfig.ConfigResponse configResponse) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:553)
Unity.Services.RemoteConfig.ConfigManagerImpl+<>cDisplayClass46_0.<DoRequest>b0 (UnityEngine.AsyncOperation op) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:542)
UnityEngine.AsyncOperation.InvokeCompletionEvent () (at <2d8783c7af0442318483a199a473c55b>:0)
Scriptable Objects professionas, how can I check if an asset has been saved/is being saved? I'm losing some data on a material after an event to save is triggered. This is because Im setting some compute buffers into a material in the scene, and after the event of saving the data gets cleared, so I need to reset it. I would like to subscribe to an event to know if an aset has been saved and reload the textures if thats the case
But this one is only for before
I need for after it has been saved, to reload the data, since after being saved, material data that doesn't have a property gets flushed (like compute buffers)
I found some issues online but sadly they are all unavailable to be seen in unity forums
Hello guys,
is there any option for UIToolkit EnumField's Dropdown Position from code
there's not a lot to go on here, but the error is quite clear in what the problem is - are you expecting UI_References to be destroyed at any point? changing scenes? have you explicitly defined code execution order?
hey guys. I'm writing my own custom collision detection system using SAT. I'm trying to find collision points and I'm struggling to do so here. it works fine in some cases but not in others, it seems. seems to mostly bung up in vertical edges . any idea what might be happening?
and before anyone asks why I'm not using unitys system, it's because I have to write my own for what I'm making.
I'm following this angels tutorial playlist
https://youtube.com/playlist?list=PLSlpr6o9vURwq3oxVZSimY8iC-cdd3kIs&si=io25V7nDvhrNNth7
Well we haven't seen any code of course but perfectly aligned edges in general present a problem because you don't really have a contact "point" but really a manifold with infinite points along the touching edges
so I'm sure this is a special case in the code somehow
but how come it's working fine with horizontal along horizontal?
it seems to only be an issue with the vertical edges
no idea, that will boil down to how your code works
I can send it when I come back if you want to have a look, I'll send the relevant things
hey heres the code if u wanna have a look
If you are going to attempt to make your engine you should instead work on your debug skills than relaying on external help.
Why are you not able to find the issue ?
I'm sort of just following a tutorial, and until now everything has been working fine and I've been able to solve most issues myself, but when it comes to this the math is quite confusing
so i'm struigglign
What have done to attempt to fix your issue.
Because simply reading code is most of the time not enough.
Did you isolate your issue ?
Did you profile your code ?
If you are saying that your issue with vertical edge, have you printed what is the result of the expected collision.
Are you aware of what is a debugger ?
yeah, I'll have to try these when I get back from work
let's say I have a class Player which uses interface IAttackable. I then do the following: IAttackable attackable = new Player(); . What would be the benefit of initializing this?
wdym by "the benefit of initializing this"?
The benefit of the interface is that you could have a piece of code that works with IAttackable. That one piece of code can work with a Player or any other type that implements IAttackable. So you don't have to write a bunch of different code that does the same thing
e.g.
public void DealDamage(IAttackable target, float damage) {
target.TakeDamage(damage);
}``` as a quick dirty example
so am I specifying the interface of player there?
wdym? No you're not "specifying the interface" of anything
IAttackable attackable = new Player();```
This code just declares a variable and assigns it to a new instance of the Player class
nothing else
It does illustrate how a variable of the interface type can accept a value of a class that implements the interface though
you are creating a player class which only exposes the interface
creating an instance of the Player class
gotcha. I understand
thank you both! Sorry, I am not up to speed on the lingo. Appreciate the patience
Hey guys I'm making a SO that's capable of generating new cards for my game but I have one issue, I need to be able to know when the AssetDatabase has refreshed and unity has compiled my new generated code so then and only then I can generate the new SO from that newly created class. The code I'm sending here is still creating the new card with the BaseSO class for testing purposes, but I've already caught on that this issue is gonna happen. Any tips?
private void GenerateScriptableObject()
{
//Find the correct class to inherit from
//Create the ScriptableObject
BaseCardSO card = ScriptableObject.CreateInstance<BaseCardSO>();
AssetDatabase.CreateAsset(card, _cardSOPath + _cardName + ".asset");
card.Name = _cardName;
card.Description = _cardDescription;
card.DeckType = _deckType;
card.Image = _cardImage;
//Clear the fields
_cardName = "";
_cardDescription = "";
_deckType = default;
_cardImage = null;
}
private void GenerateScript()
{
//Class name is going to be the same as the card name, prefixed with "XXX_" where XXX is the deck type
var className = GetDeckTypePrefix() + _cardName;
//We make sure there are no spaces in the class name and if we remove them and make the next character uppercase, we also remove special characters other than the underscore
className = CreateValidClassName(className);
//Create the Script
string script = "Boilerplate Code here..."
System.IO.File.WriteAllText(_cardScriptPath + className + ".cs", script);
//After creating the script, we need to refresh the asset database so Unity can recognize the new script
AssetDatabase.Refresh();
}
}
you can trigger a reimport on the new file and just assume that on the next line it was compiled. it shouldn't really matter if it was compiled, i suppose you just want to be sure that it was imported and all the processing for the given asset type has been performed? UnityEditor.AssetDatabase.ImportAsset("path/to/script", ImportAssetOptions.ForceUpdate);
Actually managed to achieve my goal by using the CompilationPipeline.assemblyCompilationFinished event and then putting my logic there, but thank you anyway! Now my issue is with getting the scriptable object fabricator to know this new type exists xD
Yup in regards to getting the new type I create, can anyone spot something? I can guarantee that both the namespace and assembly def of BaseCardSO and the dynamicly created types are the same:
private string CreateScriptBoilerplate(string className, string cardName)
{
return "using System;\nusing UnityEngine;\n"+"namespace Assets.Project._Scripts.SOArchitechture.Cards{ \n" +
"\n[CreateAssetMenu(fileName = \"" + cardName + "\", menuName = \"Cards/" + cardName + "\")]\n" +
"[Serializable]\npublic class " + className + " : BaseCardSO\n{\n " +
"public override void ActivateCard()\n {\n base.ActivateCard();\n Debug.Log(\"Activating Card: " + cardName + "\");\n }\n " +
"public override void DeactivateCard()\n {\n base.DeactivateCard();\n Debug.Log(\"Deactivating Card: " + cardName + "\");\n" + " }\n " +
"protected override void OnEnable()\n {\n Debug.Log(\"Created script of type: \" + GetType() + \" in assembly: \" + GetType().Assembly.GetName().Name);\n" + " }\n}\n} ";
}
private void GenerateScriptableObject()
{
//Fully qualified name of the class
var namespaceName = typeof(BaseCardSO).Namespace;
var assemblyName = typeof(BaseCardSO).AssemblyQualifiedName;
var className = _newClassName;
string fullyQualifiedName = namespaceName + "." + className + ", " + assemblyName;
Debug.Log(fullyQualifiedName);
Type newCardType = Type.GetType(fullyQualifiedName);
if (newCardType == null) //<--- Always null
{
Debug.LogError("Could not find the class " + _newClassName + " to create the ScriptableObject");
return;
}
(...)
would it be faster to calculate a triangle normal in a compute shader or on the cpu when creating the mesh?
It Dependsβ’οΈ
How big is your mesh?
How are you making your mesh, how big is the CPU<->GPU overhead?
etc
im generating the tris on the gpu in a compute shader, then on the cpu reading it out and creating a mesh with it in a loop over the tris
just wondering cause if i do the normal calculation on the cpu im transferring less memory and the struct im using will fit evenly on the gpu cahce
WebGL topic but its more on the technical side:
In my browser game I do API calls to an external service, for that I use an api key that is stored as an const string in the code.
I imagine that it is possible to somehow extract that key for malevolent use.
What can I do to avoid that?
setup your own backend server and use that as a pass through
Then can't them spoof the communication between the server and unity?
(idk if that is the right term but I guess they could track every message that comes in and out)
that is possible, basically nothing is 100% secure you just need to make it very difficult or not worthwhile
Got it, so returning to the pass through, what should I search for? I have no knowledge in this so I'll have to study it
Called API shimming
Probably best to stick with the CPU then if you've already transferred it off
I don't think it'll be too hard to test both with your setup, but mesh normal calculations are generally pretty fast anyways
You should make your own backend, and let the backend call the external service. Ideally the endpoints backend expose are not just a straight proxy, but rather tightly integrated to your game.
Whatever external service you are using, there's a very good chance that it was not designed to be used directly on the client side (but rather intended to be used in your own backend). This means that very likely:
- The service does not have fine grained access control. Getting access to the API key will allow someone to do anything the key can do, eg if the service is a storage layer and you are only using it to update player scores, yet someone getting access to the key can modify not just their own score, but someone else's score, or even delete someone else's account.
- The service does not have any logging for you to know what people are doing with that key.
- The service does not have any rate limiting and someone can spam certain endpoints to bankrupt you.
With your own backend and you expose for example only a submit score endpoint, that's the only thing client can do, and you can properly protect that endpoint with authentication/logging/rate limiting.
with backend u mean on the website I host the webgl game right?
This service let me get text to speech audio, an it comes via a unity web request directly in form of an AudioClip
I image that in your way I should send the request from the side backend and then somehow transmit the output to unity
No, like a web backend. The service you are using is also a backend.
Is that service designed to be used in client directly?
Their documentation should be very clear about that. If the service is designed to be used in client directly, their docs will say so very clearly; if the docs mentions anything about the API key being a secret and should not be exposed, then the service is not designed to be use directly in client.
I think so
here's the service btw
https://elevenlabs.io/docs/api-reference/text-to-speech
Hmm not sure, I don't use it and from a quick scan of the docs nowhere it says whether your API key is sensitive or not, and the examples they show use keys client side, which seems to suggest your key isn't sensitive.
On the other hand, a quick Google search shows people who have their ElevenLabs API key compromised and used (Rabbit R1 being one of them which I found hilarious). When in doubt ask their support about your security concerns.
is there a way to temporarily disable scene view mesh/object outlines? (ideally without force-changing users' currently set "show mesh outline" setting, this is for a plugin!)
In a strange discovery, the issue with collision point finding seems to be isolated only between the vertices with index 1 and 2...
Anyone know why having a NavMeshAgent on my object, rotates its transform by -90 on X axis?
I think it has something to do with me using NavMeshPlus, it probably tries to rotate the object to fit the navmesh which rotates to accomodate XY
This looks like the relevant editor code:
https://github.com/Unity-Technologies/UnityCsReference/blob/77b37cd9f002e27b45be07d6e3667ee53985ec82/Editor/Mono/SceneView/SceneView.cs#L2286C43-L2286C63
Based on this, only AnnotationUtility.showSelectionOutline (internal) determines whether selected objects have outlines, and it's the same property that gets changed by the Gizmo GUI.
I think the only way you can avoid changing that property is using something like Harmony (https://github.com/pardeike/Harmony) to hook into SceneView and modify it.
hmmmm good point, but also, there is the s_CachedParentRenderersForOutlining and s_CachedChildRenderersForOutlining arrays in there 
but alas they seem to be populated on each call 
Only if s_SelectionCacheDirty is true, right?
hm, true
..this seems cursed
a true, "I could, but, should I?" situation
maybe it's fine to just, reflection edit the user scene view setting
just feels kinda cursed
If clearing the array with Reflection works, I would consider that less cursed, at least user facing. The user would be able to see the setting has been changed if they check the GUI, and try to change it.
I hope there's no assert checking if the input array is empty π
Otherwise you might need to give it a bogus renderer off screen.
hmmm my reflection isn't finding the field
oh boy okay might be a version difference
yeah, I'm on 2022 LTS
field isn't there
looks like on 2022 LTS I want s_CachedParentRenderersFromSelection
oh no it works
it shows up for one editor frame, and then disappears
same thing during assembly reloads
but yeah it seems to work otherwise!
@sage radish behold
public static class SceneViewHacks {
// theoretically should work from Unity 2022.1 to 6000.0 (I only tested in 2022.3)
#if UNITY_2023_3_OR_NEWER
const string FIELD_PARENTS = "s_CachedParentRenderersForOutlining";
const string FIELD_CHILDREN = "s_CachedChildRenderersForOutlining";
#elif UNITY_2022_2_OR_NEWER
const string FIELD_PARENTS = "s_CachedParentRenderersFromSelection";
const string FIELD_CHILDREN = "s_CachedChildRenderersFromSelection";
#elif UNITY_2022_1_OR_NEWER
const string FIELD_PARENTS = "m_CachedParentRenderersFromSelection";
const string FIELD_CHILDREN = "m_CachedChildRenderersFromSelection";
#endif
const BindingFlags bfs = BindingFlags.Static | BindingFlags.NonPublic;
static readonly FieldInfo sceneOutlineParents = typeof(SceneView).GetField( FIELD_PARENTS, bfs );
static readonly FieldInfo sceneOutlineChildren = typeof(SceneView).GetField( FIELD_CHILDREN, bfs );
/// <summary>Hides selection outlines until a new selection is made,
/// bypassing the user scene view setting</summary>
public static void HideSelectionOutlinesTemporarily() {
#if !UNITY_2022_1_OR_NEWER
throw new NotImplementedException( $"Outline hiding not implemented for unity {Application.unityVersion}" );
#endif
sceneOutlineParents.SetValue( null, new int[] {} );
sceneOutlineChildren.SetValue( null, new int[] {} );
SceneView.RepaintAll();
}
}```
Any ideas why it's firing the complete opposite way?
top transform is the red cube, bottom is the selected object
var raycast = Physics2D.Raycast(transform.position, Hero.Instance.transform.position, 9999, 10);
if(raycast.collider != null && raycast.collider.gameObject == Hero.Instance.gameObject)
the collider is always null
even if I walk into the raycast, it is still null despite the selected object having a collider and being on the right layer
You should assume any API you expose will be used by a thirdparty, and consider the potential abuse that could happen.
Wrapping an API is not the perfect solution, but it's way better than exposing your direct API key access to a thirdparty service. Having requests go through your server allows you to serve these requests within the context of your project, like you know a single client (IP, user) can't reasonably be doing thousands of requests per second.
Is there any guides on implementing IK for articulation bodies? I'm in the process of trying to create physics-based procedural animation.
Attempting to use any physics-independent IK solver (I've tried unity animation rigging (with animator set to animate physics) and multiple github repos) doesn't seem to work
Your raycast targets layers 1 and 3 and you're providing a position instead of a direction in the second arg
Update to this, I found Unity's already tried to address this issue with Burst-Compiled Function Pointers
https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-function-pointers.html
Do you have a tl;dr on what Burst function pointers solve here? To my knowledge they are just a workaround for not being able to store delegates in jobs, but you could always store actual C# function pointers (+ some state like a GCHandle if you had an instance to invoke on)
You can store a function pointer as a raw pointer like an IntPtr on a unity job, but to call it you have to convert it back to a delegate which is a managed type.
No you can't-- delegate* is a managed type
It's not
I tried--
If Burst considers it one, that's a bug in Burst
I tried storing it as delegate* unmanaged<void*, void>
it doesn't allow it to be stored
Yeah this is a Burst bug, thanks Unity
You can cast it at the usage site just fine though
[BurstCompile(CompileSynchronously = true)]
public unsafe struct FunctionPointerJob : IJob
{
[NativeDisableUnsafePtrRestriction]
public void* Callback;
public readonly void Execute()
{
((delegate*<int, void>)Callback)(10);
}
}
//
static void LogNumber(int value) => Debug.Log(value);
new FunctionPointerJob
{
Callback = (delegate*<int, void>)&LogNumber
}.Schedule().Complete();```
this works fine
Oh wonders-- Unity's UnsafeUtility doesn't recognize it as unmanaged last I checked.
Function pointer types in C# are unmanaged, they're just addresses and not reference types
I guess Burst doesn't account for that in its validation code
Yeah they probably only check IsPointer and not IsFunctionPointer
You could probably report it and pray for it to get fixed lol
I wonder what FunctionPointers are for then, if it's just to fix this bug then it seems an awful lot of work to make all this
Burst FunctionPointers are specifically for managed delegates, not raw function pointers
i.e. public delegate void MyDelegate(int a);
ah ok...
public unsafe struct EntityFunction
{
[NativeDisableUnsafePtrRestriction]
private void* _pointer;
public EntityFunction(delegate* unmanaged[Cdecl]<Entity*, void> pointer) => _pointer = pointer;
public readonly delegate* unmanaged[Cdecl]<Entity*, void> Invoke => (delegate* unmanaged[Cdecl]<Entity*, void>)_pointer;
}
you could work around it with this for the time being
Burst should let you store that
Not ideal though, since you'd need a special struct for each unique function signature
I see, didn't know there was an attribute for disabling unsafeptrrestrictions
There are quite a few niche attributes like that
Some of them have absolutely no documentation and I've never seen them used in any publicly available code
Thanks for the tip--I got it to work! Just gotta fix my saftey now
np!
if I make a ScriptableObject instance through code (via the ScriptableObject.CreateInstance function) how does that behave at runtime? does it get saved to the disk with the rest of the game? I'm thinking about using SOs for save files
no, you cannot save any SO at runtime without 3rd party assets
oof. thanks
Hi,
Does anyone know how to programatically recenter the world origin(I dont mean to create a new gameobject and then assign everything under it, that would be local recentering). My idea is to recenter to a specified point so it would be recognized as new world origin. This would also help in the case of photon which sends networked data based on world origin(i suppose)
The easiest would be to use HDRP feature "Camera Relative Rendering" https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@8.0/manual/Camera-Relative-Rendering.html
Obviously, it would not help with photon, but I'm pretty sure you do not need to recenter anything for photon.
Well at a basic level you would move all the root objects in the scene
yes we can do that but photon or anyother networking for the matter wont move the transforms based on that right? it would be local repositioning in that case.
yea recentering is one of the options iam exploring for my usecase, so basically i have a passthrough app which would allow users to place a fire-place in their environment and other users spawn around it(not -colocation). So my thought process is, since each user should be able to place a fireplace anywhere in their environment then it should kind of act like a starting point(aka new origin) and photon should spawn and move players relative to that origin?
Any other way do you think would be better?
I guess you are doing VR. You can send and receive whatever you want. You do not need to take the NetworkTransform.
Simply push the position and interpreted it the way you want on the other device.
Alternatively, you can simply put everything inside a "root"
Also, if you are not in the same physical space, you do not even need that.
i'm doing quest passthrough so people will scan the room and place the fireplace in their environment. What i'm confused about is when trying to sync player movements, photon will always sync movement in terms of world transform.
Even if i put everything inside a root, not sure photon will follow the hierarchy, it would still sync transform in world space
atleast thats what i think
The documentation of Photon state that it sync the local
As the name suggests, this enables syncing of the transform.localScale value.
https://doc.photonengine.com/fusion/current/manual/sync-components/network-transform#
The component is derived from and can be added to any Unity GameObject to automate synchronization of its Transform position and rotation states,
You should head to their forums/social platform if you struggle with that.
Got it and Thanks! let me try exploring more on this.
How can I get a point that's a specific radius away from another point?
Trying to make an enemy whose main mode of movement is rolling. I want it to roll within a specific distance to the player. I tried just moving the object towards the player and stop at a specific distance (using velocity on a rigidbody), but it always ended up getting too close and becoming stuck because it was moving towards the player, not towards a point that was a specific distance from the player.
origin + direction * distance is a point that's distance away from origin if direction is a normalized direction vector
π thanks
yo so i have this door scirpt, but the problem im having is that the door is coming of its hinges, does anyone know how to make it like stay on the hinges?
Im not sure if this is the right channel to ask this question, but I am helping develop a CAD software for a specific robotics program and we are in the process of adding chains that connect gears together. We are trying to have a system that works by clicking a button and then selecting two gears and a chain automatically generates around the two. Ive recently found a asset that helps alot with the generation of chains on a path and that is the "Splines". The problem im having is i dont know how to automatically generate the spline in the right place on the gears and im not sure if its even possible. I have a picture below of an example that i manually created the points for it to rotate around. To restate the question, how can i have this type of spline generate in a loop around any two gears that i select with the press of a button.
https://docs.unity3d.com/ScriptReference/Selection.html
You need to use this API
Also, you probably should make some EditorGUI to help facilitate this process and organize it
If you need to do it in-game that's harder cause you probably need to build/import your own editor
You will not be able to rotate the chain around the object from a transform given that the shape is not circular.
You have multiple alternative you could look into that I can think at the moment:
- Using skinned mesh
- Dividing in small section each individual piece of the chain and animating that
- Dividing in two part. Circular and linear.
- Using shader to displace the chain
(In theory, you only have to make a small movement loopable movement to be able to rotate)
@halcyon cloak No collab posts here
If there a channel for that
I have been thinking and want to understand how to properly build the logic with Zenject. I may have MonoBehaviour components, but I think it's not just about using two interfaces and "cluttering" the container with dependencies that always need to be injected into MonoBehaviour through a custom constructor method.In general, I am thinking of starting to create objects from prefabs at the moment of initialization/dynamically. Here, I don't fully understand the correct approach. Yes, there should be a service that handles configuration delivery, and a factory (here, I don't want to use a Placeholder because I think it will require a lot of injections and writing code, which isn't a problem).Suppose I have a player who will have scripts like PlayerSpawnPoint, IPlayer, PlayerProxy (can it be used to hide the implementation? Here, too, I don't understand if it's necessary to use an interface for the factory and proxy implementation - I think not). Some kind of PlayerBehaviour and so on will also be needed, and everything should be covered by a facade.It's interesting to create the player at the level of GameObjectContext, that is, through PlayerInstaller or not.
My main problem is that I don't fully see the application architecture. Of course, many implementations are possible, but I want to finally try dynamically creating objects, attaching components, using an asset provider, and developing smoothly. I sincerely ask for advice, as I'm still far from being a Unity expert.
Zenject only makes sense for very large teams for long lived live services. Itβs a terrible burden on your process if you are a small team and people on the team donβt fully grok automated dependency injection. Zenject does allow you to do all sorts of stupid hacks and does in no way guarantee a sustainable architecture. Mind also that DI containers are really bad at handling dynamic scopes. The pattern is at its best when all factories and scopes can be defined statically on startup.
I don't work, sorry. I'm learning Unity, that's my current situation. Can you give me some advice? Preferably, write a bit more in detail. I'm not insisting, just asking as a Unity developer to another Unity developer.
hmm, ok interesting
Donβt use DI containers in unity would be my advice
how to learn if... :))
There is a very simple DI example in https://unity.huh.how/references
And that one is ok. But anything more is pretty garbage in Unity
if you must use one, use VContainer
Well, they don't differ much as far as I know when it comes to proper dependency injection, just smaller memory allocation. Am I wrong?
They differ quite a bit honestly
In terms of usage and set up
proper Unity architecture cannot be learned by reading, you need to shoot yourself in the foot 1000 times to actually learn what works and what all the theory you read about means.
Zenject allows you to do stupid things, VContainer doesnβt (or at least it doesnβt help you doing it)
I bet you everyone who works in a zenject project thatβs older than a year hates life
itβs one of those techs, that once an org adopts them, it gets taken hostage and starts an unhealthy dependence on it, unable to move past it, despite all the health hazards, stuck.
jira being another example
I've been working in a small team (~4) on a project using Zenject that was released over 4 years ago and still gets occasional updates. I don't hate life π
But we never went all in. Never use factories. Don't have any deep unit testing capabilities, just surface level stuff. We mostly use it instead of singletons and to enable some patterns that would otherwise be difficult.
What problem to you want to learn to solve that lead you to zenject?
So you probably mostly used it as a fancy service locator?
Mostly. We use the subcontainer scopes a bunch (project > scene > game object), to easily get references between scripts under the same game object hierarchy. We also use Convention Based Bindings a lot: Container.Bind<IFoo>().To(x => x.AllNonAbstractClasses().DerivingFrom<IFoo>()), to implement some things by just defining a new class.
For example, we have a simple save data system that uses that. If you want to save some data somewhere, all you have to do is define a class:
public class LevelSaveData : SaveData
{
public int LevelsUnlocked;
}
and inject it where ever you want to access it:
[Inject]
private LevelSaveData _levelSaveData;
private void OnLevelComplete()
{
_levelSaveData.LevelsUnlocked++;
}
A save manager class injects all the SaveData and manages the serialization and deserialization.
Not sure if a service locator will allow these sorts of use cases. Or if VContainer has something similar.
as far as I can recall this should be possible in VContainer too. Seems reasonable usage. Iβd still prefer the non-magic (manual) way of it though. My gripe with automatic DI is that it makes certain messaging patterns too easy which in the end produce the same global access & coupling problems as singletons, just with more interfaces to hide behind.
The average dev will just [inject] what they need an never stop for a second to think about the message flow & coupling or where stuff should be routed, whether a new system is needed to handle a case etc. So you end up with ravioli connected by invisible spaghetti and many bugs that were once discovered by static code analysis become runtime bugs.
True. I would not trust a junior dev to add new bindings, but that's why we have pull requests.
i'm currently trying to find an architecture/patterns where juniors feel empowered to contribute at a systems level
This is really an issue I'm struggle with as well. There is a lot of fancy architecture but they usually are complex for unexperimented developer.
How can I interpolate an object that isn't a RigidBody or a CharacterController
that's a really vague question. It depends on the specific circumstances
generally "interpolation" just means "move a little bit each frame until you reach your destination"
It's also not really an advanced question
So I'm writing a custom thing for movement because RigidBodies and CharacterControllers don't have what I want, and right now I'm manually changing transform.position of the object in FixedUpdate, but I have a camera set to follow the player, and that uses LateUpdate, and there's a lot of jitter because of it
If you want I can put the script I made in a pastebin
right now I'm manually changing transform.position of the object in FixedUpdate
This is a problem
if the object is moving in FixedUpdate there will always be jitter unless you do your own interpolation, yeah
I mean generally if you're not using physics, you would just move your object in Update
I mean I am checking for collisions and stuff still, I'm just doing it manually
I got interpolation working :3
I'm storing the old and new positions, as well as the current Time.time, and then using the amount elapsed since that to lerp between the old and new positions
Is there a way to have async methods as listeners for UnityEvents? If I make my method async I can no longer select it in the inspector, and the way it is right now it doesn't work sometimes:
you can use UniTask to do that in a "clean" way by turning them into observables/enumerables.
make a regular method that calls the async method
async event handlers are however a somewhat problematic idea producing all sorts of race conditons and overall debugging hell (thats already bad due to (unity)-event usage)
That should work just fine, hover over the green underline, it's not an error but a suggestion.
It's probably one telling you to do _ = UpdatePlayerName(input); for clarity.
Trying to write a behaviour tree using muse. I want enemy to move towards player if enemy is within a distance of 20 units but do something else if the enemy is outside of that distance.
Currently, the "Move the Rigidbody" action (custom) will cause it to stay in the true branch even if it becomes false because the action is always running.
I tried adding an "Abort if" node but it caused the "Move the Rigidbody" to never run
This is how I had that setup
I also tried without the inverter just to make sure
Can I see your script?
Seems pretty simple:
if (playerDistance > 20)
{
moveToPlayer();
}
else
{
// Do something else.
}
it's not a script, it's a behaviour tree.
Oh I thought that was a planning graph. Here may not be the best place to look.
To be specific, it's a question for #1202574086115557446
Is there a way to reset an AnimatorControllerPlayable through code just like how an Animator behaves when the GameObject it's attached to gets deactivated and reactivated again (restart from entry node)?
Good morning / afternoon/ evening depending on where you are from!
I am looking for some pointers in the right direction on how to set an external display (display 2 for simplicity) and be able to change it's resolution at runtime. I already have a list of resolutions that I can set but when I change the resolution from the dropdown only display 1 is responding and changing:
Any settings I'm overlooking for the additional displays?
launch arguments etc
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.
hi. anyone knows why the _qrcodeImage 's image isn't being updated in the UIToolkit?
its populated by _qrcodeImage = this.Q<Image>("qrcode-image");
and in the debugger I can see the image property is fully set.
for the record, this works in the webgl build, but not in the editor
do I have to call a specific function to force-update it?
can I view the texture in the uitoolkit debugger? to ensure it's not being hidden by an overlay
you can try calling
MarkDirtyRepaint();
didn't work
is there really no way to debug the image at runtime?
(also for the record, the arcode is a valid link and I tested it in other qrcode makers, it works. so the issue here is regarding UITK, not the qr-code)
Looking at my UITK Image code, I do not use the image variable. I create a Sprite from the texture and set the sprite variable
ah, also regarding [your previous suggestion](#archived-code-advanced message), I realized since the script is in a package, my changes didn't work. so maybe MarkDirtyRepaint would work
i'll try that in a editable package
alright, MarkDirtyRepaint didn't work.
so, apparently its the qr-code generator. sorry for the misslead
so, right, the qr code generator was compressing the texture, and I don't know why but this was messing it up, probably because of my compression settings (ASTC)
or rather, this was the author's issue. according to here the compression must occur after applying textures
On line 13 is it intentional that you started the loop at 1?
Anyone here familiar with the CullingGroup API? I'm having trouble understanding how it works based on the Unity documentation for it.
im a bit lost on the difference between these functions:
Graphics.RenderMesh which says RenderMesh submits the Mesh for rendering, which means it does not render the Mesh immediately. Unity renders the Mesh as part of normal rendering process. If you want to render a mesh immediately, use Graphics.DrawMeshNow.
why / when would you want to opt to draw immediately? Also how does the render mesh function differ to Graphics.DrawMesh
If you want to render meshes to be drawn by cameras in the scene, you should use the non-immediate methods. These can be called from any point during the frame, such as Update, as it will just get queued and rendered later.
But if I want to render a mesh immediately, such as when performing your own rendering without using Unity cameras, you need to use immediate methods like Graphics.DrawMeshNow or those found in CommandBuffer.
not sure why you would want to render without using a camera? also why is there a Draw and a Render mesh function being non immediate
how does unity differentiate between Draw and Render
The Draw methods are older, the Render meshes are newer. They both do the same things, just with slightly different parameters.
ah okay
weird they have both but neither were marked deprecated
unnecessary confusion by unity π
Sometimes you don't need a whole camera. Maybe you just want to render one mesh onto a render texture. Instead of creating a temporary camera and messing around with layer masks, you can simply do this:
Graphics.SetRenderTarget(myRenderTexture);
GL.PushMatrix();
GL.LoadProjectionMatrix(myCameraMatrix);
Graphics.DrawMeshNow(...);
GL.PopMatrix();
ah i see
But this is a very direct method of rendering, which bypasses Unity's lighting and other rendering systems.
I'd like to bounce ideas regarding speed vs code readability.
I have this AI checking for friends and foes in vicinity and was briefly tempted to do bitwise test for team check, but it seems that physics is so expensive anyway that i might keep the list.Contains.
teams are held in scriptable objects and team-wide affinity is a reference to other team SO, when team A attacks team C, team C SO gets updated and all of team C counter attack.
what do you guys think, by eperience.
I'd look into how u could speed up those physics checks rather than worry about a list as this is probably only comparing a few elements. If you think the bitwise solution would be readable to your future self (assuming solo project) then I'd see no issue with it though dont really think its needed
what methods can i use to make setpixels() and apply() faster on very large textures?
Focus on optimizing the code in places you think it will matter. Make optimizations in other places after seeing it actually has a bad impact on the performance. Optimizing the right segment of the code will usually give you much more than optimizing random code fragments.
I change this around to start from 0 or from 1, works on display 0 which is the main screen. Just doesn't work for the secondary screen
I'm instantiating a GameObject from a prefab and GetComponent<>() returns null when trying to access any other script attached to the game object prefab. What gives?
ive been having an issue for about 3 days asking in the #π»βcode-beginner channel and i am continously getting an issue saying that c# dev kit is targeting the wrong program format x86 instead of x64
thats the error code
Install the 64x netsdk? https://dotnet.microsoft.com/en-us/download
Free downloads for building and running .NET apps on Linux, macOS, and Windows. Runtimes, SDKs, and developer packs for .NET Framework, .NET, and ASP.NET.
is there a limit as in how much things you can save to the appdata folder?
we have a game what only can crash when the appdata save folder is clean?
As long as there's disk space
There is a limit on individual file size and that depends on your disk format and OS but it is unlikely you are hitting that
it is possible that something like OneDrive or Dropbox is causing your problem
aa thx steve!
so i found a bug in my code where i subscribe 2 times on a event += in the on enable and on disable
the strange thing is the bug happens most of the time for the players who playing it the first time what happen when you 2 times subscribe += to a event
it executes twice when you invoke it
that is not a memory leak, they are completely different beasts
If you never unsubscribe, those instances never get GC'd though
So technically if you do it a lot you might run out of memory
No idea what that sentence means
so i have this error how do you clear the profiller memory ?
Probably with the Clear button
Any articulation body wizards that could take a peek? (thread in code-general)
https://discord.com/channels/489222168727519232/1265591984698163271
TLDR: Instantiating prefabs with arti bodies in them do funky stuff π€
yes ive downloaded that i think ihave the right sdk installed the dev kit js isnt using the right one but i could be wrong
How do I get a shader to render on top of everything?
render it last, turn off depth testing for it, I guess π€·ββοΈ
Is it a bad practice to store all logic about players in one class? I currently have two classes for each player: One being for the player state machine and one for the player physics. These classes are highly dependent on each other. What I was thinking is because they exchange data so much is to merge them into one class, but I fear that would defy conventions. If they were both in one class it would defy the βsingle useβ convention of SOLID.
if both of them know about each other - that's not good, but if only one knows about the other - that's fine (usually)
Kinda. PlayerHandler feeds all the parameters that PlayerPhysics needs to know. PlayerPhysics is required an intake of parameters but not from PlayerHandler specifically
this seems fine
is it annoying to work with for some reason?
if not, I'd probably leave it as is... if yes - then I'd try to resolve the annoyance in some way other than merging these
Kinda. Mainly because PlayerHandler has a parameter called CharacterData, which represents the character the player is playing as. Different characters have different collision boxes and falls speeds which are needed by the PlayerPhysics class. What I currently do is feed those variables to them and assign them as fields within the PlayerPhysics when PlayerHandler starts running.
mm... to be fair though - the S in SOLID is also overrated... I use an extended version of it called "less than five responsibilities principle" π
What would you suggest?
does that need to be part of the PlayerHandler in the first place?
Does PlayerPhysics?
I mean, from what I understand those are params needed by the PPhysics class... can't you just put them there and set them there?
although, injecting params is generally not unreasonable π€·ββοΈ
CharacterData holds things needed by the PlayerHandler as well. Such the moves a character can preform.
yeah... well then just inject the physics part into the physics one as you do (it could be one struct with the data, so that you won't need to do multiple assignments and can add more data later on, etc.) π€
without seeing the code, it seems fine.. (am a bit lazy right now to read code and think hard though, but someone else might feel like it)
Perhaps. Though if I merge them I could do something like:
Rect CollisionBox => myCharacterData.CollisionBoxData;
That way I donβt have to keep them as parameters. Though if you said merging is fine, I might just do that.
the separation sounds reasonable, tbh, so I'd prefer to keep it... but if you don't mind the potential issue that you may need to separate them again in the future, because something else needs to control the physics thing - then it's not the end of the world
usually it goes the other way around... you start with a merged thing (because it's simpler) until you have a reason to split it... technically split gives you more flexibility
so im generating a mesh asset, i save it as a subasset to my scriptable object and i assigned it to the field in my scriptable object yet in the inspector i get type mismatch (see image)
the asset file is valid though... when i double click the type mismatch box it loads the mesh inspector and sure enough its correctly showing a mesh so why is it a type mismatch?
this is how im loading it to the field in OnValidate
var path = AssetDatabase.GetAssetPath(this);
var subAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(path);
foreach (var subAsset in subAssets)
{
if (subAsset is Mesh mesh && mesh.name == "Plane Mesh")
{
_planeMesh = mesh;
return;
}
}
I have found very little information on this specific issue related to vs code and unity. Whenever I launch vs code with the default console template opened it loads for a second and gives me this error. I know I have the latest version of the .NET SDK installed as x64 and I have no idea how to change what the c# dev kit is targeting. I have tried uninstalling the SDK, vs code, and all of the extensions within vs code. I have also tried editing my system environment variables and changing the path settings. I have truly no idea what to do and have been stuck on this issue for days. any help is much appreciated!
You need both the vs extension and the vs code extension
Get the unity vs code extension, then in your unity settings set you IDE to vs code
My units are forgetting which healthSystem it has created an instance of during setup. Why is this occuring?
It is not possible for a class reference to suddenly become null. So that leaves two possibilities: Something is setting the field to null, or the field isn't assigned before Damage is called.
The first one is easy to check since it's a private field, so only this class can assign it. If you're not assigning it to null anywhere, that only leaves the second possibility.
I am not sure what you mean by the field not being set. The totalDamage variable is not null on Debug. But healthSystem is null on Debug
totalDamage is the parameter, healthSystem is the field. Field not being set means it's null.
healthSystem is a class. A field is a variable stored on class
HealthSystem is a class. healthSystem is a field of the type HealthSystem.
This is not a #archived-code-advanced topic.
ah i see what you mean
i dont think its either of those issues then. Like you said, nothing should be able to set the field to null since its private. And the field is definitely assigned before Damage is called since the target units are in the scene from the very start and initializes healthSystem on Start()
Start is called just before the first Update is called. It's possible for the unit to be spawned and immediately get damaged before its first Update, and therefore its Start, is called.
Or if the script is disabled, Start won't be called, but it can still be collided with and Damage can still be called on it.
i already have that set its not the issue
Ah darn. My personal issue was solved because I only had the visual studio code package and not the visual studio package, so I assumed that was this issue.
If I perform some kind of function a few thousand times is it better if variables are declared outside of it?
float b;
void A()
{
b *= b;
}
I'm thinking that would free up the garbage collector as the function is reused
none of that will affect the GC, it is all on the stack
but it would be damn silly if b were a local variable
I just need a temporary vector3 for something inside the function and was wondering
as long as you are not new{} ing it then, yes declaring outside the method is better
Are you sure of that ? Pretty sure local variable are basically free and it might even be better given that they would be closer.
In any case, it would probably not even be perceptible
I'm not really an expert, but here is the difference between:
public float M(float a) {
return a*a;
}
and
float a;
public void M() {
a*=a;
}
https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyDMABGgQMIEDeOB1BAZhAPYCGwBTA3FTfkQCwEBZABQBKClxo0mAKgC8HCQQC+OJUA===
https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyDMABGgQMIEDeOB1RhAZhAPYCGwBAsgBQMtvMCUFKjRHIA7AWYAqZgG5h1AL45FQA
It's not a performance question so much as a "this does a completely different thing" question
if the variable isn't needed outside the funciton it should be declared inside the function. Always give the most local scope possible
I know but this function needs to have really good performance
Local variables are almost certainly better for performance too
due to memory locality right on the stack
but - why don't you benchmark it?
I tried to but fps doesn't change and I can't check the memory usage because it's constantly rising for some reason
talking about benchmarking the function not the game as a whole
I don't know how to do that
Use benchmark.net or just simply run each function 100,000 times and record how long it took
So in the unity play mode(not build), there isnt really a way to create a new screen dimension setting and set to it all from a C# script, right?
Do you mean game window? There was a thread about it with solutions, but I'm not sure if it still works.
https://discussions.unity.com/t/add-game-view-resolution-programatically-old-solution-doesnt-work/783954/3
oooo this looks perfect!! thanks!!
I ended up getting it fixed thank you for trying to help though!
does anybody know some resources that talk about procedurally animated spiders? I have a working procedurally animated spider but it gets messed up when i try to make it walk on surfaces with steep slopes.
I think I need to cast some horizontal rays to check for obstacles in front since I'm only casting downwards rays from above every foot but I'm not sure what to do
Thi is the current version
tbh i watched this whole video and don't see any issues
Other than the fact that the body stays at the same height all the time. It would be a bit more realistic if the body adjusted according to the leg heights
right so - the body isn't adjusting at all
that's a problem
it will need to follow
Also "raycasting straight down" isn't going to cut it for a spider which can walk straight up vertical walls and even upside-down
when i rotate the body and move it, legs at the back just go limp
instead of raycasting straight down
should i raycast down with respect to the body rotation
definitely, something like that
Hello
What RenderParams should I use for Graphics.RenderPrimitives(rp, MeshTopology.Lines, (...))?
the example is for MeshTopology.Triangles
Probably the same params..?π€
I don't thing there's a difference in params depending on the topology.
Well I have no triangles, just edges to draw
I'm searching for a way to draw a debug wireframe in ECS
given list of edges
hey so i need help making a game, im struggling to put my ideas into it and need help, i know it kinda seems a little jumpy but i could really use the help.
I may get the triangles but thought it's possible just with edge list
I don't think that's enough for the GPU. Pretty sure it needs the triangles regardless of the topology.
okay, thanks
Is that really and advanced code issue?
good point, didnt see the other chats at first
I have methods with default input values. i am using a delegate to use these methods but right now its giving me an error because there is nothing within the delegate parameter. How do I specify that the delegate should use default value?
Your delegate needs to match the expected delegate type of course
Not sure what you mean by default value
Show code?
my gun method has a default input of int damage = 15. I can create an action delegate that takes int called attack but I am not sure how to specify to take the default input: private Action<int> attack;
You make another function/delegate that calls your method
Show your code if you want specifics
You can define default values in the delegate. But it sounds like you want to be able to use the default values of the method, without knowing which method you're calling because you're invoking it through a delegate. This is not possible.
You can do this:
public delegate void AttackAction(int damage = 15);
private void Invoke(AttackAction attackAction)
{
attackAction(); // passes the default 15 damage.
}
But the default will always be 15. It doesn't matter what the defaults are for the actual method assigned to the delegate, or if there are any defaults at all.
that is actually the exact case I am facing. I am just running the methods directly now instead of the delegates. should be okay
thank you both!
Hey everyone! I'm trying to set up a flag football game where flag pulling is the base of the game. The offensive player has to avoid the defensive player and score while the defensive player has to pull the flag to win
The defensive player is controller by Ai and has a navmeshagent and also the football field has Navmesh
Currently the way i have it set up, the ai is supposed to go towards the offensive player to "pull its flag" but the ai stops each time i move my player and then moves once my player is stationary
Here's my code for the ai
Im using Unity and VS 2022
<@&502884371011731486> Spam
!warn 972587276972462171 don't spam random crap here. There is no off-topic.
jamafr has been warned.
What debugging steps have you taken?
Did anyone make a weapons system with scriptableObjects, that hold both the game assets and the logic to spawn, fire them?
Itβs probably a well used/represented solution, that is why I am wondering what caveats/issues/etc. were encountered?
I've looked at my navmesh and tried to make adjustments to the settings. I've also looked at my code I pasted and tried different variations
Having logic in ScriptableObjects works pretty nicely for me. The inconvenient thing is that you must pass the source(s) and/or target(s) as arguments, but it's a good price to pay.
Usually, I have Definition (Weapon, Projectile, Ability, Character, etc.) for many things which have their Instantiate function. I have no particular issue.
if (IntersectCirclePolygon(closestPoint, radius, polygonVertices, out circlePolygonNormal,
out circlePolygonDepth))
{
if (circlePolygonDepth < depth)
{
normal = circlePolygonNormal;
depth = circlePolygonDepth;
return true;
}
}
if (IntersectCirclePolygon(capsuleA, radius, polygonVertices, out circlePolygonNormal,
out circlePolygonDepth))
{
if (circlePolygonDepth < depth)
{
normal = circlePolygonNormal;
depth = circlePolygonDepth;
return true;
}
}
if (IntersectCirclePolygon(capsuleB, radius, polygonVertices, out circlePolygonNormal,
out circlePolygonDepth))
{
if (circlePolygonDepth < depth)
{
normal = circlePolygonNormal;
depth = circlePolygonDepth;
return true;
}
}
I've got an issue with my capsule. my current order is checking the closest point, then the top, then the bottom.
but sometimes the capsule will phase through walls. is my order wrong?
scriptable objects are globally accessible instances of classes, and all downsides of that exist with them. If you are disciplined and don't abuse or misuse their nature, they are fine. If you put pure functions on them that don't mutate some internal state or produce side-effects, maybe configured by immutable serialized properties on them, thats all fine.
Do you have any tips I can use?
standard debugging techniques - logs, attaching the debugger. Make sure the code is running when you expect it to run and with the data you expect.
does any one know how to update unity navmesh in runtime in specific areas i really don't understand the api at all and theres few example codes provided
i just want to update the navmesh after adding more meshes to the scene but its a bit complicated
You can block access in certain areas by using NavMeshObstacle:
https://docs.unity3d.com/ScriptReference/AI.NavMeshObstacle.html
i cant use that
i need to rebake the navmesh in an area when i add more geometry to the scene - navmesh obstacle only allows two basic shapes which is totally useless
im trying to use this https://docs.unity3d.com/ScriptReference/AI.NavMeshBuilder.UpdateNavMeshDataAsync.html
its not really obvious to me if when updating via the bounds it will wipe out the areas outside of the bounds or not so it becomes a bit unclear if im using the right thing
Sounds easy to test though
i did i tried this:
private void OnEnable()
{
_collider = GetComponent<MeshCollider>();
_worldBounds = _collider.bounds;
var center = _surface.transform.TransformPoint(_worldBounds.center);
_localBounds = new(_worldBounds.center, _worldBounds.size);
var sources = new List<NavMeshBuildSource>();
NavMeshBuilder.CollectSources(_worldBounds, NavMesh.AllAreas, _geometrySources, 0, new(0), sources);
var handle = NavMeshBuilder.UpdateNavMeshDataAsync(_surface.navMeshData, _surface.GetBuildSettings(), sources, _worldBounds);
handle.completed += OnComplete;
}
private void OnComplete(AsyncOperation operation)
{
if (operation.isDone)
Debug.Log("NavMesh update completed successfully.");
else
Debug.LogError("NavMesh update failed.");
}
but this does not do what you would think it does
this is the visual of the navmesh + the bounds area i want to update
but when i run it i get this:
makes no sense to me
MeshCollider bounds are already worldspace so your TransformPoint line makes no sense
you want the inverse if you want center to be in _surface's local space
i finally got it working
i can now use abstrast polygon shapes as navmesh obstacles
took forever to figure it out
checking the capsule's endpoints firs and then the closest point might give you better results because endpoints are often more critical for collision detection. also instead of returning early when collision is detected have you tried to loop over all the points you need to check for collisions and then gather the results and keep track of the smallest penetration depth so you can then return whether any collsion was detected along with the best normal and depth values.
I must be misunderstanding how RenderTextures work. I'm trying to render two different textures, one that goes to the screen, the other to be used for a graphical effect. I created a secondary camera + render texture and set the target buffers of said camera to the rendertexture, I then set a texture in my compute shader to the render texture. After the the scene renders, when I then read the data of each pixel out to a dummy array just to verify what data is in it, all the values are blank (they should not be). When I open the frame debugger, I can confirm that rendering of the scene is occurring, but it doesn't seem to be writing to the RenderTexture. I feel like I must be missing some fundamental step, anybody know?
In the frame debugger, the steps that draw the secondary texture state the target buffer as a temp buffer, but I don't know if that's unusual.
Whats wrong. I have a camera and will calculate the right upper point dinstance from pivot. With the height all is okay but width is wrong
You are multiplying it by 2 just to divide it by 2?
2x/2 = x
(2 * x * y) / 2 = xy
Unl;ear what you're trying to calculate here
is this a perspective camera or orthographic?
its a perspective
i try to calculate the half distance from the cameraposition vector to the roght or left end of the view
but this code seems to only be dealing in angles
so what do you mean by distance
also for a perspective camera distance between parts of the camera view depends also on the depth that you're looking at
the calculation what i postet works in 2d. i dev it for thois . but now i convert to 3d and there this doesnt work with this formular
Yeah because it makes so sense, you're dealing with angles here
you can't treat an angle as a position
So you have to specify the problem better
based on your screenshot you want the position on that game plane
for this you should use Plane.Raycast
e.g.
Plane p = new Plane(Vector3.up, Vector3.zero); // assuming your plane is flat and at y = 0
Ray r = Camera.main.ViewportPointToRay(new (0, 0));
p.Raycast(r, out float distance);
Vector3 topLeft = r.GetPoint(distance);
r = r = Camera.main.ViewportPointToRay(new (1, 1));
p.Raycast(r, out float distance);
Vector3 bottomRight = r.GetPoint(distance);
camera viewport and from the pivot to the corner the distance
this doesn't explain the 3d space part of it though
that point can be 0 units from the camera or a million units from the camera
and it represents a different position in space depending on where
My example code projects that point to a given Plane in the game world and uses that.
but it depends what you actually want.
yes you have to change your thinking
From what I've read online, if Unity is using the Async Upload Pipeline, I should see specific Profile markers in the profiler (AsyncUploadManager.ScheduleAsyncRead, AsyncReadManager.ReadFile, and Async.DirectTextureLoadBegin). I'm assuming these markers will appear on the Main Thread in the CPU Profiler? Can anyone confirm?
is there a way to rename these sub-assets?
whenever I try editting its name with .name and refreshing the asset list, I get errors in the console
what are we even looking at here? Those look like ScriptableObjeccts so F2 should be able to rename.
Also just saying ' I get errors in the console' is not very helpful. Show the errors
Also, not a code question, please use the correct channels
well it is a code question because I'm trying to rename them with code
they are scriptable objects
but they're sub-assets
the type you create with this code
the error is that it basically loses a reference to the asset once I try renaming it, which doesn't happen with normal scriptableobjects, only the sub ones
I also tried using AssetDatabase.RenameAsset which isn't doing anything at all on the sub-asset
@frozen ravine complete shot in the dark but any chance the so's .name isn't matching it's file name? messed w/ making so's via code but not subasset stuff
well it works with my other scriptable objects, it just doesn't work with that one
Unity's just weird about sub-assets, you can't even rename them in the inspector manually (which is why I'm trying to figure out how to do it with code)
Can you rename them in the project view?
no, this is the project view
I can rename everything else just fine
as far as I know, in the project view, not being able to rename them is just an oversight, but I figured there would be a way to rename them via scripting
If you click on the asset's name, wait half a second, and click again, does it let you rename it?
Unity is weird about exposing renaming
I suspect this may be a design flaw in Unity, probably related to meta data
no, I also can't F2 it
zamn
Certified Unity moment
that really sucks lol, because the sub-assets are really good for organization
if you cannot f2 rename then that is actively blocked by code so the chances are you just cannot rename
true
very odd behaviour, normally Unity does not care about names at all
There has to be a better way of doing this in ECS right? If so let me know, the goal is to make the workers do two seperate tasks repeately after each other. This "works" but seems like a slow way of doing so
also, is there a way to trigger code via an event / pruning rather than just boolean locking with ECS?
if you're looking for an event, you won't find it (unless you give up on burst-compatibility for every code using that system/component). but you can make it easier for yourself by creating generalized data types that at least make it consistent across your application. example:
public struct Event<T> where T : unmanaged
{
private T? _args;
/// <summary>
/// Gets the event arguments if the event is valid. Also consumes the event.
/// </summary>
/// <param name="args">Arguments of the event</param>
/// <returns><c>true</c> if the event is valid.</returns>
public bool TryGetArgs(out T? args)
{
args = _args;
_args = null;
return _args.HasValue;
}
public void Invoke(T args) => _args = args;
}
invoking the event:
spawner.spawnWorker.Invoke(...)
using the event (it also consumes it, but you get the idea. change it to accept IDs if you want proper subscription system in it) :
if (spawner.spawnWorker.TryGetArgs(out var args))
{
// use args...
}
Might wanna ask in #1062393052863414313 next time
I watched Codeerβs video on how to make a procedural animation. I need a bit of help with the second step of the video, which involves anchoring the bottom of the leg to the ground.
I have a mysterious object that came from a wacky json object... most of the times I can convert it with:
(T)Convert.ChangeType(mysteriousObject, typeof(T), CultureInfo.InvariantCulture)
however, if the object is something that looks like a list, that fails.
my workarround is to reserialize it and parse it back in the correct type π
string json = JsonConvert.SerializeObject(mysteriousObject);
T value = JsonConvert.DeserializeObject<T>(json);
But this feels really hacky π
What is the correct C# syntax for this kind of crazy cast?
(note, just casting (T)mysteriousObject fails)
that came from a wacky json object
Can you elaborate on this? What does the json look like and how are you parsing it?
the json is being parsed as Dictionary<string, Dictionary<string, object>> it's a two key deep json object that can have pretty much anything on the last level
the problem in question is an array of bool
well.. that's why it's coming in as an object of course
but when I asked the question I wanted to know things like which Json library you're using and what the actual code was being used to parse it
Sounds like you're using Json.NET and JsonConvert. For a structure like this you could consider using the JObject API instead of JsonConvert
That will give you a lot more control here
but a lot of this depends heavily on where the JSON is coming from in the first place and why it has that format
there's probably a better/cleaner way with less ambiguity
There are settings to control the amount of type information, if that's the problem you are running into
I will investigate the JObject π€
The json should always come from another c# serializer... but I am not entirely sure π
right assuming JsonConvert is being used to serialize in the first place. But JSON.Net's type information strategies don't all conform to the actual JSON standard π
thanks a lot!!! JObject (and the entire family of J* thingies) worked perfectly and are WAY easier than typeguessing in a C# dictionary π₯Ή
Awesome glad to hear!
If this wasn't Unity Json.NET also supports dynamic which would probably be good for your use case but Unity IL2CPP doesn't support it!
you're not even looking at the correct line
The error says line 71
do i delete this
Send a snippet of a few lines before and a few lines after
Yeah delete what's on line 71.
