#archived-code-general
1 messages · Page 375 of 1
'Fragment Normal Space'
now its no longer gray
but it doesn't look fixed either
ah yeah I was about to post that
Like this, just put the corners on top of each other. Each corner needs 3 vertices with different normals, otherwise the normals will look like in the second picture and end up interpolating into a smooth edges which doesn't seem to be what you were looking for
Funnily enough, I'm actually fixing this exact issue right now with my own voxel renderer.
Hopefully at least.
..I thought you two were the same person for a good like 5 minutes
lmao
i don't want hard edges, i just don't want it to tile like it is rn
You don't?
Are you using mesh.RecalculateNormals(); after Mesh generation?
what do you mean by tile in this case?
because your screenshot looks the way it does presumably because each voxel is a cube with 8 vertices, sharing normals in the corner, which leads to the rounded shading you're seeing on every voxel
if you look at the original image i sent, each cube has the normals that the whole object should have, they all behave identically instead of as an offset block
right, that's because of what I just wrote above c:
They mean that the lighting is dark in places that it shouldn't be dark
No no. I believe they just aren't setting the normals which would cause issues similar to that.
yeah that's what I wrote lol
The way my voxels were initially rendering is what griff is trying to get, and what I'm trying to get the opposite of.
i'm setting identical normals for each cube, hence the problem
Just, don't set normals when generating the vertices
also are you culling faces that are obstructed by other voxels?
well, that depends on how you want to shade it, you'll have to supply normals one way or another
After mesh generation is complete, do mesh.RecalculateNormals();
and doing in in the vertex data is one way, and doing it in a shader is another way
nope, not yet, i have a really basic script rn
that is with recalculatenormals
right, this would generate normals as well yeah, but would also be slower than doing it manually, but it also depends on whether vertices are merged and if internal faces are deleted. it only works if the mesh is topologically sound
I do all of that so it makes sense that it would work for me
I believe it doesn't work for griff because they do not cull faces.
yeah
It should fix itself when you cull faces, however the voxels would look off unless they were far away from the camera so I recommend a different approach
is there an algorithm other than marching cubes that you'd recommend for culling internals?
it'd kinda just be a neighbor check
if two adjacent voxels are solid -> don't create a face between them
^ That's basically what my approach is.
does it not accumulate tiles?
What do you mean by that?
marching cubes is a more specialized tool to discretize volumetric data, but your data is already discrete, there's no need to use marching cubes
idrk, nobody online has explained marching cubes decently that i've seen, not sure how the algorithm works
marching cubes is a way to generate a polygonal surface from a description of arbitrary solid volumetric shapes
Its basically a method to make a smooth surface from voxel data.
As far as I can tell
ah so nothing like what i want lol
In this coding adventure I try to understand marching cubes, and then use it to construct an endless underwater world.
If you'd like to support this channel, please consider becoming a patron here:
https://www.patreon.com/SebastianLague
Project files:
https://github.com/SebLague/Marching-Cubes
Learning resources:
http://paulbourke.net/geometr...
no it's the opposite c:
it's a way to make a discrete polygonal surface from smooth volume data
Really?
like, say, turning a sphere volume into a mesh surface, you can use marching cubes for that
or surface nets, is another similar technique
(I suppose the volume data doesn't have to be smooth but yeah same same. straight lines are called curves in math so what are words even)
Did someone know here something about motion blur (post processing)
Yeah but no-one is writing there
love sebastian, but didn't watch the vid because the final product looks entirely different, figured that there was some special cube way of doing it
Yes, it samples a float value and only displays "edges" (very simplified) when reaching certain breakpoints, making a smooth surface polygonal
The missconception that it makes voxel -> smooth comes from the fact that you can also feed it with less detailed data and still get a result (and that its used by many to do this exact task)
his cave generation stuff has a 2d version of it if you are looking for that
not sure what exactly you need
Still have no idea how to calculate normals in the fragment shader. None of the methods I'm finding online work on Unity.
anyway if you want to make a voxel/minecraft style world, you won't need marching cubes
doing purely cubes, so it doesnt seem applicable
I think the issue is that your SG shader might not be lit
try making it from the lit SG template
you can convert cubes to the marching cube surface style
It is lit.
i want them to stay as cubes lol, i just want the normals to not be broken
Ohh yeah then you dont need marching cubes 😄
are you using the same vertex for two surfaces of the same cube? like one looking up and one looking left?
oh, swap ddy and ddx. normalize(cross(ddy(p),ddx(p))) works for me
looks like its sharing the vertex and that breaks the normal of it
8 vertices for the cube
4 per side
wait is there a difference if I swap them
otherwise you break normals
i'll try the 24 vertices, but that seems like itd be really slow
yeah, the cross product is anticommutative
(unlike the dot product where order doesn't matter, bc it's commutative)
bruh it works now
that's pretty much how all cubes in all games are rendered
in that case the normal is the avg of the normal of each tri attached to it if you just recalc normals
griff its not impossible to use 4 vertices per face even if you use only unique vertices
you can still make it look fine
with correct lighting
but that requires a custom shader
which might not be apt depending on your use case
btw there are some issues
that looks like doubled surfaces
that gives the same, i tried that
yeah thats the mistake, not the solution 😄
oof okay I think I know why this happens
What do you mean by that?
I don't think it's doubled
I think the depth only pass in the shader (generated by SG) doesn't respect the custom frag shader normals with ddx/ddy
it might fall back to mesh normals
it looks like two surfaces sharing the exact same position and they are fighting over the renderer (which gets rendered on top)
so do I just make the mesh not have normals
pretty sure it's not z fighting no
normal fighting then
and that pass is used by shadows for lights. try changing the normal bias of the directional light shadow settings in the scene
per mesh technically yes but you can bypass itw ith submeshes
what the fuck
I removed the mesh's normal (so now vertice data is just a position)
4bil with 32bit format
and now its all dots
it's about 65,536 by default when using the 16 bit index format, otherwise way higher yeah
play with the directional light shadow normal bias setting
and see how it behaves in both cases
congrats 😄
neat!
And I also have 2x less vertices than if I don't use unique vertices
since without unique vertices its around 7500 verts
with only unique vertices its less than 4500
so its quite nice
next I'll try to make the greedy meshing algorithm properly
since rn its just slightly better than naive meshing only because I do not have repeating vertices
is this mostly for learning or is there a specific use case/game style in mind?
because often the naive approach can be faster, especially if you expect to edit the mesh frequently
I saw the game 'Clone Drone in the Danger Zone' and wanted to make a similar game. It's basically a robot fighting game where the robots are destructible.
I checked the game code and they use a deprecated Unity asset called 'PicaVoxel' so I'm making my own voxel engine
alright
then I suppose my current approach could be better than greedy meshing since I'll probably update the mesh a lot

that's what I was thinking too
triangles and vertices are very cheap to render
the expensive part is generating them
so you'll want the generation part to be simple
btw I also already have collider generation so now I just have to add destruction and the system is basically already done
and because I expect most voxel objects to be super small, I decided to not use 'chunks' to cut the object into smaller sections as they are unlikely to be super large or anything like that anyway
you can probably speed this up significantly with the job system as well if you need to, without using fancy triangulation algorithms
it's a very parallelizable thing
or do it with compute shaders!
but that can be a lot to learn if you're not familiar with shaders
I can't really use compute shaders anyway because my laptop only supports OpenGL 3.1
It looks like the voxel objects are pretty performant th
I can generate a 20 voxels radius sphere's mesh and collider instantly
and my laptop is shit ass so anyone else is likely to not experience any lag
at a radius of around 40, the vertice count is more than the limit it seems like, tho.
So it probably can't work with any voxels too big anyway due to mesh size limitations
I feel like its pretty small tho
60k triangles and 69k vertices
Without any of the optimizations it should have like 3 times more vertices
with smaller meshes vertices are literally less than triangles
I need a critique for an inventory data representation I made up. I will separate data from prefab, so there will be flaskData and flask prefab. flaskData will inherit from abstract itemData and hold additional properties, like the fluid contained as well as overriding methods, such as getting description to display what it's currently filled with
Does this make sense?
There will be a lot of code repetition though, ideally I'd like to find a way for a component to modify various evens with its data
For example, if we use composition, flask data class might have a fluidContainer field, but I'm not sure how can I make this field modify the string returned by description getter to append what kind of fluid it contains
To answer this you should explain the problem this data model must solve. What is the game-design it needs to support? What current and future constraints need to be considered, how does the data change? Any skill issues in the supporting team? Is tool development effort important, or does it have to use builtin inspectors? Who will configure and design the system, what is their technical expertise? Does it need to be saved/restored and when/how? Does it have to be networked?
How would I use the Job system here? I want to multithread collider and mesh generation.
That is not enough information.
What additional information is required?
UpdateMesh(); updates a list of meshes that is looped through every frame and rendered used Graphics.DrawMesh
UpdateCollider(); deletes a bunch of BoxColliders and generates new ones based on voxel data.
I'm guessing I'll have to generate the BoxCollider boxes on another thread then create the boxcolliders on the main thread, and for the mesh, I'd have to send the meshes to the main thread after all generation is complete, so probably not much changes
Yes, the primary reason I started thinking about it is because I need to replicate it through network and save/load it. It would be much easier to serialize classes than to generate data from gameobjects when a save or network replication is needed
So it is mainly for replication and saving. Potentially it might be used for modding in the future, but this isn't a concern at the moment
Moreover, right now all item data is just a bunch of gameobjects, and sometimes it's a hassle to manage. I think it would be better so separate data from representation anyway
This is true and necessary but you can create/restore data from view state (monobehaviours) on demand which is less difficult than it sounds… it depends on your workflow and how much you want to spend on tooling. A fully separate data model needs custom tools, MonoBehaviours and SOs can take you far without much custom tooling
I'm honestly still debating whether to separate data yet or create it on the fly. On one hand, it's more explicitly of I go with the former, but realistically the latter approach will be easier
neither will be easier
I'm not sure about custom tooling though, I think unity editor handles serializable fields good enough
Your non MonoBehaviours won’t have easy access to configuration UI
And you will do a bunch of work for spawning the views into that data.
Couldn't I use scriptableobjects with a itemData field for this?
The question really is whether your view is much smaller than your world that’s held in the data to an extent that you actually need the separation for that reason alone
say you have a world with 100 planets but you only ever visit one at a time as a player (interactively), here it’s very impractical to not fully separate view and model
I would, average case scenario, need to save up to 1000 entities per player
Not to mention the inventory
From developer perspective it would be easier not to separate anything
But I get what you're saying. I'm gonna reflect on my design a couple more times and try to determine whether I really need the separation
In most cases that don’t make either approach obviously better, you can make either one work.
I might be biased towards separating view and model even if it's not the best solution
For me it changes on each other project 😶
I think it's my time spent in web dev. You learn about importance of model and view separation. Not sure whether it holds up on gamedev though
I've seen a talk made by the developer of Caves of Qud who uses a very similar system — he sends events, such as "get name" addressed to an entity, and the components attached to that entity intercept and modify said even
So "fluid container" intercepts the "get name" event and appends its current contents and amount to payload
Seems very clunky to me, but definitely solves the problem
i am trying the change the rotation on one axis of my first person player when a key is pressed. i change transform.rotation using quaternion.euler(transform.eulerAngles.x, transform.eulerAngles.y, 30f) and changing back the z axis to 0 after a few seconds have passed from the time the key was pressed. it is working as expected but after that when using my mouse to look around the rotation changes for all axes
is there a question there or is this just a general statement?
I think in gamedev the reasons for separating modules/concerns are much more integrated, there is way less abstraction and entirely different abstractions here boost productivity for different reasons. and web’s obsession with MVC does not translate well if applied dogmatically or converted with web concerns in mind, the workflow in games, performance and reasons for change is very different. Only on a theoretical level they do align. But that is usually not helpful. Also depends on the type of game and its scale.
the question is why does the rotation when moving mouse affect all axes after the said rotation takes place
no clue, you haven't even shown us the code lol
{
if (State == MovementState.Sliding)
{
slideTime -= Time.deltaTime;
if (slideTime > 0)
{
player.localRotation = Quaternion.Euler(player.eulerAngles.x, player.eulerAngles.y, 30f);
controller.Move(transform.forward * slideSpeed * Time.deltaTime);
}
else
{
player.localRotation = Quaternion.Euler(player.eulerAngles.x, player.eulerAngles.y, 0f);
State = MovementState.Running;
}
}
}```
hey, sorry for the delay, i pasted the code
The euler angle property is an interpretation of your rotation (quaternion). Expect the value to differ on calls to the euler angle property.
is there an easy solution for storing pairs of values that are unique and order agnostic? e.g. the pair (1, 2) will be treated the same as the pair (2, 1)?
(in c#)
so, what's happening is I have a mouse look script working on the player which only affects the Y axis. Now, I implemented this function to rotate the player on z axis when he slides for 1 second. After the slide completes and I move my mouse, it affects all rotation axes not only Y, this is the issue
Does the orientation of the player actually change or do the values simply differ?
If the values differ but orientation is correct then the euler angle property is simply returning a different interpretation of the quaternion. If the orientation is incorrect and not just the values, then you've got something else modifying your rotation.
during the slide, the behavior and values, both are as expected. after the slide, when I use the mouse to look around, the orientation of the player also changes on all axes and the values also change
What happens after? Is your character, like, flipped upside down?
just override equality check and make a custom struct
how would I go about that first part?
We would need to see the mouse look script if it's related to that
screenshot of before sliding (note : x and z rotation values are 0 and the orientation is okay.
screenshot of after sliding (note : all rotation values are non zero and orientation is weird as well
unable to take screenshot of sliding
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}```
Tangent: remove delta time from get axis calls with mouse
a bit complex but should get you close to what you need
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type
Is the mouse look script on the player body as well? (It shouldn't)
it breaks it, now the mouse is superfast
no now its correct, just lower the sens
Use a scalar to decrease it
no, it's on camera
mouse is already frame-rate independent, you should not use deltaTime
Mouse with get axis already counts as a delta
i removed delta, changed sensitivity, mouse works fine without delta but the previous problem is still there
That was a tangent though. Don't recall if inspector values are with local rotation or world rotation.
I know this isn't efficient or pretty but in broad strokes that's the idea right?
is there some way to lock rotation all other times except when sliding
Unity measures the Position, Rotation and Scale values of a Transform relative to the Transform’s parent. If the Transform has no parent, Unity measures the properties in world space.
https://docs.unity3d.com/Manual/class-Transform.html
I'm pretty sure your rotations aren't being changed but rather the inspector simply shows values relative to your parent.
If there's an unwanted behavior other than just the values in the inspector, maybe use https://docs.unity3d.com/ScriptReference/Transform-localEulerAngles.html
the orientation still changes
I was referring to your other script #archived-code-general message (replied to the wrong post)
yes, i tried changing localEulerAngles of it and it doesn't work, leads to same behaviour
Dunno, I'm not on my workstation right now. Try debugging the euler angle values and local euler angle values to see what your working with
The inspector values likely aren't what you think they are - do not rely on these values.
Local and non local most definitely should not behave the same if there's a parent involved
alright, thank you for your help, i'll try figuring it out
in what way could a disabled script component still be affecting things? i thought disabling it would stop any and all code executions? but somehow it still has an effect on certain things i cant go into detail of
if a diff function calls a function from that disabled script directly, would it go through ?
Of course
absolutely, many things run on a disabled script
Yes
rip
The events are not invoked by the disabled class. You can invoke events from this class in other classes though
Not sure how this would be bad in your case
networking
but the info i got is enough to figure it out, thanks o/ idk why i thought disabling it is enough
its possible but not something we discuss here in regards to decompiling #📖┃code-of-conduct
Hi everyone, we're working on a crowd system for physically interactable crowds, like ragdolls, for a driving game and we've got a, janky first solution involving navmesh agents and rigidbody enabling and disabling. I want to know if any of you could link to articles, videos or even your own experience with simulating crowds and how to do it performantly
not sure if this is the right place to ask but I couldnt find a channel specifically for materials so here goes - is it possible to set a material colour to a gradient between two colours in c# code or do I have to create/assign a new material for that purpose?
can someone help me think through the structure of my stats class? https://paste.ofcode.org/8Tg6Jv2DDcRHeNRhZMBPGE. https://paste.ofcode.org/QB3UyvUk4iSa94ZkyiubPW My game is similar to Path of Exile or Diablo with many stat "increases", "multipliers," etc. Right now it's kind of a mess but it SOMEWHAT works. However, i believe there is a much simpler way to achieve all of this. The main problems im running into are decreasing by a flat amount (ie taking damage) hence why i have a "RawCurrent" aswell as starting with some amount in the case of enemy presets (RawMax). It wouldn't make sense to reduce this amount in "Add" since it would be affected by the multipliers. Another issue is when a player levels up or changes gear while their stats are altered. How could I structure it in a way that preserves current stats (lowered health, mana, debuffs, etc) while easily changing their max stats. thanks!
also, i feel there is a fundamental difference between stats like Health, Mana, Movement Speed since they are based on a "max" amount, while others are just a stat number, say "physical damage." how would I reconcile this?
If the gradient changes over the course of the game, make a shader. Otherwise, create a gradient in a painting software
Where would I request help for a Unity script issue?
the code channels
...which we're in I just realized
Gotcha, thanks
What would do is make a class specifically for StatModifiers. They can be stored in a list recalculated whenever one changed.
well thats not exactly the issue im facing
Thanks! I just put my request for assistance in the #📦┃addressables channel. Would appreciate if anyone familiar with addressables and async could assist me with the inquiry
I might post it here as well…
[HELP WANTED]
Hello, guys! I was wondering if I could get some help with a script. One of my team's coders (now on hiatus) recently converted some functions in our game's AssetFinder script to return an async Task<GameObject>. However, all the other functions that he hasn't touched are expected to recieve a standard GameObject. I'm not sure how to convert it to a normal GameObject, and I would appreciate some assistance, as I've never worked with Addressables or ASync.
NEW FUNCTION EXAMPLE:
{
string[] guids = AssetDatabase.FindAssets("t:Prefab");
foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
var operation = Addressables.InstantiateAsync(path);
GameObject go = await operation.Task;
if (go != null && go.name.Equals(prefabName))
{
Collectable goCollectable = go.GetComponent<Collectable>();
goCollectable.type = goCollectable.itemSO.type;
goCollectable.icon = goCollectable.itemSO.icon;
return go;
}
// Clean up if the prefab doesn't match
Addressables.ReleaseInstance(go);
}
return null;
}```
I need to take the result and turn it to a standard GameObject
!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.
For a dialogue system, should I opt for using constants? i.e static strings bundled in classes by character?
DAVE {
publc static string Line1 = "Hello, I am Dave",
},
JOHNNY {
public static string Johnny01 = "Hello, I am Johnny",
},
``` etc
Typically you should not hardcode those strings, but that also depends on your localization strategy and tech savvy of your writers. If your dialogue involves complex logic/evaluations, and if your writers are programmers you can do a lot by doing everything in code that would otherwise require large investment into tools development.
as I said in the #💻┃unity-talk
oh god no.. use a json file or something
you need a "lookup system" key and value works well
maybe even scriptable objects with an array of strings
What do you mean? Are you asking to display the function in a code window? I'm not sure how to do that
And like someone else said, #archived-code-general
im saying to format the code properly so its better legible
I mean sure but you could've also replied to it here or something lol
anway, using constants like that would probably the most cumbersome method lol
not flexible / modular at all. Not an option when you want good code
Is it better now?
I guess but if this is an addressable question should keep it there, posting in two channels isn't allowed just fiy
Gotcha, I'll refrain from doing so in the future. I just wasn't entirely sure as I didn't write the script myself, so I figured I'd post it here just to be safe. My apologies
no worries, is there a specific reason for using addressables btw ? They have some good tutorials that goes over the whole setup
this function is for an AssetFinder script. I initially wrote the functions using AssetDatabase.LoadAssetAtPath<GameObject>(path), which is an editor-exclusive function that doesn't work in builds. I didn't know how else to locate and load Prefabs and other assets, and when I brought other developers on the project, one of them recommended addressables
the developer should be back in a week or two to handle this stuff moving forward, but progress has slowed to a halt right now and I really just want to fix this script so we can move on with further development
Addressable is good but probably overkill from what you need, you can easily just use prefabs n plug them in the inspector or resource folder if you really want to go with the whole string thing..
Well, I want to be able to search for any prefab by name, without needing to manually add a reference to it through the inspector every time
In addition, I have other functions in the script that act very similarly but search for other assets like Tiles
https://docs.unity3d.com/ScriptReference/Resources.Load.html
worth checking out
if it's supposed to work in builds, your guy's code makes no sense because it's also only usable in editor
btw what is the current issue with your setup, returning gameobject , is it not working?
Hm...here's the original function. If anybody can help me rework it so that it can be used in builds, I would appreciate it immensely:
string[] guids = AssetDatabase.FindAssets("t:Prefab");
foreach (var guid in guids) {
var path = AssetDatabase.GUIDToAssetPath(guid);
GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
if (go.name.Equals(prefabName)) {
Collectable goCollectable = go.GetComponent<Collectable>();
goCollectable.type = goCollectable.itemSO.type;
goCollectable.icon = goCollectable.itemSO.icon;
return go;
}
}
return null;
}```
well you can't use AssetDatabase for starters
its a UnityEditor class rather than UnityEngine (build)
yeah, I get that...the other developer suggested Addressables as an alternative, but now that also seems to be unviable, so I'm unfortunately at a loss
Still unclear what your end goal for all this is
You could probably even use Scriptable objects to hold groups of prefabs etc
this whole thing seems like the end-stage result of a terrible plan to begin with. Why are you searching by name? The easiest solution is a SO, slap a serialized list of prefabs + names on it, #ifdef an editor context method that populates that list using AssetDatabase, and boom you have a runtime thing you can search much more efficiently than literally loading every single prefab you find to see if it's the right one
but since you're using string names, it's going to be brittle and awful to work with
addressables pair better if you plan on using bundles or files stored else where, something like that
loading downloadable content, or large environments that need to be loaded into memory much later
so let's say I have a script for the player character that says whenever I use this item (let's say an empty bucket) while facing a body of water, the bucket gets removed from the inventory and a new item (the filled water bucket prefab) gets added in its place. I could add a direct reference in the script to that prefab, but then I'd need to create a new reference every time I make a new prefab that needs to be used in the script. whereas if I can just create a function to grab the preset by searching with a string parameter, I can grab the prefab by calling a function in the player script, no direct reference required. that's my goal with this function, and the others in the AssetFinder script
I'll happily admit that I'm not the most experienced Unity developer, but your proposed solution seems to involve a list of prefabs + names that I will need to update every time I save a new prefab for use in other scripts. I'd rather avoid that if possible, and be able to reference any prefab as needed without making references or leaving the script editor
no, you don't manually change the names or add to the list. You automate it so the editor does it for you
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How to prohibit the use of the StartCarryHold() method
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I don't want to make a fool of myself, but I'm admittedly lost as to how I would implement that. Some of my prefabs do have SOs attatched to them, but how would I automatically scan for them and then be able to reference them in other scripts through a function? I'd really like to learn how so I can use this information in future projects
when you're holding an object?
[HELP WANTED] btw, if anybody else is reading this chain of messages and can help me implement xEvilReeperx's solution, I'd be really grateful for your assistance. Just ping me when available or reach out via DM.
people arent gonna dm or just randomly work on a solution for you. try and implement it, and ask specific questions when you're stuck on something. I read some of the messages above, and some things dont really make sense.
Some of my prefabs do have SOs attatched to them,
SO's dont get attached to a prefab, they arent components. you would be referencing it through a script which is a component. You shouldnt need to "scan for them" no matter what you're doing
my issue with trying to implement it is that I really don't know where to start. when mentioning SO's being attatched to the prefabs, I did mean as a component. Sorry if that didn't come across clearly. But if you're saying I don't need to 'scan for them', then what was xEvilReeperx referring to with the serailized list of prefabs + names that automatically populates the list using AssetDatabse?
@lean sail I'm already stuck. If that means that I should be writing this thread in #💻┃code-beginner, then fine. But I haven't been able to find a solution for revising this function on my own, and when I'm being given solutions from others that I don't fully understand and therefore don't implement, what else can I do besides ask for more involved assistance?
https://docs.unity3d.com/ScriptReference/ContextMenu.html the AssetDatabase part they wrote is strictly for editor. you can use a context menu attribute to give yourself a button to run this code during editor time (or use editor scripts).
my concern is that I need this function to operate without relying on editor-only resources like AssetDatabase, otherwise I won't be able to export a build
the whole purpose of this is to populate your data at editor time. The code isnt in the build if you wrap it in the #if UNITY_EDITOR conditional
which is what they meant by "#ifdef an editor context method that populates that list using AssetDatabase"
Ah...I think I'm starting understand what you and xEvilReeperx are referring to. The goal is to create an editor function that loads the prefabs into a list or dictionary that can then be accessed and searched during runtime, correct?
Yes, though a dictionary would require other editor code to make it serializable. A dictionary isnt serialized by default
Gotcha
here is an example you can start with, the simplest possible implementation of the idea: https://hastebin.com/share/zaheriqolu.csharp
updated script, accidentally ifdef'd GetInstance :(
but I maintain this is a terrible plan, from your earlier description the player script knows too much and it's forcing you down this dark path
help guys
It’s not just the player script that wants to be able to search for prefabs. This script you sent would hypothetically be usable by any script who needs to find a particular prefab, and it can do so by just calling a function and passing in a string. I’m failing to see the big problem, unless this script either doesn’t work or ends up being abhorrently inefficient.
I’ll try implementing it and let you know how it goes, though. And thanks for your assistance regardless
What do you need?
It really is a mess.
However, I believe saying that Health, Mana and Movement Speed are fundamentally different because they have a "max" is wrong. Other statistic could potentially have a maximum value as well.
Your main problem (decreasing, increasing) is an other things that could be considered fundamentally different per stats. However, I believe there is nothing wrong with how you did it. The only thing I would do is try to rename current and rawCurrent for something else. (base/baseValue could be a good choice)
Whenever you level up or your equipment change, you could have a refresh happens.
- Drop all modifier from your stats.
- Ask every provider of modifier to recreate their modifier.
- (Do not reevaluate your current till all provider have not finish adding their modifiers)
As a side note, I believe Diablo use "bucket" for multiplier. You could have something similar instead of doing CurrentModifier.Increase and CurrentModifier.More.
check my message
Linked the message for greater visibility
check
How to prohibit the use of the
Im making a game involving space orbits. I have a pretty simple setup where I divide objects into attractors and attractees. The player is to control one of the attractee objects. I want to later allow for the player to add forces to control the object, but for now Im trying to figure out how to calculate the future posistion of the object, for a line renderer to trace it.
I originally thought about using the Physics simulate, but that would move everything into X steps into the future, which I do not want. So I am guessing that I have to create a copy of all of the gravity objects then use physics simulate, or is there some better way that I overlooked
If you do not need to consider collision, you can simply use math to figure it out. Otherwise, you have https://docs.unity3d.com/Manual/physics-multi-scene.html
[HELP WANTED, RESOLVED]
Currently trying to call a function that has no type arguments, but although no errors appear within the code editor, Unity won't compile the script because "The type arguments for method ' PrefabCollection.FindPrefabMyName<T>(string) ‘ cannot be inferred from the usage. Try specifying the type arguments explicitly, despite the function having been edited to not have <T> as an argument
var instance = GetInstance();
var entry = Array.Find(instance.prefabs, e => e.name == name);
if (entry.prefab == null) {
throw new InvalidOperationException($"Prefab with name {name} not found");
}
var item = entry.prefab;
return item;
}```
```inventory.AddItem(PrefabCollection.FindPrefabByName("WoodBucket(Water)").GetComponent<Collectable>());
So my unity is crashing due to the post-processing script plugin. I've found the line that is crashing and it's crashing because of a texture it's trying to read. i want to find the texture but i cant attach VS because unity is crashing when i open the scene that references the texture.
How would i attach VS to be able to debug scripts like post process which run in the editor?
the function you mentioned isn't the shown function. If you want to use the template version of it, provide type arguments, ex:
inventory.AddItem(PrefabCollection.FindPrefabByName<Collectable>("WoodBucket(Water"));
I wrote that method using generics because:
- almost always, a serialized reference of a prefab that is a GameObject is a code smell
- your line, as written, can potentially add null items to inventory unless AddItem guards against it
as someone who has very little experience with using generics, I have to ask so I understand: wasn't T the only generic in the original function? And by removing T and writing the function to return a GameObject without any type arguments, it shouldn't need any, right?
your error implies FindPrefabMyName<T> (misspelled intentionally?) exists in the PrefabCollection script
The weird thing is that there isn't. I changed the name of the original function to FindPrefabComponentByName<T> in case I needed it. The version I sent in the earlier message is the only one currently in the script, which is why I'm confused that it's asking for generics
are you sure you're looking at the right line/script? Maybe you are trying to call it from elsewhere
Nope, I've checked the references. The function being called for the inventory is the same function listed above it
Even if I delete the FindPrefabComponentByName<T> function, Unity still won't recompile the script and the error still persists
post the updated scripts + the exact error. I assume you aren't using any relevant third-party tools like hot reload that seem to throw a wrench into things occasionally
nope. lemme do that
use code sites for anything larger than a snippet
lemme do that
here's the PrefabCollection script https://hastebin.com/share/boxawakofi.csharp
and here's the PlayerHandler script https://hastebin.com/share/yobuxinado.csharp
writing the error now
Assets/Scripts/PlayerHandler.cs(90,48): error CS0411: The type arguments for method 'PrefabCollection.FindPrefabByName<T>(string)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
(CHECK LINE 90)
looks fine to me. Try these steps next, in order, to see if any solve the problem:
- restart Unity
- close Unity, delete Library/ScriptAssemblies folder, open Unity again
- Unity prefs -> External Tools -> Regenerate project files; restart Unity
- wipe Library entirely
Surely you want
- PrefabCollection.FindPrefabByName("WoodBucket (Water)").GetComponent<Collectable>()
+ PrefabCollection.FindPrefabByName<Collectable>("WoodBucket (Water)")
Oh wait, you're using a different thing...
where is the generic version?
You removed the generic version, so presumably you never saved that change
Sorry, I didn't read the whole convo and did the bad thing. I've never seen this happen unless there are other errors or there hasn't been a save
the not-saved script is an excellent point though, my ide saves automatically so I didn't consider it. It could be that simple
some IDEs don't save all dirty files, which sounds very inconvenient
it's working now..kinda (something else broke, but that script is working properly). Thank you for helping with the script, I really appreciate it. 💖
Is there a way to get the playmode resolution? Screen.width doesn't seem to work with it...
should work fine
I'm having an issue with the screenshots being cut off while in the editor
{
string _screenshotDirectory = Application.persistentDataPath + AstroEngine_ScreenshotDirectory;
if (!Directory.Exists(_screenshotDirectory))
{
AstroEngine_WriteToConsole($"Directory '{_screenshotDirectory}' does not exist. Created folder");
Directory.CreateDirectory(_screenshotDirectory);
}
string time = System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Year.ToString();
Texture2D _screenshot = ScreenCapture.CaptureScreenshotAsTexture();
//Save the file
string _fileName = $"Screenshot {time}.png";
File.WriteAllBytes($"{_screenshotDirectory}/{_fileName}", _screenshot.EncodeToPNG());
audio.Audio_CreateUISFX("uiclick");
AstroEngine_WriteToConsole($"Screenshot taken and saved to {_screenshotDirectory}/{_fileName}");
//Prevent from garbage collecting
Destroy(_screenshot);
}```
Here's the code I'm using for capturing the screenshot
Is it possible to do transparent WEBM captures on the Unity Video recorder?
This sounds like a stupid question since it exports in VP8, but I've tried everything imaginable to find out how to make that happen and I feel like I've hit a wall
try with a coroutine and yield return new WaitForEndOfFrame(); before capturing maybe
ah it pays off to read the docs you see..
To get a reliable output from this method you must make sure it is called once the frame rendering has ended, and not during the rendering process. A simple way of ensuring this is to call it from a coroutine that yields on WaitForEndOfFrame. If you call this method during the rendering process you will get unpredictable and undefined results.
Ohhhhh ok
Is there a way to save a List/Dict with JsonUtility?
I can use a struct, but I'd need a List/array to make it more useful.
or do I use the other Json parser, forgot its name
List yes, Dict, no
It seems like I cant save List of structs, but I will try again
Does the struct have the [System.Serializable] attribute?
oh no 😄
can't serialize something which is not marked as Serializable
Do I need to serialize all public fields too? It seems like that might be required
no, public fields are serializable by default as long as they are primitive types
they are primitive types
It saves {}
then you are doing something wrong
I am saving:
List<AudioChannelVolume>
[Serializable]
public struct AudioChannelVolume
{
[SerializeField] public AudioChannel Channel;
[SerializeField] public float Volume;
}
string channelVolumeSaveData = JsonUtility.ToJson(AudioData.GetChannelVolumeList());
is AudioChannel also Serializable
but wouldnt it at least save Volume?(it's not serializable tho, let me add that)
no idea based on that code. Debug it
Debugging all the time
if you want a List you need that to be inside an object
oh thats what I thought might be the case, let me give that a go
Actually thats not very convenient, can it save dictionaries if they are inside a struct?
no
I suppose that I need an extra layer then to store a list only
yep
That works, thanks 😄
if you have a Dictionary to serialize you can break that down to a List of Keys and a List of Values before serialization and then reconstruct the Dictionary from the 2 Lists after deserialization
That sounds like a better solution too, this way I don't need 2 structs.
Hi is there a way to wait until a gameobject has done being enabled?
The object is enabled right after setting it enabled. What exactly do you want to wait?
do you mean after instantiation
I want to wait until its done being enabled for example lets say i have a level and i enable it with SetActive i want to wait until its done being enabled so i can do other stuff afterwards
Why just not run code* onEnabled ?
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnEnable.html
Yes but what does "done being enabled" mean? It is "done being enabled" right after calling SetActive. You don't need to wait anything.
Do you have some problem with it that you're trying to solve?
im trying to wait for level to be enabled so i can spawn my character thats it
You don't need to wait. SetActive is instant.
If it doesn't work then the problem is somewhere else
so even if i have a really big scene is it still instant?
You asked about enabling gameobjects. Are you actually loading a new scene?
this doesnt work in my situation bcuz im not using scenes
So what does having a big scene have to do with it then?
by big scene i mean enabling a large gameobject like a Level Gameobject
It doesn't matter how big the object is or how long it takes to enable it. It's enabled on the next line after calling SetActive
ok i get it but some times the characters falls even if i spawn it after i enabled the level
That's an unrelated issue
My brain just stopped working so, how would I get the delta of a vector using the previous and current value? It should be simple but my brain can't right now for some reason
just subtract them right? curr - prev
Thanks
alternatively, if you're really dealing with vectors as opposed to points, maybe you want the angle between them, which you can find using the cross product
Yes, it should
If something can't be serialized it should be ignored, or at least throw an exception
But JsonUtility is a very bad tool for serializing JSON. Consider switching to Newtonsoft which will work properly. JSonUtility lacks a lot of basic features
Note that it does require you to use properties rather than fields. This is very normal and only Unity uses fields because it has very bad standards
Is there any way to control the softness of shadows?
Like obviously there is hard vs soft. I'm saying the amount of softness.
What render pipeline?
Anyone worked with BehaviorGraph in Unity 6? I'm getting NullReferenceExceptions on my BlackboardVariables in my Action scripts and I'm not really seeing docs about it yet.
What are the exceptions?
not by default with the Standard pipeline afaik. You can surely code it in a shader though and use it for your game meshes -- if you're willing to go that way.
URP
Standard Pipeline as in URP or Built-in?
Built-in
@stable osprey they're just nullreferenceexceptions when trying to set the values
or read the values
In my case I'm using URP
I meant like post a screenshot lol
but it's very probable you just didn't assign any values in the inspector
oh, sec
for example you read myText.text but myText isn't assigned
@stable osprey this issue is specific to the behavior graph. these variables are created in the behavior graph itself. i didn't even think they could be null because of that, since they're assigned a value in the blackboard itself
Imma ask for that screenshot after all.. full screen preferably 😛
click on the blue thing here:
well, seems your SwimSpeedMultiplier is null at that time 😛
yes, it is. i'm trying to find out why 🙂 i'm not seeing documentation for getting the values for that variable from the blackboard
did you check out the stuff in here?
ah, should you be calling base.OnStart() in the beginning of the method?
not sure where the initialization of the variables from the BehaviorAgent to the graph/script happens, sorry.
nah, adding that didn't help
it seems like the blackboard variables are supposed to sync between the script and the graph as long as they're named the same. at least, i can't find any documentation saying otherwise
can u post the relevant parts of the script?
u can use ctrl+M+O to collapse it so I can only see the definitions if u want
(in screenshot is fine -- post as much as fits from the start)
ah yeah no wonder they don't sync 😄
they should be [SerializeAsReference]
also, maybe blackboard variables need to be public, I'm not sure.. that's what the tutorial says
they also add the [Serializable] and [GeneratePropertyBag] attributes to the class
[SerializeReference]*
where are you seeing this in the docs?
I don't, first result for BehaviorGraph returns this video: https://www.youtube.com/watch?v=QpIBFLvumEc
The New Behavior package comes with some much needed functionality for building node based systems in Unity. Learn how you can take advantage of this new package to create custom node based logical flows, broadcast events, and build custom actions with a system that is extensible, serializable and easy to use.
NOTE: Requires Unity version of ...
alright, great news! different error now! wooo! thank you so much.
np 🙂
sup gang
Hello everyone!
Today I will teach you how to make objects in Unity draggable using a simple script!
Leave a like if you enjoyed, and let me know if you want to see more of these types of videos!
The script used in this video:
https://pastebin.com/X6DPn5XN
------...
I was trying to follow this
out of curiousity, could you try making it nonpublic -- just with SerializeReference and see whether it still syncs?
it does, yes
thanks
can you like post the code properly and with a coherent question attached to it ?
let me cook
use ScreenToWorldPoint, not ScreenToViewportPoint
ya don't bother 😛 the issue comes from what I posted above
I did this btw
public static Vector3 GetMousePosition()
{
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
return mouseWorldPosition;
}```
nah, it's fixed, I think
void OnMouseDrag()
{
_rb.isKinematic = true;
Vector3 objPosition = ExtensionMethods.GetMousePosition();
objPosition.y = 1.5f;
transform.position = objPosition;
}
void OnMouseUp()
{
_rb.isKinematic = false;
}```
I mean the code is fixed, but it still does that
the z is probably still wrong because of this
https://unity.huh.how/screentoworldpoint
it's still not 100% proper if you're using a UI canvas
I do have a Canvas, but the cards are 3d objects
LOL yeah that's an issue xD
your camera is prospective and you're dealing with the Z on nearclip issue
this ain't gonna work
and.. why are you using 3D objects on a UI? 😛
I have it open
oh
much easier to use Plane usually
but can also try
var pos = Camera.main.ScreenToWorldPoint(etc..
pos.z = 0; // or whatever position
mything.position = pos```
let me try that
then I'll try this if it doesn't work
didn't work, let's see xD
void OnMouseDrag()
{
//Vector3 objPosition = ExtensionMethods.GetMousePosition();
_rb.isKinematic = true;
Vector3 mousePosition = Input.mousePosition;
Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
objPosition.z = 1.5f;
transform.position = objPosition;
}```like this?
didn't work XD
what do we mean by using a plane btw?
people will be able to move the camera
I would like something that works from any angle
would using a plane like you're saying work for this?
a plane would make it so there is some a "board" you can drag stuff onto etc
like its invisble but the ray can capture it so you can have movement always be proper
ohhh
super good method
right now is kinda messy but
I have a box collider on my invisible table, would that work?
Nevermind, I was wrong. They do have to be public. I forgot to save
thanks for the update
minor feedback you have too many Zensus and Vacatas 
it works as a plane sure
no this is super wrong.
why are there rigidbodies on the card lol
void OnMouseDrag()
{
_rb.isKinematic = true;
var mousePos = Input.mousePosition;
mousePos.z = 0;
Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePos);
objPosition.y = 1.5f;
transform.position = objPosition;
}
@solemn ember
nah they had it correct
Input.mousePosition is vector2
XD
already has a 0 as z
cards have physics duh 
I want physics, so people can drag them
You don't need physics for that.. you just need collider
it's like a tabletop simulator kinda project, something to pullup quickly so we can show the game to people
its vector3 to not cause issues with calculations n having to cast v3 n v2 but its technically only a vector2 captures
its pixel position of your mouse
if u insist this might even remotely be correct in ANY use case I suggest you re-read this xD
oh right yeah the idea would be to mousePos.z = camMinPlane. the main change was on objPosition.y = instead of .z
yeah basically https://unity.huh.how/screentoworldpoint
the z on ScreenTOWorld is always the nearClip so it cause wonky numbers
however just go with the raycast mode imo
agree. ScreenToRay much easier
esp if dealing with colliders
but might still need plane to capture the dragging movement of a card
ahm
yeah, on the link one of these would be the most appropriate way to correctly identify the target world position.
okay so screentoray
the rigidbodies, I want to give freedom of movement to people and also make it feel like if it was playing in real life
or aiming to that
imo a plane makes more sense
ya'll fighting for me, that's cute
not at all lmao
whoever wins I'll give a kiss in the cheek
I want riches and fame instead
I'm debating myself if one is better than other cause I used both, in similiar situation
pat your buttox with a hammer
tbh I always reach some hacky fixed-or-fake-distance + cast downwards to get the actual world position when I wanna use that in 3D
mostly need ScreenToWorld for 2D
so, raycast to the plane?
try both see which one fits your needs
that'll be best for your card game yeah
you need to learn to experiment and trial n error
the alternative is actual-physics-based, so you find the ground and offset upwards by some amount
but this might end up dragging the card on the floor on your specific case
nice
this works
void OnMouseDrag()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
_rb.isKinematic = true;
Vector3 cardPos = hit.point;
cardPos.y = 1.5f;
transform.position = cardPos;
}
}
void OnMouseUp()
{
_rb.isKinematic = false;
}```
thx gang
so i still dont know whats better to use class or struct
no such thing as better in this case, it depends on your design and use case
few arrays with data of another type
depends on what you're doing with the data
that store very much infi
if the object contains other objects then, generally, class is better
but object lifetime is also very important, shorter lived objects are better as structs
basically yes
what about very large arrays of something like floats
arrays are objects
so I created a Shader that takes two colours and puts them on a material as a gradient
works like a charm
but I dont know how to access the colour properties in code
this is how the shader looks in editor
this is the code Ive been trying, which doesnt seem right in the first place but Im not sure what other options Id need to use
Using shader graph?
aye
The names of the parameters you set in the graph are only for display, you need to look at the Reference Name of a parameter. It's the one you use from the code
You can rename them as well
np
you can also see them if you switch your inspector tab to debug mode
well well well
Any good Tutorials that are simple and explain the thematic of changing variables in another script from a diffrent script? I just cant figure it out
ok followup on this: I do this for a bunch of objects in the scene, but running the code changes all instances of the material - Id like it to only apply to the instance of the material that's on the object Im running the code on
this goes in#💻┃code-beginner
not a video but this should help
https://gamedevbeginner.com/how-to-get-a-variable-from-another-script-in-unity-the-right-way/
https://docs.unity3d.com/ScriptReference/Renderer-material.html
worth taking a look
got it, ty
not a code question
Where should i ask about this?
Ok my bad
all good
hi. my inventory system has an item class, where each item basically just contains a string identifier.
when rendering my inventory i basically want to look up the icons based on the identifier.
what's the best way to do that? is there any built-in data-table or so that i could use?
you should look into ScriptableObjects for creating your items
i dont want my items to contain any references, i want them to be simple structures basically
with ScriptableObjects you can define the items with their names and sprites and identifiers and anything else you may possibly need that is related to said item
and then you can make a Dictionary at runtime that stores the identifiers as keys and scriptableobjects as values
and keep the identifiers inside your inventory class
and look up the ScriptableObjects from that Dictionary using those identifiers and pull things like icons from that ScriptableObject
also consider switching to int IDs rather than string ones
string IDs are p a i n
and they WILL screw you over
i appreciate your help, but i already know about scriptable objects. i'd rather bring back my original question: is there anything built-in or in a package that lets me link assets with identifiers in a table?
addressables maybe? and making a specific category?
that would be taking a bad idea and then implementing it in the most convoluted possible way
if you need a table to look up identifiers, implement it yourself in a few lines of code. Somebody asked a similar question yesterday about looking up prefabs by string identifier, so maybe you can have a look there to see if that might be adapted to your needs
the way I've always done it, is create a key-value Dictionary where the key is the identifier and the value is something like scriptableObjects - and since you can't show dictionaries in the inspector, whatever you're using as values needs to have a reference to the key as well
If you're determined to have another way, you can use the Resources.Load or Addressables to load your data, and have a function that converts the string identifier into a path to load the addressable
but you're gonna have to keep that in mind while creating and assigning your addressables and honestly it's not the way to go
if you do items, you do scriptable objects it's as simple as that I really don't know what to tell ya
it's the solution to the problem and unless you have quite a unique reason for why you can't use scriptable object, they're the way to go
ok, i might consider scriptableobjects. but i'd still be interested if there's data-tables like in unreal. so i guess there isnt?
dictionaries
but you can't show them in the inspector easily
i remember doing a custom class once where you manually had to serialize the dictionary
into 2 lists (key list, value list)
well yeah you can do it this way but it's a pain in the ass to do and it's very vulnerable to changes
if you actually just go with 2 lists
because if you want to change something or remove an item it's in 2 places and it's difficult to match them up in editor etc etc
no, the class used a dictionary, as i said on serialize you had to serialize it as 2 lists
and on deserialize fill the dictionary again
and you end up maybe creating a struct to keep the key/value list in one place and create a dictionary out of that and maybe there's an easier way to manage them than a shitty list within an object within an inspector window and oops you're at scriptable objects
yea I get what you mean
but how do you serialise deserialise those lists into a dictionary? you go by order?
that's my point
so i guess if i use scriptableobjects i'll still need some sort of lookup table if i want to spawn an item by identifier and not by reference
yes
but why do you not want to use scriptable objects?
the scriptable objects approach is simply to create the lookup table without pulling your hair out
i dunno, something something "dont mix backend with frontend"
something something bad reason
frontend and backend need to communicate and to do your backend properly, you should use scriptable objects in this case
i guess if i'd want to go the rimworld route, it'd also be nice if the identifiers are the actual classnames, so it's kinda data-oriented
which seems nice for modding
please don't make string identifiers unless you absolutely have to
keep identifiers as ints
use names
in the scriptable object
strings that have no actual bearing on anything except they're being displayed in your ui
don't rely on string for identifiers ideally ever or almost ever
i have to use identifiers anyways once i save something to json or xml
yea
INT identifiers
i prefer when you can edit save-files though and read what they actually contain
then at least implement some safeguards for your system that will make sure you're not looking for random spaces at the ends of items, or different capitalisations ruining your day ¯_(ツ)_/¯
also when modders add new items you can have namespaces for items
I'm not even saying you shouldn't have namespaces that are user-facing
modders don't even have to know about the ints
I'm saying that under the hood you should use ints instead of strings
otherwise you're gonna be hunting spaces at the ends of strings until you move on from this project
well, do as you will
scriptableobjects are the way
hm i cant really find much info about inheritance with scriptable objects. they all seem to use very very simple examples of inventory's and everything is supposed to be one Item and one ItemData class.
but what if i have StackableItemData inhering from ItemData?
then i need an Item class and a StackableItem class and the StackableItem needs a reference to the StackableItemData
so basically when i add an item to an inventory i need to know its class and its scriptable object reference
scriptable objects are only supposed to hold data right? e.g. they should hold maxAmount but not amount!?
since they are not instances, they are just one thing in memory holding static data
other option is having one big monolithic item and itemdata class i guess, but that kinda sucks
you could always have the asset ones define data and have in memory instances for stuff like current quanity
inheritance works the same way it does any c# class. this part doesnt really make sense imo
so basically when i add an item to an inventory i need to know its class and its scriptable object reference
why?
Your inventory should hold the base class if possible, the base class should define as little as it needs to but define methods that deriving classes can override.
i have Item, StackableItem and HealthPotionItem right now.
and they get their needed data from ItemData, StackableItemData (inherits ItemData, adds maxStacks) and HealthPotionData (inherits StackableItemData, adds healAmount)
so basically when i want to add a health potion to my inventory i need to call:
(property) HealthPotionItemData healthPotionItemData;
...
inventory.AddItem(new HealthPotionItem(healthPotionItemData));
if i want to add a basic item i need to add:
(property) ItemData ItemData;
...
inventory.AddItem(new Item(itemData));
having the data passed in the constructor so the items can store a local reference to the data object.
so i basically need a lookup table like:
[identifier, Item SubClass, Scriptable Object Reference]
if i want to spawn items
Why does inventory know details about items and item data? This seems like a design problem to me, and inventory is going to end up having to know about every type of item and every type of item data (whatever that is)
You should not use inheritance for to add the concept of Stack.
The reason is that C# does not permit multiple inheritance and if you ever want to make something like a DurabilityItem or a EphemeralItem you would not be able to have a Stack + X behavior. Instead, you should use composition.
public class ItemData
{
private List<ItemDataComponent> components;
public bool TryGetComponent<T>(out T component)
where T : ItemDataComponent
{...}
}
public class ItemDataComponentStack {...}
public class ItemDataComponentDurability {...}
that looks like a terrible design too, unless you intend to add those components at runtime for some reason
does trycatch cause any lag when no error found?
What do you mean ?
If the idea is to serialize the data, you either:
- Use a Factory (Not really something I recommand)
- Use a GameObject and harvest Unity Instantiate Function.
- Or implement a "Clone" function.
Shouldn’t as far as I know. There’s likely a lot of resources available online on the performance implications
your design implies runtime addition of presumably immutable properties like whether something stacks. And if you think a little further into the future, what if one Item wants to interact with another Item? You'll have to put a string identifier on them to tell them apart and have no compile-time protections at all. Why wouldn't HealthPotion just be an ItemData that has Stackable + Durability fields? That would be the right way to do composition here
- There is many way to distinguish between one item or an other. I usually use a
Definition(ItemDefinitionin this case) - If you think even further ahead, you are going to realize that you needs a way to interact with
Stackable Itemthat are notHealthPotion. Your only alternative would be to use an interface (IStackable) which would means that you need to redefine all the code of aStackableItem. (You might have events (OnStackModified), maximum value or other behaviour that would be appropriate to be share through all items)
You have a ItemDefinition that defines the data that defines what an Item is? Why? And no, if I were designing this there wouldn't be stackable items. All items would be stackable. Some would just stack up to 1. Otherwise you end up with those corner cases that you're talking about, where actually Items don't all have the same interface and so can't be treated the same way
- Every Object (Character, Level, Item, Modifier, etc.) has a
Definitionto be able to retrieve the identity of it. - Making every object having every behavior does indeed work. However, the more behavior you add the more your item code become bloated.
Also, I'm not sure what is the issue that each item has different Interface.
your ItemDefinition as described is redundant if you also have an ItemData containing "component"s which is the real definition of what a item is. You could merge them
and no it doesn't bloat code; items only implement what they need. Make behaviors virtual with default implementations. You get the benefit of type safety this way, too
ItemDefinition contains the name, icon, description and the instantiation process (in this case). It is not redondant.
What you suggest goes against Interface Segregation Principle and the Open-Close Principle.
Also, the pattern you suggest would be Template Class Pattern which in it essence is not an Anti-Pattern however the way you are using it definitely makes it one.
That being said, as long as your item behavior are relatively small, you would not have any issue with the approach you suggest.
no it doesn't. Like I said, all items are designed with the same interface in mind. And you never modify Item, you derive from Item to implement new items and define their behavior
be careful slavishly following solid methods btw, those are intended for long-term business applications and can be harmful in game programming where it's mostly build it, you're done, move on with no long term support
If you want to add a behavior, you need to modify the Item to include this behavior. - This violate the Open-Close Principle.
If you do not have a behavior for a specific item you need to keep it empty or throw a not implemented exception - This violate the Interface Segregation Principle
Not sure what you mean, an Inventory system is usually reused through multiple project. They have a considerable long life if you are doing things right.
With something like this, I honestly think it's ok because you mainly define what an inventory can do and it rarely changes.
Like stackable/non stackable, item use, item drop is enough for most cases.
I don't modify Item ever, because it has all the common behaviors needed already. And all items need all behaviors. For example, in your design, how does the user merge stacks, one being a stackable thing and the other not? The correct, default behavior that all Items in my design share is that nothing stacks, and Items individually determine what happens (they can override this default-supplied behavior). No open/close violation there
Yeah, I said it too. As long as it stays simple. The issue is bloated code, if the code is not bloated then there is no issue.
Sure, if the behavior can be share through all items. If you have something like a chest or a charging item. Does every item contains the behaviour of a chest or the behaviour of charging item ?
Item is an interface that only defines inventory-related things. Does the behavior of a chest belong in an inventory?
If the item needs to hold all the item a chest holds, yes it does.
you said behavior though. Chest would just be yet another inventory and do all the same things inventory does. Chest logic wouldn't go there
I meant an item that is a chest (I.E. holds other item when in inventory)
You would by example, have the possibility to open the item to see what is inside.
lol I think we've really got into the weeds here. I don't think I would understand your design unless I could see it implemented in code. There's no reason you couldn't have an ItemContainer that contains an Inventory, and its Use or Inspect or whatever inventory-related behavior opens another ui that shows its contents
So, you would use inheritance to add the behavior.
If you have a second behavior that also requires inheritance because the behavior cannot be shared, you would not be able to have both of them at the same times.
By example, if you were to say that a ChargingItem is required, you could not have a ChargingItem that is also a ContainerItem.
You're trying to come up with weird edge cases for some reason? Yes, if I needed behavior like that I'd factor out the common stuff and make ChargingContainerItem sure. If that's actually a common case and not a one-off, it starts to seem like maybe every Item is a ChargingItem that has one charge and then it's solved easily again
but I don't think I'll be able to convince you over your way so this conversation isn't productive and we should move to a thread since it's way past the original point
If you ever get to a point where your item is 1000+ lines with class such as ChargingContainerItem, know that there is alternative. If not, then what you are doing is mostly adapted for your needs.
Also, you should really consider the aberration that is ChargingContainerItem.
lol that was your weird edge case, not mine. And it's likely to have only a few dozen lines, given that common logic would be factored out so ContainerItem and ChargingItem presumably both exist and use it
What are you talking about ? ChargingContainerItem is what I'm trying to prevent, this is your way of doing things. Failing to see what is the issue with such class is on you.
A few dozen lines of code ? If you have 10+ behaviors that is share that is not going to be a few dozen of lines of code.
Anyway, keep doing what you are doing. It seem to work correctly for you.
Trying to figure out a better way to control my npcs turns in my game. Currently I have everyone in a list and it controls their turn with a bool.
It works fine but the more npcs I add the longer a longer the turn waiting gets. In many roguelikes for instance the npcs move dam near instantly. What techniques can I use? I thought about coroutines with a foreah loop but then npcs sometimes stack on each other.
what do you mean "controls their turn with a bool"? whats stopping you from just using Update to control their movement.
Them stacking on each other sounds like an issue with your setup. do you want them to be able to move through each other?
Like the base class has a bool that when true they can move. Wouldn't just preforming their movement in update make them move nonstop? I could very well be doing this completely wrong.
well its not like that bool is actually moving them. you must be doing something in an update like setup or a coroutine.
I currently have it like so ```public class TurnManager : MonoBehaviour
{
public List<BaseMobile> characters = new List<BaseMobile>();
private int currentIndex = 0;
void Start()
{
if (characters.Count == 0)
{
characters.AddRange(FindObjectsOfType<BaseMobile>());
}
if (characters.Count > 0)
{
StartTurn();
}
else
{
Debug.LogError("No characters found for the Turn Manager.");
}
}
void StartTurn()
{
BaseMobile currentCharacter = characters[currentIndex];
currentCharacter.CanMove = true;
Debug.Log($"It's {currentCharacter.gameObject.name}'s turn");
}
public void EndTurn()
{
BaseMobile currentCharacter = characters[currentIndex];
currentCharacter.CanMove = false;
// Refresh tile for the current character
currentCharacter.RefreshTile();
currentIndex = (currentIndex + 1) % characters.Count;
StartTurn();
}
}```
and it works, it's just it cycles through all the characters then the player moves. The more NPC's the longer it takes which is expected. But I know there are some games that have near instant NPC turns in turn based games. Was just curious of some insight if anyone had any that might work.
I mean that would lie with whatever code actually takes the NPC turn
This code just manages the list
If you want it to go faster that'd be elsewhere
How heavy is your processing logic to have a delay whenever npc turns take place. 😵
that would be this then?
{
if (baseMobile != null && baseMobile.CanMove)
{
bool threatDetected = DetectThreats();
if (!threatDetected && currentState == AIState.Flee)
{
SetNextState();
}
HandleState();
// Rotate towards movement direction (optional)
RotateTowardsMovementDirection();
// After performing actions, end the turn
EndMyTurn();
}
}```
i assume its less about the processing logic taking awhile, but how this code or the movement code runs. Start calls StartTurn once. Nothing here calls EndTurn and nothing here would happen more than once without another script using Update or a coroutine.
Why is it running in update if it is a turn based game?
wouldn't it only move the npc if their bool can move is true no matter where it is?
I guess saying that outloud sounds bad
Yes sure, whatever code you have that is delaying that End turn call
Needs to be sped up
But… Why?
You are right
public void ExecuteAI()
{
if (baseMobile != null && baseMobile.CanMove)
{
HandleState();
RotateTowardsMovementDirection();
EndMyTurn();
}
}
public override void PerformAction()
{
if (aiCharacter != null)
{
aiCharacter.ExecuteAI();
}
}```
I've changed it to call PerformAction on the NPC turn.
That should speed it up. Ai will not be running idly anymore.
It's unclear to me how this ExecuteAI code works. Two of those function calls seem like an "every frame" thing, but EndMyTurn is happening each frame?
I'm reading the documentation for the StreamReader class rn, I want to try the method ReadBlock and it has the arguments char[] buffer, int index, int count, does anyone know what each of these arguments do for the method? I can't find any information on what exactly they're for
Hey, I have a problem with the Unity particule system. I have an object pooling system for obstacles in my game, and I would like to have particles whenever the obstacle linked with it is disabled. The problem is that I need to particles to get the velocity of the obstacle that is getting disabled. I tried having the system as a child and using the current velocity in Inherit Velocity (I'm using physics for my velocity, not transform), but this doesn't work if I disable the parent. Any ideas of how I could do this ?
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.Toggle-onValueChanged.html
https://docs.unity3d.com/ScriptReference/UIElements.Toggle.html
I can see that Toggle component was changed from 2018, and I don't understand how to use it now
How do I access OnValueChanged or every other thing in C#?
UIElements and UGUI are not the same system. You are looking at two completely different types
UIElements is the new(er) UI system. You probably want the UGUI toggle . . .
Yeah, I tried, I'm just missing something really simple tbh
As you pointed out I'm not using the right system
Honestly I'm not even sure what I am using right now and how to change it lol
You've probably just declared the wrong type
can you link to your !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.
(gdl.space is down)
Wait a second, you are completely right
It compiles in unity just fine
I'm so sorry lol 💀. It seems my IDE is confused
hit the Regenerate Project Files button in Edit/Preferences/External Tools
Am i just not understanding how this works, or does checking for a Quest Condition every frame sound like a bad idea?
To me, anything that sounds like it should be an event, sounds like a "bad idea" to have in Update instead, quest conditions might only need to be checked when the state of a quest changes - for example "collect 10 apples", after collecting an apple, a event can be fired, that can check if there has been 10 apples collected and any other quests where apples are relevant
Ok great, i fully agree. Hopefully i can get this Asset maker to update the system, as i am pretty locked into it. Unfortunately, as is expected, the system got big, and he has forgotten a bit of how it works. There are not proper triggers for that exact scenario you described within his system, without checking every frame (or every 'some set time'). perhaps both he and i are missing something, but seems it was just not considered properly. Thanks
Np, I dont know how complex that assets system is, but maybe you/asset creator could look into adding a Broadcaster/global event system ontop of it, to replace the "every some set time" checks, that way objects, locations, npcs, etc that are relevant to quests can call a static function that triggers what "every some set time" would otherwise do, and neither the quest objects, nor the asset needs to know exactly who/what is triggering the events (so you wont need direct references)
Sounds good. I will discuss it with him, as it is beyond me to do so, but i think if he steps back, he may decide that is a good idea. Cool deal. Thanks for the insights 🙂
sometimes assets are just poorly made or the developer just isnt that experienced. id suggest to try make a workaround instead of waiting for them to do anything.
Im not really sure how they wouldve made such a system that even checks every frame. there should definitely be events to tie into and id question the quality of this asset heavily before continuing. This isnt something a proper developer would just miss
sup gang
I'm looking to make a player hand for my cards game
like this, but in 3D
do you have any good video source on how I could make that? I've been looking and can't find anything yet
agreed. I am attempting a workaround now, but my knowledge is limited. I think he thinks that there is a way to trigger it, but his code has changed so much since he first started making the Asset, that i believe there are issues he has not yet comprehended.. there is a bit of a language barrier too, so that is making it a little more difficult. I am going to keep digging to see if i can find another way, or if it is just that i do not understand something major about his system! (pretty sure it is not that, but i have to make sure)
this does not seem to have anything to do with General Coding Concepts. meaning, wrong room. try #💻┃unity-talk
at a certain point, its not worth it to fight the system and just make your own stuff related to this. Like if you have the ability to manually complete a quest condition, make your own component which checks the quest condition via events
https://hastebin.com/share/bisifayaho.csharp
how can i turn this from single game object to multiple game object being detected
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
That does detect multiple objects. They're in the hits array. What do you want to do with them?
but it still only return one object
oh wait
i think it's because of the if statement. how can i make it return all the object it hits?
private void FindTarget()
{
RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, TargetingRange, (Vector2)transform.position, 0f, enemyMask);
if (hits.Length > 0)
{
target = hits[0].transform;
}
}
how do i turn this into detecting all object it detects?
do i make for each statement?
how many raycast hit u have?
since u only said hits[0].transform, which u only specified one hit
I want it to hit all the enemies within the circle. it acts like a radar
target can only store one gameobject. Change it to private Transform[] target; and then set target = hits
you'll have to then change the entire code to take into account that target is now an array
ideally call it targets :p
then u need more than one raycast point from the ur position to hit all the points in enter the collision u making
which will be like spider legs shape
It's a circlecast. No need for raycasts.
oh i didn't see the circle cast one
ya u need to store an array not single object for targets
Although I suspect it should be OverlapCircle instead
Hi!
I was wondering if it's possible to reference an object stored in a ScriptableObject from another ScriptableObject?
Basically I want to have public class First : SciptableObject act as a sort of "database" for objects (public List<object>).
Then, I want to be able to have a public class Second : ScriptableObject that can reference any of the objects from the First using some sort of dropdown.
Currently I think I can solve this with a custom Editor that creates such a dropdown, but I was wondering if there was a better/more native way of doing that?
Also if it's safe to do in terms of serialisation? Can I reference objects in such way and save references instead of copies?
whynot just use a simple reference field. Any reason for it being a dropdown?
dies
isnt that already giving you an array to work with?
yea and im'm trying to figure out how to return all of the game objects it hit
Either make a simple for loop or cast to List and use foreach
since it works like a radar, I plan on having all the game objects it detects to be submitted to another tower and hit it with projectiles
wouldnt be using for each easier?
thanks tho
Seems like the selector-thingy expects an object to be saved on disk in order to reference it?
Not sure how to tell it to look for an object that is saved as part of another SerializedObject
i mean that entirely depends on what you want to use the hits for. you can't just foreach over all of them and assign each to target. that would mean you just assigned the last item in the array once control leaves the method.
Depends on the amount of times you are doing it. to use foreach, you have to cast it to a new list. Usualy not a big deal, but if ithappens multiple times in update or whatever, it can add up
How so
i semt a vid on where i use it once
wait
lemme find it
Haha, sorry 😄 I am so attached to using Lists.ForEach() , my bad
Using lists?
List<T>.ForEach specifically
If I get a list of whatever callback, I for sure use foreach
i use it as a radar for tower defense
yeah, foreach, certainly. but pretty much never ForEach :p
receivelmages.ForEach(m => Debug.Log(m));
for sure
in this case, maybe. but use receivelmages.ForEach(Debug.Log) here
no reason to write out the lambda
yeah sure, why use lambda to get the item in the list 😄
private void FindTargets()
{
RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, TargetingRange, Vector2.zero, 0f, enemyMask);
// Clear the list before populating
targets.Clear();
foreach (var hit in hits)
{
targets.Add(hit.transform);
}
}
should I change it into this?
log writing is pretty much the only place i use ForEach as well
that was a joke, if you want to do something on an item in the list, you for sure use thath lambda expression, why not
cause it's longer and unnecessary :p
and i'm not sure unity's compiler version is able to optimize it away as a static anonymous function
so just pass the method group
#archived-code-general message There's no point in adding items one by one. Just set the entire thing at once
whatever, you stick to your type of doing it 😄 no sense in continueing this conversation here
so i should change this?
That's what I said, yes
i mean this part?
targets.Add(hit.transform);
private void FindTargets()
{
targets = Physics2D.CircleCastAll(transform.position, TargetingRange, Vector2.zero, 0f, enemyMask);
}
That is all you need
they're getting the transforms of the hits though?
It's better to access the transform later when needed
i'd agree
Crazy abstraction
0 distance casts are weird when there's an OverlapCircle function
I always wonder whether there's any cost incurred
public void PlaySound(string fileName)
{
Debug.Log(fileName);
Debug.Log(GameManager.instance.clipDictionary[fileName]);
audioSource.clip = GameManager.instance.clipDictionary[fileName];
audioSource.Play();
}
The line where i set the audio clip is returning an error: Object reference not set to an instance of an object, this error is for GameManager.instance.clipDictionary[fileName] and the debugs show that it isn't null, so i'm unsure what the error is about
A null reference error is very easy to debug.
- Log the value of
GameManager.instance - Log the value of
GameManager.instance.clipDictionary. - Log the value of
audioSource. - Depending on the collection type, log the value of
GameManager.instance.clipDictionary[fileName]. This is likely a Dictionary, in which case you don't have to do this as the exception would be different.
show the debugs. and how do you know its not audioSource ?
When you found the invalid value, either prevent it with a null check, or ensure it has the value. We can't help you with this unless you share more information
These are my debugs and my script to get my audio source
I am missing log messages
Optionally, you can do a comparison against null so it's more clear
make prefab of audioclip and re attatch it
Which one is line 21
yeah you never logged audioSource to make sure its not null
check if it is null or not, and check if the audiosource has audioclip or its showing missing audioclip
if the log is properly logging the element in collection, is most likely audiosource
My unity is being slow right now, i'll let you know how the debugging goes in a bit
public void PlaySound(string fileName)
{
Debug.Log(fileName);
AudioClip clip = GameManager.instance.clipDictionary[fileName];
Debug.Log($"clip {clip} ready to play in {audioSource}");
audioSource.clip = clip;
audioSource.Play();
}```
Alright so.. i debug.log(audioSource); in Start() and it doesn't come back in null.. but then in my method it does return null
Which makes 0 sense because i never set it to null
I'm making it public right now and then seeing if it goes to null
Is anyone here familiar with the mechanics of [SerializeReference]?
I'm looking at the saved asset file and see these rids
items:
- rid: 1445398361900843011
references:
version: 2
RefIds:
- rid: 1445398361900843011
type: {class: Modifier, ns: GAS, asm: Dreadpon.GAS}
data:
_level: 1
_displayName: Stuff 1
_labelName: Stuff 1 [LVL 1]
Is there a guarantee these will stay constant across editor relaunch, project exports and end user launches?
I want to reference these rids in a ScriptableObject as a "link", and retrieve data from it using ManagedReferenceUtility.GetManagedReference() both in Editor and at Runtime
So my issue was that i had two of the same objects in the scene and then when i added them using FindObjectsOfType() and one was inactive so the audiosource was null, yeah that was my issue haha, rookie mistake
ohhh...hm yea..was going to suggest searching for that next but was hesitant because it only printed 1 version of logs, but now it makes sense ig lol
yeah it only printed one because only one was active i guess
If you press the home button in mobile or respond to a notification, which one is called? OnApplicationFocus or OnApplicationPause
#📱┃mobile
Also why not just 
Does not work on the simulator
anyway as described in docs
On Android, when the on-screen keyboard is enabled, it causes an OnApplicationFocus( false ) event. If you press Home when the keyboard is enabled, the OnApplicationPause() event is called instead of the OnApplicationFocus() event.
you dont have android to test on?
Nope I use an iphone
OnApplicationFocus does work with the editor.
I read it
Pause probably does too, but I'm not sure I've used it to know for sure.
All you have to do to test Focus is to click on a different app in Windows, and then return to Unity
Not with simulator
Yeah it does
Simulator is just a view anyway, it's the editor that's giving you the calls
It doesn’t at least for me
I have a debug.log in those methods to doublecheck
When I press play, both onapplicationpause and onapplicationfocus is called
Then never again no matter what I do
I can't even test ios cause no iphone lul
i can test android device if you want tho
I mean I can send my friends the apk thats not the thing
I just tested it, you're right .. it doesn't
But you don't need to be in simulator to test this.. just change to game view (or have both open)
if you have an IOS device and a mac try the xcode simulator to test your app
if you plan on release to iOS you need it at some point 😛
I’ll do it later when the internet is better
I mean the only reason I didn’t download xcode is because
It is harder to distribute my friends the game via whatsapp or whatever
aint no way to do that anyway
I don’t even know if I can send the .ipa file and they could open it
It's much easier to just use TestFlight
Cuz it works with apk this way
apple says no to sideloading
Yes this
unless you use cydia impactor or something similar
You can sideload ipa's
Don’t you need to open a developer acc for that
Yes
How?
You need a dev account to share anyway. You can't make a shareable IPA without a dev account, all you can do is build to a local device
None of my friends with iphone has their phones jailbroken
Haven't had to do it in years, used to just be able to do it via iTunes.
impactor isn't just for jailbroken, it would work sideloading IPA . but its gray area of legality
oh says on site, as of 2019 its broken and only works only using the dev license. RIP
Wdym build to a local device
You mean with itunes?
a local device... a device you have locally with you.. physically ...
When I cba with TestFlight I use - https://www.diawi.com/
We're wildly off topic for this chan now
Ur talking about building ipa and using an emulator?
Yea nvm I got my answers ty
xcode lets you test on your local device but you can't distribute without Apple Dev license
No, otherwise I would have said something close to that 😄
Without a Dev account, XCode can only build directly to a device you have connected
Ok I didn’t know about this ty
hmm does anyone know why my sprites vanish when i change their shader? only happens on some levels and not others
Can i make a unity toolkit ui worldspace?
thank you
Thank you!
for further questions, #🧰┃ui-toolkit
hello lads, I've encounted a problem and requires assistantance!
I'm trying to get the raycast of camera.forward to spawn an object at its' max raycast distance if it does not hit anything at all, is there a way to achieve this?
yes
thank you!
Or, origin + direction * maxDistance is the "end point" of the ray
yea much simpler ☝️
assuming direction is normalized
that's actually a cool work around
It's not a workaround, that's how you do it
oh right, my bad for the wording
you are forgiven
I have ui code updating some TextMeshProUGUI elements. And now adding code to replace tokens with button prompts, (and in the future handle translations). I have some global events for when the input type is switched or language is changed, now I wonder if there's a way to somehow hook up to the tmp element's .text property getting assigned?
(I guess I could just have a "convention" that every time I assign text I run it through some code)
yeh you could keep a list of them, and check if current text == originaltext, set new text
looks like i have a script on every text that can be translated, and a bool like isScoreText, which u tick, and then it knows it has to grab the translation of the score text
for example if (incomingNuke){ t.text = RSL_LanguageCollector.getFromCache(INCOMING_NUKE); return;}
then u find them all call method to update the text
How do I make those gear interactions like shown in this video?
https://www.youtube.com/watch?v=KBEhmKxEvfQ
Welcome to our exciting tutorial on "Developing a Candy Crush Style Game in Unity 2D (2024)"! In this video, we'll guide you through the entire process of creating your very own match-3 puzzle game inspired by the popular Candy Crush saga. Whether you're a beginner looking to dive into game development or an experienced developer wanting to expa...
quite a lot going on, they must all be separate sprites with anims
how do I create that animation with all the gear components changing? and how does the swiping work here?
looks like it will be explained in that tut
its not a tut, just a gameplay
ah dont know then, either in unitys anim tools or using an artist 🙂
THANKS EVERYONE WHO HELPED ME. FIGURED IT OUT AND WAS ABLE TO MAKE THE CODE THAT I NEEDED
is there a way to override (or block) the parameterless constructor of a struct?
here's my issue
my workaround is this
but doing something like
new HexGrid()
doesn't actually use that constructor, it uses the default 0 parameter one that sets all variables to their default
and I want to set some variables when calling that constructor with 0 parameters
so I need to call new HexGrid(0) to get my desired constructor but that's silly
no, unity's version of c# does not allow declaring a parameterless constructor on a struct
yea but that's infuriating, is there seriously no actual way to deal with this properly?
do I REALLY have to wait till unity 7 for this to be properly fixed?
insane
there is not because a parameterless ctor on a struct is supposed to create an instance of the struct with all of its bits at 0 (meaning all of its fields are at their default value)
well it's clearly not "supposed" to do that if they fixed it in the next version, not letting me override it is annoying
annoying as hell but I guess I can't do anything about it
or is there a way to like disable that constructor
parameterless constructor
c# went 20 years without being able to declare a parameterless constructor. i'd say "supposed to" is accurate
It's a year old feature in a 24yr old language
it went 20 years with a design oversight that was later fixed I dunno what you mean
c++ has it since forever
there is a simple way to solve this problem, dont use c# if you don't like it
ehhhh there we go
Believe it or not language designers have multiple competing priorities and this one just wasn't that important
it wasn't a design oversight, it was exactly what i said. structs were initialized with their default values in all fields with the parameterless constructor. if you want to declare a constructor then it must not be a parameterless one. until unity 7 with the .net modernization
I guess I just have to deal with it until unity 7 brings us sanity
You could just write a static method and use that
It's really not a big deal
that's annoying
I'll just put a pointless zero in my new HexGrid(0) calls
¯_(ツ)_/¯
it's actually quite nice in my opinion, it's my preference too - named something like, e.g HexGrid.CreateNew(); or HexGrid.CreateDefault(); , I feel it makes it a bit more clear what your intent is without the odd irrelevant parameter
but it's just syntax preference
It's a very common practice, nothing annoying about it
Like, some languages don't even have constructors and they get along just fine. For example Go.
never even noticed c# not allowing empty constructor
Also, even better; make a static property + field that represents the "default" value here. Considering you don't have parameters it makes no sense to create a new instance every time. If it's mutable, then have the property return a new instance every time
This is even more common
it's only structs that cannot have a parameterless ctor and only c# 9 and below
ah that explains it, i never use structs
argh i tweaked something and platforms all changed in every level wtf.
if you modify a prefab, then all of the instances of that prefab will also change unless what you modified was overridden by an instance. then it won't change on that instance
